diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 86226ef..89035a2 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -9,17 +9,21 @@ permissions: contents: read jobs: - check: + swift: runs-on: macos-26 env: DEVELOPER_DIR: /Applications/Xcode_26.6.app/Contents/Developer steps: - uses: actions/checkout@v4 - - uses: actions/setup-go@v5 - with: - go-version-file: go.mod - - name: Check - run: make check + - name: Lint + run: make swift-lint + - name: Test + run: make swift-test + - name: Dependency audit + run: make verify-deps + + - name: App sources + run: make app-check - name: Build app run: VERSION=0.0.0 BUILD_NUMBER="$GITHUB_RUN_NUMBER" make app - name: Verify app diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index d09aaa7..830a4c1 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -1,67 +1,40 @@ name: release +# Publishes the Swift CLI built with the Xcode toolchain alone. This fork does not +# publish the Go build or a Homebrew bottle: those belong to upstream +# (github.com/mobai-app/simslim) and its tap. + on: push: tags: ["v*"] - workflow_dispatch: - inputs: - tag: - description: Existing release tag to add a Homebrew bottle to - required: true - type: string - -env: - SIMSLIM_RELEASE_TAG: ${{ inputs.tag || github.ref_name }} permissions: contents: write +env: + DEVELOPER_DIR: /Applications/Xcode_26.6.app/Contents/Developer + SIMSLIM_RELEASE_TAG: ${{ github.ref_name }} + jobs: release: - runs-on: macos-15 + runs-on: macos-26 steps: - uses: actions/checkout@v4 - - uses: actions/setup-go@v5 - with: - go-version-file: go.mod + - name: Test + run: | + cd swift + swift test - name: Build - if: github.event_name == 'push' run: | SIMSLIM_VERSION="${SIMSLIM_RELEASE_TAG#v}" - go test ./... - go build -ldflags "-X main.version=${SIMSLIM_VERSION}" -o simslim ./cmd/simslim + printf '// Copyright (c) 2026 Pavel Akhrameev (Swift port). MIT License; see LICENSE.\n\npublic let simslimVersion = "%s"\n' \ + "${SIMSLIM_VERSION}" > swift/Sources/SimSlimKit/Version.swift + (cd swift && swift build -c release) + cp swift/.build/release/simslim simslim codesign --force --sign - simslim + test "$(./simslim --version)" = "simslim ${SIMSLIM_VERSION}" tar -czf "simslim-${SIMSLIM_RELEASE_TAG}-macos-arm64.tar.gz" simslim - shasum -a 256 "simslim-${SIMSLIM_RELEASE_TAG}-macos-arm64.tar.gz" - - name: Build Homebrew bottle - run: | - SIMSLIM_SOURCE_URL="https://github.com/${GITHUB_REPOSITORY}/archive/refs/tags/${SIMSLIM_RELEASE_TAG}.tar.gz" - SIMSLIM_SOURCE_TARBALL="${RUNNER_TEMP}/simslim-source.tar.gz" - SIMSLIM_BUILD_TAP="mobai-app/simslim-release" - - curl --fail --location --retry 3 "${SIMSLIM_SOURCE_URL}" --output "${SIMSLIM_SOURCE_TARBALL}" - SIMSLIM_SOURCE_SHA256="$(shasum -a 256 "${SIMSLIM_SOURCE_TARBALL}" | cut -d ' ' -f 1)" - - brew tap-new --no-git "${SIMSLIM_BUILD_TAP}" - SIMSLIM_FORMULA="$(brew --repository "${SIMSLIM_BUILD_TAP}")/Formula/simslim.rb" - mkdir -p "$(dirname "${SIMSLIM_FORMULA}")" - sed \ - -e "s|@SOURCE_URL@|${SIMSLIM_SOURCE_URL}|g" \ - -e "s|@SOURCE_SHA256@|${SIMSLIM_SOURCE_SHA256}|g" \ - packaging/homebrew/simslim.rb.in > "${SIMSLIM_FORMULA}" - - brew install --build-bottle "${SIMSLIM_BUILD_TAP}/simslim" - brew test "${SIMSLIM_BUILD_TAP}/simslim" - brew bottle \ - --json \ - --no-rebuild \ - --root-url "https://github.com/${GITHUB_REPOSITORY}/releases/download/${SIMSLIM_RELEASE_TAG}" \ - "${SIMSLIM_BUILD_TAP}/simslim" - - # brew uses a double dash locally; custom HTTP bottle URLs use one. - for SIMSLIM_BOTTLE in simslim--*.bottle*.tar.gz; do - mv "${SIMSLIM_BOTTLE}" "${SIMSLIM_BOTTLE/--/-}" - done + shasum -a 256 "simslim-${SIMSLIM_RELEASE_TAG}-macos-arm64.tar.gz" | tee "simslim-${SIMSLIM_RELEASE_TAG}-macos-arm64.tar.gz.sha256" - name: Release uses: softprops/action-gh-release@v2 with: @@ -69,4 +42,4 @@ jobs: generate_release_notes: true files: | simslim-*-macos-arm64.tar.gz - simslim-*.bottle*.tar.gz + simslim-*.sha256 diff --git a/.gitignore b/.gitignore index efd9a05..c04a447 100644 --- a/.gitignore +++ b/.gitignore @@ -3,3 +3,5 @@ *.tar.gz .DS_Store /build/ +/swift/.build/ +.vscode/ diff --git a/CLAUDE.md b/CLAUDE.md index d7432d7..62f2574 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -5,86 +5,92 @@ This file provides guidance to Claude Code (claude.ai/code) when working with co ## What this is simslim runs many more iOS, tvOS, watchOS, and visionOS simulators on one Mac by disabling the background -daemons a simulator doesn't need, cutting each simulator's memory ~4x. It is a Go -CLI plus a SwiftUI macOS app that wraps it. Everything is driven through -`xcrun simctl`; the tool only ever touches the simulators you point it at, never -the host Mac. macOS-only. +daemons a simulator doesn't need, cutting each simulator's memory ~4x. It is a dependency-free Swift CLI, +built with the Xcode toolchain alone, plus a SwiftUI macOS app that wraps it. Everything is driven through +`xcrun simctl`; the tool only ever touches the simulators you point it at, never the host Mac. macOS-only. + +This repository was originally an independent Swift port of [MobAI's simslim](https://github.com/mobai-app/simslim) +(Go); the port reached parity and the Go tree was removed. See +[docs/remove-go.md](docs/remove-go.md) for how, and +[docs/parity-check.md](docs/parity-check.md) for how the ported behavior was checked against the Go +reference, tagged `go-reference-final`. ## Commands ```sh -go build ./cmd/simslim # build the CLI -go test ./... # run all tests (Makefile: make test) -go test -run TestName ./... # run a single test -make check # full CI gate — must pass before a PR -make format # gofmt + swift-format (run before committing) -make app # build build/SimSlim.app (Go + swiftc, macOS only) +make swift-lint # swift-format --strict over swift/Sources and swift/Tests +make swift-test # cd swift && swift test +make verify-deps # system modules only, no network symbols, no third-party libs +make app-check # gui swift-format lint, build-app.sh syntax, Info.plist lint +make app # build build/SimSlim.app (swiftc + swift build, macOS only; no Go) open build/SimSlim.app +make format # swift-format over gui/ and swift/ (run before committing) ``` -`make check` runs `go test`, `go vet`, `swift-format lint --strict --recursive gui`, -`zsh -n scripts/build-app.sh`, and `plutil -lint gui/Info.plist`. CI (`.github/workflows/ci.yml`) -runs exactly this on macos-26 / Xcode 26.6, then builds and verifies the app bundle. +CI (`.github/workflows/ci.yml`) runs lint, tests, the dependency audit, `app-check`, and the app build and +bundle verification, all in one job on macos-26 / Xcode 26.6. Tests are pure unit tests (parsing, delta logic, allowlist invariants) — they do **not** boot real simulators, so they run anywhere. Only the app build and manual runs need Xcode + an iOS runtime. +Go-vs-Swift parity checks (`scripts/parity.sh`) still exist for regression-checking against the last Go +build (tag `go-reference-final`, built from a sibling worktree) and need a Go toolchain only to run that +script; see [docs/parity-check.md](docs/parity-check.md#prerequisite-check-go-toolchain) for which checks to +run when Go is and isn't available — never install Go just to make that check pass. + ## Architecture -Two packages. The repo root is `package simslim`, an importable library holding -every piece of slimming logic and **no external dependencies**. `cmd/simslim/` -is `package main`, the CLI: `main.go` dispatches `os.Args[1]` to a `cmd*` -function per subcommand and enforces macOS-only up front. +Two targets under `swift/`: `SimSlimKit` is the importable library holding every piece of slimming logic +and **no external dependencies**; `SimSlimCLI` is the command layer, invoked by the tiny +`swift/Sources/simslim/main.swift` executable. `CLI.run(_:)` (`SimSlimCLI/CLI.swift`) dispatches each +subcommand to a `cmd*` function (`SimSlimCLI/Commands.swift` and friends) and enforces macOS-only up front. -Anything that talks to a terminal — printing, `--json` encoding via `writeJSON`, -the interactive wizard in `wizard.go`, `fatal()`, `usage()` — lives in -`cmd/simslim/`. The library never writes to stdout; it returns values and +Anything that talks to a terminal — printing, `--json` encoding, the interactive wizard +(`WizardModel.swift`/`WizardTerminal.swift`), `top`'s live screen (`TopCommand.swift`/`TopModel.swift`/ +`TopTerminal.swift`) — lives in `SimSlimCLI`. The library never writes to stdout; it returns values and reports progress through the `Reporter` callback the caller supplies. -Exported identifiers in the root package are the public API, so renaming one is -a breaking change for importers as well as for the CLI. - -**The slimming model (the core idea).** `profiles.go` defines `Categories`, an -allowlist of launchd daemon labels grouped by user-facing feature (siri, search, -icloud, …). Categories may overlap — a label lives in every category whose -feature needs it (e.g. the AMS payment-sheet daemons are in both `store` and -`icloud`), and `Profile.Desired()` keeps a label enabled when **any** excepted -category lists it. `SlimmableSet()` is the deduplicated union of every label in -`Categories`. -`managedSet()` adds each category's `AlwaysEnabled` compatibility services, +Public identifiers in `SimSlimKit` are its API, so renaming one is a breaking change for importers as well +as for the CLI. + +**The slimming model (the core idea).** `Catalog.swift` defines `Catalog.categories`, an allowlist of +launchd daemon labels grouped by user-facing feature (siri, search, icloud, …), plus the +`Generated/CatalogData.swift` seed data (hand-maintained now; the folder name is historical). Categories may overlap — a label lives in every category whose +feature needs it (e.g. the AMS payment-sheet daemons are in both `store` and `icloud`), and +`Profile.desired()` keeps a label enabled when **any** excepted category lists it. `Catalog.slimmableSet` is +the deduplicated union of every label in `Catalog.categories`. +`Catalog.managedSet` adds each category's `alwaysEnabled` compatibility services, which simslim may only repair back to enabled; these are **the only labels the tool may ever disable or enable.** Anything outside those sets is never touched. -`service_descriptions.go` supplies the short per-daemon explanations shown by -the GUI; its coverage and length are enforced in `profiles_test.go`. -`profile_file.go` loads a committed JSON profile (`simslim on --profile `) +`ProfileFile.swift` loads a committed JSON profile (`simslim on --profile `) whose `except`/`keep` arrays mirror the flags of the same name, validates it -against the allowlist, and resolves it to a `Profile`. The dependency-free -`profile` command's interactive wizard lives in `cmd/simslim/wizard.go`. -`features.go` defines `Features`, a finer-grained catalog than `Categories`: +against the allowlist, and resolves it to a `Profile`. The `profile` command's interactive wizard lives in +`WizardModel.swift`/`WizardTerminal.swift`. +`Features.swift` defines `Catalog.features` (data in `featureList`), a finer-grained catalog than `Catalog.categories`: each feature (push, storekit, universal-links, …) names just the daemons one testable capability needs. `doctor` reads a booted simulator's disabled labels and reports any required feature whose daemons are down, exiting non-zero — a CI -preflight. `features_test.go` asserts every feature label is managed, including +preflight. `FeaturesTests.swift` asserts every feature label is managed, including required services that earlier versions could have disabled. -`slim.go`'s `ensure()` rejects a non-empty slim profile on runtimes older than +`Slim.swift`'s `ensure()` rejects a non-empty slim profile on runtimes older than iOS/tvOS 18.5, watchOS 11.5, or visionOS 2.5 before booting or mutating the device, then reads the currently disabled labels, computes a `delta` against the desired set, and applies the changes with `launchctl disable/enable` run inside the simulator via `simctl spawn`, a pool of `spawnWorkers` (8) at a time. It reboots and reads the state back before reporting persistence. `on` disables the profile; `off` remains available on every runtime and re-enables the whole managed set. -`Profile.DesiredForDevice` keeps `com.apple.homed` enabled on watchOS, which +`Profile.desired(for:)` keeps `com.apple.homed` enabled on watchOS, which re-enables that service after startup, and `com.apple.mobileassetd` on visionOS, whose simulated surroundings are mobile assets. Slimming, verification, and per-device -status totals use this platform-specific profile; `Profile.Desired` remains the -platform-independent catalog for profile editors. `Device.Platform` identifies +status totals use this platform-specific profile; `Profile.desired()` remains the +platform-independent catalog for profile editors. `Device.platform` identifies iOS, tvOS, watchOS, or visionOS (CoreSimulator's `xrOS` runtimes); an empty platform defaults to iOS for library callers. -`EnableSlimNoReboot` (`on --no-reboot`) skips the reboot: it runs `launchctl +`enableSlimNoReboot` (`on --no-reboot`) skips the reboot: it runs `launchctl disable` + `launchctl bootout` per label so the daemon stops in the current boot session, which is the only slimming possible on runtimes older than iOS 18.5. Before that per-label pass, `unloadInBatch` stops most labels at once: it finds -each label's job plist under the runtime's RuntimeRoot (`Device.RuntimeID` → +each label's job plist under the runtime's RuntimeRoot (`Device.runtimeID` → `runtimeRoot`, used only when the plist's own `Label` matches) and passes them to one `launchctl unload -w` per 64 plists, which writes the same override as `disable` and removes the job like `bootout`. It then reads `print-disabled` and @@ -92,7 +98,7 @@ one `launchctl unload -w` per 64 plists, which writes the same override as per-label path; any failure in the batch just means more labels do. **The offline fast path.** On a runtime with persistent overrides `ensureOffline` -takes over: `disabled_store.go` writes the overrides directly and boots the +takes over: `DisabledStore.swift` writes the overrides directly and boots the device once, already slim, skipping every `launchctl` spawn *and* the reboot that would apply them (measured 2m14s → 33s for 170 labels). A **booted** device gets there too — an override only takes effect at the next boot, so `ensure` reads its @@ -107,57 +113,56 @@ only by UDID. It is an undocumented CoreSimulator detail, so treat it as best-effort: writes **merge** (the runtime keeps its own explicit-enable entries there, and unmanaged labels are never simslim's business), the booted device is always read back with `print-disabled` rather than trusted, and anything that -does not work out returns `errOfflineIneffective` so `ensure` falls back to the +does not work out throws so `ensure` falls back to the `launchctl` path. A store problem must never surface as a command failure. -`watch.go` uses the same store to slim a shut-down device before it boots +`Watch.swift` uses the same store to slim a shut-down device before it boots (`preslimDevice`): it only adds the profile's disables, to every shut-down device on startup. A kqueue `NOTE_WRITE` watch on each device-set directory -(`watch_dirs_darwin.go`, re-attached each scan interval while a set directory is -missing) seeds a new device from its `device.plist` in its own goroutine -(`seedNew`), since a `simctl list` on a loaded host takes longer than a script -waits between `simctl create` and boot. A boot that starts first is logged and +(`DirWatcher.swift`, re-attached each scan interval while a set directory is +missing) seeds a new device from its `device.plist` within milliseconds of `simctl create`, +without waiting for `simctl list`. A boot that starts first is logged and caught by the no-reboot slim at boot, which stays as the read-back and fallback. -Each boot's after-boot pass has its own cancel (`slimPass`), called when the +Each boot's after-boot pass has its own cancel (`Watcher.Pass.cancel()`), called when the device shuts down or is deleted, so a pass never retries into the next boot; a -superseded pass reports `stopped`, never `slimmed`. `WatchWithEvents` emits +superseded pass reports `stopped`, never `slimmed`. `Watcher.run` emits `WatchEvent`s, which `watch --json` prints one per line as a stable contract. -**Live enable/disable.** `live.go` holds `EnableServices`/`DisableServices` +**Live enable/disable.** `Live.swift` holds `enableServices`/`disableServices` (`simslim enable`/`disable`), which act on a booted simulator only and keep no state, like `on --no-reboot`: the profile stays the only description of a slim -simulator. `startServices` runs one `launchctl load -w` per chunk via -`loadJobs`, then per-label `enable` and `bootstrapJobs` for what is left; +simulator. `startServices` runs one `launchctl load -w` per chunk, then per-label `enable` +and `bootstrapJobs` for what is left; `stopServices` is the unload/disable/bootout path `on --no-reboot` uses. Everything is read back; a label that loads only at the next boot is reported in `notStarted`, not as an error. `disable` keeps a label a named category shares with another category whose labels are all enabled right now (`enabledNeighbours`), and reports it in `stillEnabled`; a label named on its own is always stopped. A simulator that is not booted is an error unless -`--save` is given. `profile_save.go`'s `SaveServices` (`--save `) adds or +`--save` is given. `ProfileSave.swift`'s `saveServices` (`--save `) adds or removes categories in a profile file's `except` and labels in its `keep`, keeping order and other fields, skipping duplicates, starting a missing file from the default (empty) profile, and writing atomically; the file is validated first and written only after the live change succeeded. Launchd reads (`readLaunchd`) retry launchd_sim's error 124 ("Domain is tearing down", answered for a few seconds around a boot or reboot) and an attempt that ran out -of `SpawnTimeout`, on `launchdRetryDelays`, and nothing else; later -`applyDelta` passes pause on the same delays. Reads and per-label -transitions go through `launchctlCmd`, whose `WaitDelay` abandons the output -pipe a killed xcrun's simctl child would otherwise hold open forever. +of `spawnTimeout`, on `retryDelays`, and nothing else; later +slimming passes pause on the same delays. Reads and per-label +transitions go through `Subprocess`, whose `waitDelay` abandons the output +pipe a killed `xcrun`'s simctl child would otherwise hold open forever. -**simctl wrapper.** `simctl.go` is the only place that shells out to -`xcrun simctl` (list/boot/shutdown/clone/erase/delete/spawn). `measure.go` sums +**simctl wrapper.** `Simctl.swift` is the only place that shells out to +`xcrun simctl` (list/boot/shutdown/clone/erase/delete/spawn). `Measure.swift` sums `phys_footprint` across the simulator's launchd process tree (via `pgrep`/`ps`/`top`) -— that's the memory figure that decides how many simulators fit. `MeasureProcesses` +— that's the memory figure that decides how many simulators fit. `measureMany` keeps the per-process detail (footprint + cpu, from the same snapshot) for the -`top` drill-down. `fleet.go`'s `FleetSnapshot` composes booted devices + slim -status + `MeasureMany` into the fleet view; the live TUI is `cmd/simslim/top.go` -(Bubble Tea), which also has a `--json`/non-TTY one-shot fallback. `disk.go`, -`disk_cleanup.go`, and `disk_inventory.go` handle disk measurement and the -separate, permanent disk-cleanup feature. +`top` drill-down. `Fleet.swift`'s `fleetSnapshot` composes booted devices + slim +status + measurements into the fleet view; the live TUI is `SimSlimCLI/TopCommand.swift` +plus `TopModel.swift`/`TopTerminal.swift` (plain ANSI redraw, no library), which also has a +`--json`/non-TTY one-shot fallback. `DiskCleanup.swift` and its supporting files handle disk measurement +and the separate, permanent disk-cleanup feature. **JSON is a contract.** Every read-only and management command supports `--json`. -The structs in `output.go` (`DeviceSummary`, `StatusOutput`, +The structs in `Output.swift` (`DeviceSummary`, `StatusOutput`, `SimulatorMutationOutput`, `ServicesOutput`, etc.) plus the category/plan structs are the stable interface the SwiftUI app decodes. Changing a JSON field breaks the GUI in `gui/*.swift` — keep them in sync. `gui/Backend.swift` @@ -165,16 +170,18 @@ invokes the bundled CLI with `--json` and decodes these types; there is no other IPC. **The SwiftUI app** (`gui/`) has no Xcode project. `scripts/build-app.sh` compiles -the Swift sources directly with `swiftc`, cross-builds the Go CLI, bundles it into +the Swift sources directly with `swiftc`, builds the CLI with `swift build` (stamping the version into +`swift/Sources/SimSlimKit/Version.swift` for the build, then restoring the file), bundles it into `SimSlim.app/Contents/Resources/simslim`, generates the icon, and ad-hoc codesigns. The app is a thin front end that shells out to that bundled binary. ## Safety invariants — preserve these -- **Never add a deadlock-prone daemon to `Categories`.** A handful of daemons wedge - a simulator when disabled. `profiles_test.go` holds a `forbiddenLabels` list and +- **Never add a deadlock-prone daemon to `Catalog.categories`.** A handful of daemons wedge + a simulator when disabled. `ProfilesTests.swift` holds a `forbiddenLabels` list + (`swift/Tests/SimSlimKitTests/Generated/ForbiddenLabels.swift`) and asserts none appear in any category; if you add labels, keep that test green. -- **Only managed labels are ever mutated.** `delta()` is scoped to `managedSet()` +- **Only managed labels are ever mutated.** `delta()` is scoped to `Catalog.managedSet` on both sides. Compatibility labels are omitted from every desired slim state, so they can only be repaired to enabled. - **Destructive/management commands resolve the exact UDID first** (`findDevice` / @@ -187,26 +194,27 @@ The app is a thin front end that shells out to that bundled binary. ## Conventions -- CLI parsing uses `github.com/urfave/cli/v3`; the `top` command's live TUI uses - `github.com/charmbracelet/bubbletea` + `lipgloss`. These are the CLI's only - dependencies — the root library still has none, so importers never inherit a - terminal stack. The command tree lives in `cmd/simslim/app.go` (`newApp`); - each subcommand's `Action` is a `cmd*` function in `cmd/simslim/main.go` that - reads flags via `cmd.Bool/String(...)` and positionals via `cmd.Args()`. Flags may appear before or after positional args - (e.g. `simslim on --except search`) — v3 parses flags anywhere by default. - `--set` is a global flag (inherited by every subcommand) registered in its flag - `Action`. `main.go` still owns `version`/`help`/no-args and the macOS-only guard - before handing off to the tree, and routes every command error through `fatal()` - for the stable `simslim: ` (exit 1); unknown commands exit 2 with usage. -- Two timeouts live in `simctl.go`: `ShutdownTimeout` (30s, a const) and `BootTimeout` - (10min, because a first slim reconfigure boots twice). `BootTimeout` is a package var, - not a const, so the CLI's global `--boot-timeout` flag (env `SIMSLIM_BOOT_TIMEOUT`, - wired in `app.go` like `--set`) can raise it for slow CI runners where the per-daemon - `launchctl` transitions would otherwise blow the deadline mid-reconfigure. +- The CLI has no third-party dependencies; its own flag parser lives in `SimSlimCLI/Arguments.swift`, with + each command's flags declared in `CLI.commandSpecs` (`CLI.swift`). Flags may appear before or after + positional args (e.g. `simslim on --except search`). `--set`, `--boot-timeout`, and + `--spawn-timeout` are global flags (`CLI.globalSpecs`). `CLI.run(_:)` owns `version`/`help`/no-args and + the macOS-only guard before dispatching to a `cmd*` function, and routes every command error through a + shared `simslim: ` formatter (exit 1); unknown commands exit 2 with usage. +- Two timeouts: `Simctl.shutdownTimeout` (30s, `Lifecycle.swift`) and the boot timeout (10min default, + because a first slim reconfigure boots twice), resolved in `SimSlimCLI/CLI.swift` from the global + `--boot-timeout` flag (env `SIMSLIM_BOOT_TIMEOUT`) and passed down as a parameter, so slow CI runners can + raise it where the per-daemon `launchctl` transitions would otherwise blow the deadline mid-reconfigure. - Progress for multi-minute operations goes to **stderr** via the `Reporter` callback; machine-readable JSON goes to **stdout**. Under `--json`, suppress the stderr chatter so consumers reading a combined stream still get clean JSON. -- Memory estimates (`ApproxMemoryMB`) are iOS-26.5 clean-boot medians and are +- Every Swift file starts with `// Copyright (c) 2026 Pavel Akhrameev (Swift port). MIT License; see LICENSE.` + (`Package.swift`: the line after `swift-tools-version`). The files under `Generated/` carry + `// swift-format-ignore-file` on line 1 and the copyright on line 2. +- `Generated/` is edited by hand now (the generator went with the Go tree). `ProfilesTests` and + `FeaturesTests` are its only guard: they enforce the forbidden-label list, managed/unmanaged invariants, + and that every daemon has a short description (`testEveryServiceHasShortDescription`, + `serviceDescriptionByLabel`). Keep them green when editing the catalog. +- Memory estimates (`approxMemoryMB`) are iOS-26.5 clean-boot medians and are **not additive**. Every category must have a positive measured estimate. ## Git diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md new file mode 100644 index 0000000..c9985ed --- /dev/null +++ b/CONTRIBUTING.md @@ -0,0 +1,24 @@ +# Contributing + +## Before you commit + +```sh +make format # swift-format over gui/ and swift/ (rewrites files) +make app-check # gui swift-format lint --strict, build-app.sh syntax, Info.plist lint +make swift-lint swift-test verify-deps +``` + +CI runs the app-check, Swift lint, test and deps-audit steps in one job (not `make format`, which rewrites files). None of them need a Go toolchain — the Go reference implementation was +removed; see [docs/remove-go.md](docs/remove-go.md). The only thing that still wants Go is +`scripts/parity.sh`, a regression check against the last Go build (tag `go-reference-final`); see +[docs/parity-check.md#prerequisite-check-go-toolchain](docs/parity-check.md#prerequisite-check-go-toolchain) +for what to run instead when Go isn't available. Never install Go just to satisfy a check; its absence is a +valid environment. + +## Changing the mutating core + +Changing the slim engine (`Slim.swift`), `Live.swift`, `DisabledStore.swift`, `ProfileSave.swift`, or any +destructive command deserves extra care and, ideally, a parity run against the Go reference; see +[docs/parity-check.md](docs/parity-check.md). + +See [CLAUDE.md](CLAUDE.md) for the full architecture notes and safety invariants. diff --git a/LICENSE b/LICENSE index f450b9c..a3e5053 100644 --- a/LICENSE +++ b/LICENSE @@ -1,6 +1,7 @@ MIT License Copyright (c) 2026 Interlap +Copyright (c) 2026 Pavel Akhrameev (Swift port) Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal diff --git a/Makefile b/Makefile index 36a43ac..6d98d27 100644 --- a/Makefile +++ b/Makefile @@ -1,22 +1,23 @@ -.PHONY: app cli check format test - -VERSION ?= $(shell git describe --tags --always --dirty) - -cli: - go build -ldflags "-X main.version=$(VERSION)" -o simslim ./cmd/simslim +.PHONY: app app-check format swift-lint swift-test verify-deps app: ./scripts/build-app.sh -test: - go test ./... - -check: test - go vet ./... +# App sources and build script gate. +app-check: xcrun swift-format lint --strict --recursive gui zsh -n scripts/build-app.sh plutil -lint gui/Info.plist format: - gofmt -w *.go - xcrun swift-format format --in-place --recursive gui + xcrun swift-format format --in-place --recursive gui swift/Sources swift/Tests + +swift-lint: + xcrun swift-format lint --strict --recursive swift/Sources swift/Tests + +swift-test: + cd swift && swift test + +# Dependency audit of the Swift port (system modules only, no network, no third-party libs). +verify-deps: + ./scripts/verify-deps.sh diff --git a/README.md b/README.md index 6666f14..4988879 100644 --- a/README.md +++ b/README.md @@ -1,5 +1,29 @@ # simslim +> **This repository is an independent Swift port of [MobAI's simslim](https://github.com/mobai-app/simslim). +> It is not the official project and is not meant to be merged upstream.** +> +> Many thanks to the original authors at [MobAI](https://mobai.run) (Interlap) for simslim itself: the +> daemon allowlist, the offline `disabled.plist` fast path, the measurements, and the design this port follows. +> +> **Why a port.** To use fewer technologies for the same result. The original CLI is written in Go; the CLI +> in [`swift/`](swift) builds with the Xcode toolchain alone, which any Mac that runs the Simulator already has. +> It has no Go toolchain, no third-party packages and no network access, and +> [`scripts/verify-deps.sh`](scripts/verify-deps.sh) checks that. +> +> **Status.** The port is complete: every command, the `--json` contract, and the safety invariants carry +> over, the macOS app bundles the Swift CLI, and the Go tree has been removed from this repository (see +> [docs/remove-go.md](docs/remove-go.md)). [`scripts/parity.sh`](scripts/parity.sh) remains as a +> regression check against the last Go build, tagged `go-reference-final`: it runs the same commands +> through both CLIs on real simulators and diffs the output. A full run (read-only, `--mutating` on a +> scratch simulator, and `--watch`) found no behavioral differences on the paths it covers. That is not a +> proof of full parity: live measurements are compared by shape, and the known, deliberate differences +> (including a run-order effect in `watch`) are listed in [docs/parity-check.md](docs/parity-check.md). +> +> **Upstream.** The Homebrew tap `mobai-app/tap` and `go install github.com/mobai-app/simslim` install +> upstream's Go version, not this port. Report problems with this Swift build here and problems with the Go +> version upstream. + Run a lot more iOS, Apple TV (tvOS), Apple Watch (watchOS), and Apple Vision Pro (visionOS) simulators on one Mac by turning off the background daemons a simulator doesn't need. A freshly booted iOS simulator starts around 180 background services: Siri, Spotlight indexing, photo analysis, News, wallpaper posters, iCloud sync, and so on. None of it matters when you're using the simulator for development, testing, or CI. simslim switches those services off, which cuts each simulator's memory roughly 4x. On the same laptop you go from a handful of simulators to a screenful. @@ -29,15 +53,46 @@ shared mappings once for every process that maps them. ## Install ```sh -brew install mobai-app/tap/simslim +git clone https://github.com/Akhrameev/simslim && cd simslim/swift +swift build -c release +.build/release/simslim --version +``` + +### Prebuilt binary + +Tagged releases attach `simslim--macos-arm64.tar.gz` (Apple Silicon only) and its `.sha256` +on the [Releases page](https://github.com/Akhrameev/simslim/releases). The binary is ad-hoc +codesigned, **not** signed with an Apple Developer ID and **not notarized**. A file downloaded +through a browser carries the quarantine flag, and Gatekeeper then refuses to run it. Either +fetch it with `curl`, which does not set the flag: + +```sh +curl -fsSLO https://github.com/Akhrameev/simslim/releases/download//simslim--macos-arm64.tar.gz +tar -xzf simslim--macos-arm64.tar.gz +./simslim --version ``` -or +or clear the flag after a browser download: ```sh -go install github.com/mobai-app/simslim/cmd/simslim@latest +xattr -d com.apple.quarantine simslim ``` +Verify the download against the `.sha256` file with `shasum -a 256 -c`. Building from source +(above) avoids the issue entirely. + +Upstream's original Go build is installed separately, not by this repository: +`brew install mobai-app/tap/simslim` or `go install github.com/mobai-app/simslim/cmd/simslim@latest`. + +### About this build + +It covers every command: `list`, `profiles`, `status`, `verify`, `doctor`, +`measure`, `on`, `off`, `boot`, `shutdown`, `enable`, `disable`, `watch`, +`rename`, `erase`, `delete`, `top`, `size`, `profile`, `clone`, `repair-clone`, +and the `disk-*` commands. `scripts/verify-deps.sh` checks that the Swift code imports only +Apple system modules, uses no network API, and links +only system libraries. + macOS only, and you need Xcode with an iOS, tvOS, watchOS, or visionOS Simulator runtime, since simslim drives simulators through `xcrun simctl`. @@ -74,7 +129,7 @@ The SwiftUI app bundles the CLI and adds: - Read-only disk analysis plus confirmed cleanup of allowlisted data. - Clone, rename, erase, delete, and Finder shortcuts. -Build it locally with Go and Xcode: +Build it locally with Xcode alone (the app bundles the Swift CLI; no Go needed): ```sh make app @@ -404,56 +459,16 @@ Documents, app data, and user media. Those durable rows are never eligible for cleanup. See the [disk cleanup safety model](docs/disk-cleanup.md) for recovery behavior, safeguards, and Xcode 26.6 validation results. -## Use as a Go library - -The repo root is an importable package with no external dependencies, so you can -drive simulators from your own tooling instead of shelling out to the CLI: - -```sh -go get github.com/mobai-app/simslim -``` +## Use as a library -```go -package main - -import ( - "context" - "fmt" - - "github.com/mobai-app/simslim" -) - -func main() { - ctx := context.Background() - - devices, err := simslim.ListDevices(ctx) - if err != nil { - panic(err) - } - - // Slim every booted simulator, keeping Siri and search enabled. - profile, err := simslim.BuildProfile("", "siri,search", "") - if err != nil { - panic(err) - } - for _, d := range devices { - if d.State != "Booted" { - continue - } - changed, err := simslim.EnableSlim(ctx, d.Set, d.UDID, profile, func(msg string) { - fmt.Println(d.UDID, msg) - }) - fmt.Println(d.UDID, "changed:", changed, "err:", err) - } -} -``` +`SimSlimKit` (`swift/Sources/SimSlimKit`) is the importable library behind the CLI, with no external +dependencies, so you can drive simulators from your own Swift tooling instead of shelling out to the CLI — +see [CLAUDE.md](CLAUDE.md#architecture) for its shape. It is not published as a package product and has no +stable, versioned API; today it is an internal target of this repository's package (`swift/Package.swift`), +not something other packages can depend on. -The package never writes to stdout — it returns values and reports progress -through the `simslim.Reporter` callback you pass in. `simslim.Categories`, -`simslim.Features`, and `simslim.SlimmableSet()` expose the same allowlist the -CLI uses; `simslim.EnableServices`, `simslim.DisableServices`, and -`simslim.SaveServices` back `enable`, `disable`, and `--save`. macOS only, -since everything runs through `xcrun simctl`. +Upstream's original Go package (`go get github.com/mobai-app/simslim`) offers the same capability for the +Go build; see [its repository](https://github.com/mobai-app/simslim) for that API. ## How it works @@ -524,4 +539,4 @@ Built for [MobAI](https://mobai.run) to run more simulators on one machine. ## License -MIT, copyright Interlap. +MIT. Copyright Interlap (original simslim) and Pavel Akhrameev (Swift port). See [LICENSE](LICENSE). diff --git a/clone.go b/clone.go deleted file mode 100644 index 9c5bcea..0000000 --- a/clone.go +++ /dev/null @@ -1,882 +0,0 @@ -package simslim - -import ( - "bytes" - "context" - "fmt" - "os" - "os/exec" - "path/filepath" - "sort" - "strconv" - "strings" - "time" -) - -type cloneFilesystem struct { - sourceUDID string - cloneUDID string - sourceDeviceDirectory string - cloneDeviceDirectory string - sourceDataDirectory string - cloneDataDirectory string - sourceLogDirectory string - cloneLogDirectory string -} - -// desiredCloneDisabled copies only labels SimSlim is allowed to disable. A -// source may contain unrelated or obsolete launchd overrides; cloning must not -// turn those into new SimSlim-managed state or propagate an unsafe override. -func desiredCloneDisabled(disabled map[string]bool) map[string]bool { - slimmable := SlimmableSet() - desired := make(map[string]bool) - for label, isDisabled := range disabled { - if isDisabled && slimmable[label] { - desired[label] = true - } - } - return desired -} - -// CloneDevice prepares a point-in-time copy. CoreSimulator's raw clone carries -// absolute source paths in symlinks and generated registries, so the source -// remains shut down until direct links have been rebased, app registrations -// have been rebuilt, the copied SimSlim service profile has been verified, and -// the running clone has been audited for open source paths. Any preparation -// failure deletes the clone rather than returning it as ready. -func CloneDevice(ctx context.Context, udid, name string) (newUDID string, err error) { - name, err = NormalizeSimulatorName(name) - if err != nil { - return "", err - } - - source, sourceDataDirectory, err := simulatorDataDirectory(ctx, udid) - if err != nil { - return "", err - } - if source.State != "Booted" && source.State != "Shutdown" { - return "", fmt.Errorf("simulator must be booted or shutdown before cloning (it is %s)", source.State) - } - sourceWasBooted := source.State == "Booted" - defer func() { - restoreCtx, cancel := context.WithTimeout(context.WithoutCancel(ctx), BootTimeout) - defer cancel() - if restoreErr := restoreCloneSourceState(restoreCtx, source.Set, udid, sourceWasBooted); restoreErr != nil { - switch { - case err != nil: - err = fmt.Errorf("%v; additionally could not restore the source boot state: %w", err, restoreErr) - case newUDID != "": - err = fmt.Errorf("cloned simulator %s, but could not restore the source boot state: %w", newUDID, restoreErr) - default: - err = fmt.Errorf("could not restore the source boot state: %w", restoreErr) - } - } - }() - - // launchctl state can only be read from a fully booted device. A shutdown - // source is booted temporarily, then both source states converge here before - // CoreSimulator copies its files. - if err := BootAndWait(ctx, source.Set, udid); err != nil { - return "", fmt.Errorf("boot source to capture its service profile: %w", err) - } - disabled, err := readDisabled(ctx, source.Set, udid) - if err != nil { - return "", fmt.Errorf("capture source service profile: %w", err) - } - desired := desiredCloneDisabled(disabled) - if err := Shutdown(ctx, source.Set, udid); err != nil { - return "", fmt.Errorf("shutdown source before cloning: %w", err) - } - if err := WaitShutdown(ctx, source.Set, udid, ShutdownTimeout); err != nil { - return "", fmt.Errorf("wait for source shutdown before cloning: %w", err) - } - - out, err := xcrun(ctx, simctlArgs(source.Set, "clone", udid, name)...) - if err != nil { - return "", err - } - createdUDID, err := parseClonedUDID(out) - if err != nil { - return "", err - } - newUDID = createdUDID - cloneIsSafe := false - defer func() { - if cloneIsSafe { - return - } - newUDID = "" - cleanupErr := deleteUnsafeClone(ctx, source.Set, createdUDID) - if cleanupErr != nil { - err = fmt.Errorf( - "prepare cloned simulator %s: %w; additionally could not delete the unsafe clone: %v", - createdUDID, - err, - cleanupErr, - ) - return - } - err = fmt.Errorf("prepare cloned simulator %s: %w; deleted the unsafe clone", createdUDID, err) - }() - - paths, err := cloneFilesystemFor(ctx, source, sourceDataDirectory, createdUDID) - if err != nil { - return "", err - } - if err := sanitizeClonedDeviceAt(paths); err != nil { - return "", err - } - - // Enforce the captured state instead of trusting a copied launchd database. - // ensure also clears any required-to-run label that happened to be disabled - // in the source, and verifies persistence across a reboot when it changes. - if _, err := ensure(ctx, source.Set, createdUDID, desired, nil); err != nil { - return "", fmt.Errorf("restore cloned service profile: %w", err) - } - if err := verifyRunningCloneDoesNotOpenSource(ctx, paths); err != nil { - return "", err - } - if err := Shutdown(ctx, source.Set, createdUDID); err != nil { - return "", fmt.Errorf("shutdown prepared clone: %w", err) - } - if err := WaitShutdown(ctx, source.Set, createdUDID, ShutdownTimeout); err != nil { - return "", fmt.Errorf("wait for prepared clone shutdown: %w", err) - } - if err := verifyCloneIndependence(paths); err != nil { - return "", err - } - - cloneIsSafe = true - return createdUDID, nil -} - -// RepairClonedDevice removes direct filesystem links and open paths into the -// supplied source from a clone made by an older SimSlim version. CoreSimulator -// does not expose clone lineage, so callers must supply the actual source UDID. -// It preserves the target's apps, app data, settings, SimSlim profile, and -// original boot state. A failed repair leaves the target shutdown. -func RepairClonedDevice(ctx context.Context, sourceUDID, cloneUDID string) (err error) { - if sourceUDID == cloneUDID { - return fmt.Errorf("clone source and destination UDIDs must be distinct") - } - source, sourceDataDirectory, err := simulatorDataDirectory(ctx, sourceUDID) - if err != nil { - return err - } - clone, _, err := simulatorDataDirectory(ctx, cloneUDID) - if err != nil { - return err - } - if source.Set != clone.Set { - return fmt.Errorf("source and clone must belong to the same simulator set") - } - if source.PlatformName() != clone.PlatformName() || source.OSVersion != clone.OSVersion { - return fmt.Errorf( - "source and clone runtimes differ (%s and %s)", - source.RuntimeName(), - clone.RuntimeName(), - ) - } - for _, device := range []Device{source, clone} { - if device.State != "Booted" && device.State != "Shutdown" { - return fmt.Errorf( - "simulator %s must be booted or shutdown before repair (it is %s)", - device.UDID, - device.State, - ) - } - } - paths, err := cloneFilesystemFor(ctx, source, sourceDataDirectory, cloneUDID) - if err != nil { - return err - } - - sourceWasBooted := source.State == "Booted" - cloneWasBooted := clone.State == "Booted" - defer func() { - restoreCtx, cancel := context.WithTimeout(context.WithoutCancel(ctx), BootTimeout) - defer cancel() - if restoreErr := restoreCloneSourceState(restoreCtx, source.Set, sourceUDID, sourceWasBooted); restoreErr != nil { - if err != nil { - err = fmt.Errorf("%v; additionally could not restore the source boot state: %w", err, restoreErr) - } else { - err = fmt.Errorf("clone repaired, but could not restore the source boot state: %w", restoreErr) - } - } - }() - - repairIsSafe := false - defer func() { - if repairIsSafe { - return - } - shutdownCtx, cancel := context.WithTimeout(context.WithoutCancel(ctx), BootTimeout) - defer cancel() - if shutdownErr := restoreCloneSourceState(shutdownCtx, clone.Set, cloneUDID, false); shutdownErr != nil { - if err != nil { - err = fmt.Errorf("%v; additionally could not leave the clone safely shutdown: %w", err, shutdownErr) - } else { - err = fmt.Errorf("could not leave the clone safely shutdown: %w", shutdownErr) - } - } - }() - - // Stop a running legacy clone first so it cannot keep writing through a - // source-bound symlink while the source shuts down. Both devices must be - // offline before any copied filesystem state is rebuilt. - if err := restoreCloneSourceState(ctx, clone.Set, cloneUDID, false); err != nil { - return fmt.Errorf("shutdown clone before repair: %w", err) - } - if err := restoreCloneSourceState(ctx, source.Set, sourceUDID, false); err != nil { - return fmt.Errorf("shutdown source before clone repair: %w", err) - } - - // Sanitization does not clear or replace launchd's override database. Do it - // before the first repair-initiated boot so a shutdown legacy clone can never - // start with a Library symlink that still resolves into the source device. - if err := sanitizeClonedDeviceAt(paths); err != nil { - return err - } - if err := BootAndWait(ctx, clone.Set, cloneUDID); err != nil { - return fmt.Errorf("boot clone to capture its service profile: %w", err) - } - disabled, err := readDisabled(ctx, clone.Set, cloneUDID) - if err != nil { - return fmt.Errorf("capture cloned service profile: %w", err) - } - desired := desiredCloneDisabled(disabled) - if _, err := ensure(ctx, clone.Set, cloneUDID, desired, nil); err != nil { - return fmt.Errorf("restore repaired clone service profile: %w", err) - } - if err := verifyRunningCloneDoesNotOpenSource(ctx, paths); err != nil { - return err - } - if !cloneWasBooted { - if err := restoreCloneSourceState(ctx, clone.Set, cloneUDID, false); err != nil { - return fmt.Errorf("restore clone shutdown state: %w", err) - } - } - - repairIsSafe = true - return nil -} - -func restoreCloneSourceState(ctx context.Context, set, udid string, shouldBeBooted bool) error { - device, err := FindDevice(ctx, udid, set) - if err != nil { - return err - } - if shouldBeBooted { - if device.State == "Booted" { - return nil - } - return BootAndWait(ctx, set, udid) - } - if device.State == "Shutdown" { - return nil - } - if err := Shutdown(ctx, set, udid); err != nil { - return err - } - return WaitShutdown(ctx, set, udid, ShutdownTimeout) -} - -func deleteUnsafeClone(parent context.Context, set, udid string) error { - cleanupCtx, cancel := context.WithTimeout(context.WithoutCancel(parent), BootTimeout) - defer cancel() - - var stopErr error - if err := Shutdown(cleanupCtx, set, udid); err != nil { - stopErr = err - } else if err := WaitShutdown(cleanupCtx, set, udid, ShutdownTimeout); err != nil { - stopErr = err - } - _, deleteErr := xcrun(cleanupCtx, simctlArgs(set, "delete", udid)...) - if deleteErr == nil { - return nil - } - if stopErr != nil { - return fmt.Errorf("stop clone: %v; delete clone: %w", stopErr, deleteErr) - } - return deleteErr -} - -func cloneFilesystemFor( - ctx context.Context, - source Device, - sourceDataDirectory string, - cloneUDID string, -) (cloneFilesystem, error) { - clone, cloneDataDirectory, err := simulatorDataDirectory(ctx, cloneUDID) - if err != nil { - return cloneFilesystem{}, err - } - if clone.Set != source.Set { - return cloneFilesystem{}, fmt.Errorf( - "CoreSimulator placed clone %s in %s instead of source set %s", - cloneUDID, - clone.Set, - source.Set, - ) - } - homeDirectory, err := os.UserHomeDir() - if err != nil { - return cloneFilesystem{}, fmt.Errorf("locate CoreSimulator logs: %w", err) - } - logsRoot := filepath.Join(homeDirectory, "Library", "Logs", "CoreSimulator") - return cloneFilesystem{ - sourceUDID: source.UDID, - cloneUDID: cloneUDID, - sourceDeviceDirectory: filepath.Dir(sourceDataDirectory), - cloneDeviceDirectory: filepath.Dir(cloneDataDirectory), - sourceDataDirectory: sourceDataDirectory, - cloneDataDirectory: cloneDataDirectory, - sourceLogDirectory: filepath.Join(logsRoot, source.UDID), - cloneLogDirectory: filepath.Join(logsRoot, cloneUDID), - }, nil -} - -func sanitizeClonedDeviceAt(paths cloneFilesystem) error { - if err := validateCloneFilesystem(paths); err != nil { - return err - } - - // These stores are generated from installed apps and current simulator - // paths. Regenerating only the system copies preserves app bundles, app data, - // settings, and even app-owned caches while removing stale absolute paths. - if err := resetClonedLaunchServicesAt(paths.cloneDataDirectory); err != nil { - return err - } - if err := resetClonedFrontBoardAt(paths.cloneDataDirectory); err != nil { - return err - } - if err := resetClonedGeneratedPathStateAt(paths.cloneDataDirectory); err != nil { - return err - } - for _, directory := range []string{ - filepath.Join(paths.cloneDataDirectory, "Library", "Caches"), - filepath.Join(paths.cloneDataDirectory, "tmp"), - } { - if err := clearDirectoryContents(paths.cloneDataDirectory, directory); err != nil { - return fmt.Errorf("reset cloned transient state: %w", err) - } - } - if err := rebaseClonePropertyLists(paths); err != nil { - return err - } - - if err := rebaseCloneSymlinks(paths); err != nil { - return err - } - return verifyCloneIndependence(paths) -} - -// Property lists frequently persist simulator-local file URLs (wallpaper is a -// notable example). UUIDs have equal byte lengths, so replacing one UUID with -// the other preserves both XML and binary plist structure while retaining the -// actual setting and redirecting its file URL into the clone. -func rebaseClonePropertyLists(paths cloneFilesystem) error { - if len(paths.sourceUDID) != len(paths.cloneUDID) { - return fmt.Errorf("source and clone UDIDs must have equal lengths") - } - source := []byte(paths.sourceUDID) - clone := []byte(paths.cloneUDID) - return filepath.WalkDir(paths.cloneDeviceDirectory, func(path string, entry os.DirEntry, walkErr error) error { - if walkErr != nil { - return walkErr - } - if !entry.Type().IsRegular() || !strings.EqualFold(filepath.Ext(path), ".plist") { - return nil - } - contents, err := os.ReadFile(path) - if err != nil { - return fmt.Errorf("read cloned property list %s: %w", path, err) - } - if !bytes.Contains(contents, source) { - return nil - } - info, err := entry.Info() - if err != nil { - return fmt.Errorf("inspect cloned property list %s: %w", path, err) - } - contents = bytes.ReplaceAll(contents, source, clone) - if err := replaceRegularFile(path, contents, info.Mode()); err != nil { - return fmt.Errorf("rebase cloned property list %s: %w", path, err) - } - return nil - }) -} - -func replaceRegularFile(path string, contents []byte, mode os.FileMode) error { - temporary, err := os.CreateTemp(filepath.Dir(path), ".simslim-rebase-") - if err != nil { - return err - } - temporaryPath := temporary.Name() - defer func() { _ = os.Remove(temporaryPath) }() - if err := temporary.Chmod(mode.Perm()); err != nil { - _ = temporary.Close() - return err - } - if _, err := temporary.Write(contents); err != nil { - _ = temporary.Close() - return err - } - if err := temporary.Sync(); err != nil { - _ = temporary.Close() - return err - } - if err := temporary.Close(); err != nil { - return err - } - return os.Rename(temporaryPath, path) -} - -func validateCloneFilesystem(paths cloneFilesystem) error { - if paths.sourceUDID == "" || paths.cloneUDID == "" || paths.sourceUDID == paths.cloneUDID { - return fmt.Errorf("clone source and destination UDIDs must be distinct") - } - for label, directory := range map[string]string{ - "source device": paths.sourceDeviceDirectory, - "clone device": paths.cloneDeviceDirectory, - "source data": paths.sourceDataDirectory, - "clone data": paths.cloneDataDirectory, - } { - info, err := os.Lstat(directory) - if err != nil { - return fmt.Errorf("locate %s directory: %w", label, err) - } - if !info.IsDir() || info.Mode()&os.ModeSymlink != 0 { - return fmt.Errorf("%s path is not a real directory: %s", label, directory) - } - } - for deviceDirectory, dataDirectory := range map[string]string{ - paths.sourceDeviceDirectory: paths.sourceDataDirectory, - paths.cloneDeviceDirectory: paths.cloneDataDirectory, - } { - if err := requireDescendant(deviceDirectory, dataDirectory); err != nil { - return err - } - if err := requireResolvedDescendant(deviceDirectory, dataDirectory); err != nil { - return err - } - } - return nil -} - -func resetClonedLaunchServicesAt(dataDirectory string) error { - lsdDirectory := filepath.Join(dataDirectory, "var", "db", "lsd") - if err := requireDescendant(dataDirectory, lsdDirectory); err != nil { - return err - } - info, err := os.Lstat(lsdDirectory) - if os.IsNotExist(err) { - return nil - } - if err != nil { - return fmt.Errorf("locate cloned LaunchServices data: %w", err) - } - if !info.IsDir() || info.Mode()&os.ModeSymlink != 0 { - return fmt.Errorf("cloned LaunchServices path is not a real directory: %s", lsdDirectory) - } - if err := requireResolvedDescendant(dataDirectory, lsdDirectory); err != nil { - return err - } - - entries, err := os.ReadDir(lsdDirectory) - if err != nil { - return fmt.Errorf("read cloned LaunchServices data: %w", err) - } - for _, entry := range entries { - name := entry.Name() - if !strings.HasPrefix(name, "com.apple.LaunchServices-") || !strings.Contains(name, ".csstore") { - continue - } - - target := filepath.Join(lsdDirectory, name) - if err := requireDescendant(lsdDirectory, target); err != nil { - return err - } - targetInfo, err := os.Lstat(target) - if err != nil { - return fmt.Errorf("inspect cloned LaunchServices store: %w", err) - } - if !targetInfo.Mode().IsRegular() || targetInfo.Mode()&os.ModeSymlink != 0 { - return fmt.Errorf("cloned LaunchServices store is not a regular file: %s", target) - } - if err := os.Remove(target); err != nil { - return fmt.Errorf("reset cloned LaunchServices store: %w", err) - } - } - return nil -} - -func resetClonedFrontBoardAt(dataDirectory string) error { - frontBoardDirectory := filepath.Join(dataDirectory, "Library", "FrontBoard") - if err := requireDescendant(dataDirectory, frontBoardDirectory); err != nil { - return err - } - info, err := os.Lstat(frontBoardDirectory) - if os.IsNotExist(err) { - return nil - } - if err != nil { - return fmt.Errorf("locate cloned FrontBoard data: %w", err) - } - if !info.IsDir() || info.Mode()&os.ModeSymlink != 0 { - return fmt.Errorf("cloned FrontBoard path is not a real directory: %s", frontBoardDirectory) - } - if err := requireResolvedDescendant(dataDirectory, frontBoardDirectory); err != nil { - return err - } - for _, name := range []string{"applicationState.db", "applicationState.db-shm", "applicationState.db-wal"} { - target := filepath.Join(frontBoardDirectory, name) - targetInfo, err := os.Lstat(target) - if os.IsNotExist(err) { - continue - } - if err != nil { - return fmt.Errorf("inspect cloned FrontBoard store: %w", err) - } - if !targetInfo.Mode().IsRegular() || targetInfo.Mode()&os.ModeSymlink != 0 { - return fmt.Errorf("cloned FrontBoard store is not a regular file: %s", target) - } - if err := os.Remove(target); err != nil { - return fmt.Errorf("reset cloned FrontBoard store: %w", err) - } - } - return nil -} - -// resetClonedGeneratedPathStateAt clears system-owned indexes, task databases, -// and asset registries that persist absolute simulator paths outside plists. -// These stores are regenerated by their daemons; installed apps, app data, and -// downloaded MobileAsset payloads are deliberately outside this allowlist. -func resetClonedGeneratedPathStateAt(dataDirectory string) error { - directories := []string{ - filepath.Join(dataDirectory, "Library", "AppleMediaServices", "Engagement", "internal", "database"), - filepath.Join(dataDirectory, "Library", "Spotlight"), - filepath.Join(dataDirectory, "Library", "chronod", "replicator"), - filepath.Join(dataDirectory, "Library", "com.apple.nsurlsessiond"), - filepath.Join(dataDirectory, "private", "var", "MobileAsset", "AssetsV2", "locks"), - filepath.Join(dataDirectory, "private", "var", "MobileAsset", "AssetsV2", "persisted"), - filepath.Join(dataDirectory, "private", "var", "db", "assetsubscriptiond", "history"), - filepath.Join(dataDirectory, "var", "db", "diagnostics", "Persist"), - filepath.Join(dataDirectory, "var", "db", "diagnostics", "Special"), - } - replicatorDirectories, err := filepath.Glob( - filepath.Join(dataDirectory, "Containers", "Shared", "AppGroup", "*", "replicatord"), - ) - if err != nil { - return fmt.Errorf("locate cloned replicator state: %w", err) - } - directories = append(directories, replicatorDirectories...) - - for _, directory := range directories { - if err := clearDirectoryContents(dataDirectory, directory); err != nil { - return fmt.Errorf("reset cloned generated path state %s: %w", directory, err) - } - } - return nil -} - -func rebaseCloneSymlinks(paths cloneFilesystem) error { - return filepath.WalkDir(paths.cloneDeviceDirectory, func(path string, entry os.DirEntry, walkErr error) error { - if walkErr != nil { - return walkErr - } - if entry.Type()&os.ModeSymlink == 0 { - return nil - } - target, err := os.Readlink(path) - if err != nil { - return fmt.Errorf("read cloned symlink %s: %w", path, err) - } - resolvedTarget := target - if !filepath.IsAbs(resolvedTarget) { - resolvedTarget = filepath.Join(filepath.Dir(path), resolvedTarget) - } - resolvedTarget = filepath.Clean(resolvedTarget) - - mappedTarget, mapped := rebasePath( - resolvedTarget, - paths.sourceDeviceDirectory, - paths.cloneDeviceDirectory, - ) - if !mapped { - mappedTarget, mapped = rebasePath( - resolvedTarget, - paths.sourceLogDirectory, - paths.cloneLogDirectory, - ) - } - if !mapped { - return nil - } - - newTarget := mappedTarget - if !filepath.IsAbs(target) { - newTarget, err = filepath.Rel(filepath.Dir(path), mappedTarget) - if err != nil { - return fmt.Errorf("rebase cloned symlink %s: %w", path, err) - } - } - if err := replaceSymlink(path, newTarget); err != nil { - return fmt.Errorf("rebase cloned symlink %s: %w", path, err) - } - return nil - }) -} - -func rebasePath(path, sourceRoot, cloneRoot string) (string, bool) { - relative, err := filepath.Rel(filepath.Clean(sourceRoot), filepath.Clean(path)) - if err != nil || relative == ".." || strings.HasPrefix(relative, ".."+string(filepath.Separator)) { - return "", false - } - if relative == "." { - return filepath.Clean(cloneRoot), true - } - return filepath.Join(cloneRoot, relative), true -} - -func replaceSymlink(path, target string) error { - temporary, err := os.CreateTemp(filepath.Dir(path), ".simslim-relink-") - if err != nil { - return err - } - temporaryPath := temporary.Name() - if err := temporary.Close(); err != nil { - _ = os.Remove(temporaryPath) - return err - } - if err := os.Remove(temporaryPath); err != nil { - return err - } - if err := os.Symlink(target, temporaryPath); err != nil { - return err - } - if err := os.Rename(temporaryPath, path); err != nil { - _ = os.Remove(temporaryPath) - return err - } - return nil -} - -func verifyCloneIndependence(paths cloneFilesystem) error { - return filepath.WalkDir(paths.cloneDeviceDirectory, func(path string, entry os.DirEntry, walkErr error) error { - if walkErr != nil { - return walkErr - } - if entry.Type()&os.ModeSymlink != 0 { - target, err := os.Readlink(path) - if err != nil { - return fmt.Errorf("read cloned symlink %s: %w", path, err) - } - resolvedTarget := target - if !filepath.IsAbs(resolvedTarget) { - resolvedTarget = filepath.Join(filepath.Dir(path), resolvedTarget) - } - resolvedTarget = filepath.Clean(resolvedTarget) - if _, linked := rebasePath(resolvedTarget, paths.sourceDeviceDirectory, paths.cloneDeviceDirectory); linked || - pathContainsComponent(resolvedTarget, paths.sourceUDID) || - pathContainsComponent(target, paths.sourceUDID) { - return fmt.Errorf("cloned symlink %s still resolves into the source simulator: %s", path, target) - } - return nil - } - if !entry.Type().IsRegular() { - return nil - } - - relative, err := filepath.Rel(paths.cloneDeviceDirectory, path) - if err != nil { - return err - } - sourcePath := filepath.Join(paths.sourceDeviceDirectory, relative) - sourceInfo, err := os.Lstat(sourcePath) - if os.IsNotExist(err) { - return nil - } - if err != nil { - return fmt.Errorf("inspect source counterpart %s: %w", sourcePath, err) - } - if !sourceInfo.Mode().IsRegular() { - return nil - } - cloneInfo, err := entry.Info() - if err != nil { - return fmt.Errorf("inspect cloned file %s: %w", path, err) - } - if os.SameFile(sourceInfo, cloneInfo) { - return fmt.Errorf("cloned file %s is hard-linked to the source simulator", path) - } - return nil - }) -} - -type sourceReference struct { - pid int - path string -} - -const ( - cloneOpenFileAuditAttempts = 3 - cloneOpenFileAuditDelay = 100 * time.Millisecond -) - -// verifyRunningCloneDoesNotOpenSource makes the filesystem checks observable -// at runtime too. It catches a copied registry or preference that contains an -// absolute path even when that path is not represented by a symlink. -func verifyRunningCloneDoesNotOpenSource(ctx context.Context, paths cloneFilesystem) error { - var lastErr error - for attempt := 0; attempt < cloneOpenFileAuditAttempts; attempt++ { - complete, err := auditRunningCloneOpenFilesOnce(ctx, paths) - if complete { - return err - } - lastErr = err - if attempt+1 == cloneOpenFileAuditAttempts { - break - } - timer := time.NewTimer(cloneOpenFileAuditDelay) - select { - case <-timer.C: - case <-ctx.Done(): - if !timer.Stop() { - select { - case <-timer.C: - default: - } - } - return fmt.Errorf("audit cloned simulator open files: %w", ctx.Err()) - } - } - return lastErr -} - -// auditRunningCloneOpenFilesOnce reports complete=false only when process churn -// prevented a meaningful snapshot. The caller retries those transient cases. -func auditRunningCloneOpenFilesOnce(ctx context.Context, paths cloneFilesystem) (complete bool, err error) { - psOutput, err := exec.CommandContext(ctx, "/bin/ps", "eww", "-axo", "pid=,command=").Output() - if err != nil { - return true, fmt.Errorf("enumerate cloned simulator processes: %w", err) - } - pids := simulatorProcessIDsFromPS(string(psOutput), paths.cloneUDID) - if len(pids) == 0 { - return false, fmt.Errorf("could not identify any running processes for cloned simulator %s", paths.cloneUDID) - } - pidsText := make([]string, 0, len(pids)) - for _, pid := range pids { - pidsText = append(pidsText, strconv.Itoa(pid)) - } - lsofOutput, lsofErr := exec.CommandContext( - ctx, - "/usr/sbin/lsof", - "-n", - "-P", - "-Fpn", - "-p", - strings.Join(pidsText, ","), - ).CombinedOutput() - return evaluateCloneLsofAudit(string(lsofOutput), lsofErr, paths) -} - -func evaluateCloneLsofAudit(output string, commandErr error, paths cloneFilesystem) (complete bool, err error) { - references, hasRecords := parseCloneLsofOutput(output, paths) - if len(references) > 0 { - return true, fmt.Errorf( - "clone process %d still has a source simulator path open: %s", - references[0].pid, - references[0].path, - ) - } - if hasRecords { - // lsof exits 1 when any PID from the snapshot has already exited, even - // though it emits complete records for every process that is still live. - return true, nil - } - if commandErr != nil { - message := strings.TrimSpace(output) - if message == "" { - return false, fmt.Errorf("audit cloned simulator open files: %w", commandErr) - } - return false, fmt.Errorf("audit cloned simulator open files: %w: %s", commandErr, message) - } - return false, fmt.Errorf("audit cloned simulator open files returned no process or path records") -} - -func simulatorProcessIDsFromPS(output, udid string) []int { - marker := "SIMULATOR_UDID=" + udid - seen := make(map[int]bool) - var pids []int - for _, line := range strings.Split(output, "\n") { - if !strings.Contains(line, marker) { - continue - } - fields := strings.Fields(line) - if len(fields) == 0 { - continue - } - pid, err := strconv.Atoi(fields[0]) - if err != nil || pid <= 0 || seen[pid] { - continue - } - seen[pid] = true - pids = append(pids, pid) - } - sort.Ints(pids) - return pids -} - -func sourceReferencesFromLsof(output string, paths cloneFilesystem) []sourceReference { - references, _ := parseCloneLsofOutput(output, paths) - return references -} - -func parseCloneLsofOutput(output string, paths cloneFilesystem) (references []sourceReference, hasRecords bool) { - currentPID := 0 - for _, line := range strings.Split(output, "\n") { - if len(line) < 2 { - continue - } - switch line[0] { - case 'p': - pid, err := strconv.Atoi(line[1:]) - if err != nil || pid <= 0 { - currentPID = 0 - continue - } - currentPID = pid - case 'n': - if currentPID <= 0 { - continue - } - hasRecords = true - path := line[1:] - _, inSourceDevice := rebasePath(path, paths.sourceDeviceDirectory, paths.cloneDeviceDirectory) - _, inSourceLogs := rebasePath(path, paths.sourceLogDirectory, paths.cloneLogDirectory) - if inSourceDevice || inSourceLogs { - references = append(references, sourceReference{pid: currentPID, path: path}) - } - } - } - return references, hasRecords -} - -func pathContainsComponent(path, component string) bool { - if component == "" { - return false - } - for _, part := range strings.Split(filepath.Clean(path), string(filepath.Separator)) { - if part == component { - return true - } - } - return false -} - -// CloneOperationTimeout is deliberately derived from BootTimeout at call time -// because tests and CI may raise that variable for slow hosts. -func CloneOperationTimeout() time.Duration { - return 3*BootTimeout + 2*ShutdownTimeout -} diff --git a/clone_test.go b/clone_test.go deleted file mode 100644 index 1304004..0000000 --- a/clone_test.go +++ /dev/null @@ -1,362 +0,0 @@ -package simslim - -import ( - "errors" - "os" - "path/filepath" - "strings" - "testing" -) - -const ( - testSourceUDID = "11111111-1111-1111-1111-111111111111" - testCloneUDID = "22222222-2222-2222-2222-222222222222" -) - -func TestDesiredCloneDisabledKeepsOnlySlimmableServices(t *testing.T) { - var slimmable, anotherSlimmable, required string - for _, category := range Categories { - if slimmable == "" && len(category.Labels) > 1 { - slimmable = category.Labels[0] - anotherSlimmable = category.Labels[1] - } - if required == "" && len(category.AlwaysEnabled) > 0 { - required = category.AlwaysEnabled[0].Label - } - } - if slimmable == "" || required == "" { - t.Fatal("test requires both slimmable and always-enabled profile entries") - } - disabled := map[string]bool{ - slimmable: true, - anotherSlimmable: false, - required: true, - "com.example.unmanaged-test": true, - } - - got := desiredCloneDisabled(disabled) - if len(got) != 1 || !got[slimmable] { - t.Fatalf("desiredCloneDisabled() = %v, want only %q", got, slimmable) - } -} - -func TestSanitizeClonedDeviceAtRebasesDirectLinks(t *testing.T) { - paths := newTestCloneFilesystem(t) - - trialSource := filepath.Join(paths.sourceDataDirectory, "Library", "Trial", "shared-state") - trialClone := filepath.Join(paths.cloneDataDirectory, "Library", "Trial", "shared-state") - writeCloneTestFile(t, trialSource, "source trial state") - writeCloneTestFile(t, trialClone, "cloned trial state") - absoluteLink := filepath.Join(paths.cloneDataDirectory, "Library", "Trial", "current-state") - mustMkdirAll(t, filepath.Dir(absoluteLink)) - if err := os.Symlink(trialSource, absoluteLink); err != nil { - t.Fatal(err) - } - - shortcutSource := filepath.Join(paths.sourceDataDirectory, "Library", "Shortcuts", "store") - shortcutClone := filepath.Join(paths.cloneDataDirectory, "Library", "Shortcuts", "store") - writeCloneTestFile(t, shortcutSource, "source shortcuts") - writeCloneTestFile(t, shortcutClone, "cloned shortcuts") - relativeSourceLink := filepath.Join(paths.cloneDataDirectory, "Library", "Shortcuts", "source-relative") - relativeSourceTarget, err := filepath.Rel(filepath.Dir(relativeSourceLink), shortcutSource) - if err != nil { - t.Fatal(err) - } - if err := os.Symlink(relativeSourceTarget, relativeSourceLink); err != nil { - t.Fatal(err) - } - - localRelativeLink := filepath.Join(paths.cloneDataDirectory, "Library", "Trial", "local-relative") - if err := os.Symlink("shared-state", localRelativeLink); err != nil { - t.Fatal(err) - } - sharedRuntimeLink := filepath.Join(paths.cloneDataDirectory, "Library", "shared-runtime") - const sharedRuntimeTarget = "/Library/Developer/CoreSimulator/Volumes/iOS_23A123" - if err := os.Symlink(sharedRuntimeTarget, sharedRuntimeLink); err != nil { - t.Fatal(err) - } - logsLink := filepath.Join(paths.cloneDataDirectory, "Library", "Logs") - if err := os.Symlink(paths.sourceLogDirectory, logsLink); err != nil { - t.Fatal(err) - } - - lsdDirectory := filepath.Join(paths.cloneDataDirectory, "var", "db", "lsd") - writeCloneTestFile(t, filepath.Join(lsdDirectory, "com.apple.LaunchServices-1-v2.csstore"), "stale paths") - writeCloneTestFile(t, filepath.Join(lsdDirectory, "SystemDataOnly-com.apple.LaunchServices-1-v2.csstore"), "keep") - frontBoardDirectory := filepath.Join(paths.cloneDataDirectory, "Library", "FrontBoard") - for _, name := range []string{"applicationState.db", "applicationState.db-shm", "applicationState.db-wal"} { - writeCloneTestFile(t, filepath.Join(frontBoardDirectory, name), "stale paths") - } - generatedStateDirectories := []string{ - filepath.Join(paths.cloneDataDirectory, "Library", "AppleMediaServices", "Engagement", "internal", "database"), - filepath.Join(paths.cloneDataDirectory, "Library", "Spotlight"), - filepath.Join(paths.cloneDataDirectory, "Library", "chronod", "replicator"), - filepath.Join(paths.cloneDataDirectory, "Library", "com.apple.nsurlsessiond"), - filepath.Join(paths.cloneDataDirectory, "private", "var", "MobileAsset", "AssetsV2", "locks"), - filepath.Join(paths.cloneDataDirectory, "private", "var", "MobileAsset", "AssetsV2", "persisted"), - filepath.Join(paths.cloneDataDirectory, "private", "var", "db", "assetsubscriptiond", "history"), - filepath.Join(paths.cloneDataDirectory, "var", "db", "diagnostics", "Persist"), - filepath.Join(paths.cloneDataDirectory, "var", "db", "diagnostics", "Special"), - filepath.Join(paths.cloneDataDirectory, "Containers", "Shared", "AppGroup", "SYSTEM", "replicatord"), - } - for _, directory := range generatedStateDirectories { - writeCloneTestFile(t, filepath.Join(directory, "copied-state.db"), "file://"+trialSource) - } - downloadedAsset := filepath.Join( - paths.cloneDataDirectory, - "private", - "var", - "MobileAsset", - "AssetsV2", - "com_apple_MobileAsset_Test", - "AssetData", - "model.bin", - ) - writeCloneTestFile(t, downloadedAsset, "downloaded payload") - - writeCloneTestFile(t, filepath.Join(paths.cloneDataDirectory, "Library", "Caches", "system.cache"), "discard") - writeCloneTestFile(t, filepath.Join(paths.cloneDataDirectory, "tmp", "snapshot"), "discard") - springBoardPreference := filepath.Join( - paths.cloneDataDirectory, - "Library", - "Preferences", - "com.apple.springboard.plist", - ) - writeCloneTestFile( - t, - springBoardPreference, - "file://"+filepath.Join(paths.sourceDataDirectory, "Library", "Poster", "snapshot.atx"), - ) - appBundle := filepath.Join(paths.cloneDataDirectory, "Containers", "Bundle", "Application", "APP", "FleetDog.app", "FleetDog") - appDocument := filepath.Join(paths.cloneDataDirectory, "Containers", "Data", "Application", "APP", "Documents", "fleetdog.db") - appCache := filepath.Join(paths.cloneDataDirectory, "Containers", "Data", "Application", "APP", "Library", "Caches", "offline.cache") - writeCloneTestFile(t, appBundle, "executable") - writeCloneTestFile(t, appDocument, "user data") - writeCloneTestFile(t, appCache, "app cache") - - if err := sanitizeClonedDeviceAt(paths); err != nil { - t.Fatalf("sanitizeClonedDeviceAt() error = %v", err) - } - - assertSymlinkTarget(t, absoluteLink, trialClone) - wantRelativeCloneTarget, err := filepath.Rel(filepath.Dir(relativeSourceLink), shortcutClone) - if err != nil { - t.Fatal(err) - } - assertSymlinkTarget(t, relativeSourceLink, wantRelativeCloneTarget) - assertSymlinkTarget(t, localRelativeLink, "shared-state") - assertSymlinkTarget(t, sharedRuntimeLink, sharedRuntimeTarget) - assertSymlinkTarget(t, logsLink, paths.cloneLogDirectory) - - assertMissing(t, filepath.Join(lsdDirectory, "com.apple.LaunchServices-1-v2.csstore")) - assertExists(t, filepath.Join(lsdDirectory, "SystemDataOnly-com.apple.LaunchServices-1-v2.csstore")) - for _, name := range []string{"applicationState.db", "applicationState.db-shm", "applicationState.db-wal"} { - assertMissing(t, filepath.Join(frontBoardDirectory, name)) - } - for _, directory := range generatedStateDirectories { - assertDirectoryEmpty(t, directory) - } - assertExists(t, downloadedAsset) - assertDirectoryEmpty(t, filepath.Join(paths.cloneDataDirectory, "Library", "Caches")) - assertDirectoryEmpty(t, filepath.Join(paths.cloneDataDirectory, "tmp")) - preferenceContents, err := os.ReadFile(springBoardPreference) - if err != nil { - t.Fatal(err) - } - if strings.Contains(string(preferenceContents), testSourceUDID) || - !strings.Contains(string(preferenceContents), testCloneUDID) { - t.Errorf("rebased preference = %q, want only clone UDID", preferenceContents) - } - assertExists(t, appBundle) - assertExists(t, appDocument) - assertExists(t, appCache) - - err = filepath.WalkDir(paths.cloneDeviceDirectory, func(path string, entry os.DirEntry, walkErr error) error { - if walkErr != nil { - return walkErr - } - if entry.Type()&os.ModeSymlink == 0 { - return nil - } - target, readErr := os.Readlink(path) - if readErr != nil { - return readErr - } - if strings.Contains(target, testSourceUDID) { - t.Errorf("clone symlink %s still names source UDID in %q", path, target) - } - return nil - }) - if err != nil { - t.Fatal(err) - } -} - -func TestSimulatorProcessIDsFromPS(t *testing.T) { - output := strings.Join([]string{ - "100 launchd_sim SIMULATOR_UDID=" + testCloneUDID + " HOME=/clone", - "101 SpringBoard HOME=/clone SIMULATOR_UDID=" + testCloneUDID, - "102 source SIMULATOR_UDID=" + testSourceUDID, - "not-a-pid helper SIMULATOR_UDID=" + testCloneUDID, - "", - }, "\n") - got := simulatorProcessIDsFromPS(output, testCloneUDID) - if len(got) != 2 || got[0] != 100 || got[1] != 101 { - t.Fatalf("simulatorProcessIDsFromPS() = %v, want [100 101]", got) - } -} - -func TestSourceReferencesFromLsof(t *testing.T) { - paths := newTestCloneFilesystem(t) - output := strings.Join([]string{ - "p100", - "fcwd", - "n" + paths.cloneDataDirectory, - "ftxt", - "n" + filepath.Join(paths.sourceDataDirectory, "Library", "Poster", "snapshot.atx"), - "p101", - "ftxt", - "n/Library/Developer/CoreSimulator/Volumes/iOS_Runtime", - "", - }, "\n") - got := sourceReferencesFromLsof(output, paths) - if len(got) != 1 || got[0].pid != 100 || !strings.Contains(got[0].path, testSourceUDID) { - t.Fatalf("sourceReferencesFromLsof() = %v, want one PID 100 source path", got) - } -} - -func TestEvaluateCloneLsofAuditAcceptsLiveRecordsWhenAnotherPIDExited(t *testing.T) { - paths := newTestCloneFilesystem(t) - output := strings.Join([]string{ - "p100", - "fcwd", - "n" + paths.cloneDataDirectory, - "", - }, "\n") - - complete, err := evaluateCloneLsofAudit(output, errors.New("exit status 1"), paths) - if !complete || err != nil { - t.Fatalf("evaluateCloneLsofAudit() = (%t, %v), want complete success", complete, err) - } -} - -func TestEvaluateCloneLsofAuditRetriesWhenAllSnapshottedPIDsExited(t *testing.T) { - paths := newTestCloneFilesystem(t) - complete, err := evaluateCloneLsofAudit("", errors.New("exit status 1"), paths) - if complete || err == nil { - t.Fatalf("evaluateCloneLsofAudit() = (%t, %v), want incomplete error", complete, err) - } -} - -func TestEvaluateCloneLsofAuditRejectsSourceReferenceDespiteExitError(t *testing.T) { - paths := newTestCloneFilesystem(t) - output := strings.Join([]string{ - "p100", - "fcwd", - "n" + filepath.Join(paths.sourceDataDirectory, "Library", "linked.db"), - "", - }, "\n") - - complete, err := evaluateCloneLsofAudit(output, errors.New("exit status 1"), paths) - if !complete || err == nil || !strings.Contains(err.Error(), "source simulator path") { - t.Fatalf("evaluateCloneLsofAudit() = (%t, %v), want complete source-path error", complete, err) - } -} - -func TestSanitizeClonedDeviceAtRejectsUnknownSourceSymlink(t *testing.T) { - paths := newTestCloneFilesystem(t) - link := filepath.Join(paths.cloneDataDirectory, "Library", "unexpected-source-link") - if err := os.Symlink(filepath.Join(t.TempDir(), testSourceUDID, "state"), link); err != nil { - t.Fatal(err) - } - - err := sanitizeClonedDeviceAt(paths) - if err == nil || !strings.Contains(err.Error(), "source simulator") { - t.Fatalf("sanitizeClonedDeviceAt() error = %v, want unknown source-link rejection", err) - } -} - -func TestSanitizeClonedDeviceAtRejectsHardLinkedSourceFile(t *testing.T) { - paths := newTestCloneFilesystem(t) - source := filepath.Join(paths.sourceDataDirectory, "Library", "State", "shared.db") - clone := filepath.Join(paths.cloneDataDirectory, "Library", "State", "shared.db") - writeCloneTestFile(t, source, "shared inode") - mustMkdirAll(t, filepath.Dir(clone)) - if err := os.Link(source, clone); err != nil { - t.Fatal(err) - } - - err := sanitizeClonedDeviceAt(paths) - if err == nil || !strings.Contains(err.Error(), "hard-linked") { - t.Fatalf("sanitizeClonedDeviceAt() error = %v, want hard-link rejection", err) - } -} - -func newTestCloneFilesystem(t *testing.T) cloneFilesystem { - t.Helper() - root := t.TempDir() - paths := cloneFilesystem{ - sourceUDID: testSourceUDID, - cloneUDID: testCloneUDID, - sourceDeviceDirectory: filepath.Join(root, "Devices", testSourceUDID), - cloneDeviceDirectory: filepath.Join(root, "Devices", testCloneUDID), - sourceLogDirectory: filepath.Join(root, "Logs", testSourceUDID), - cloneLogDirectory: filepath.Join(root, "Logs", testCloneUDID), - } - paths.sourceDataDirectory = filepath.Join(paths.sourceDeviceDirectory, "data") - paths.cloneDataDirectory = filepath.Join(paths.cloneDeviceDirectory, "data") - mustMkdirAll(t, filepath.Join(paths.sourceDataDirectory, "Library")) - mustMkdirAll(t, filepath.Join(paths.cloneDataDirectory, "Library")) - return paths -} - -func writeCloneTestFile(t *testing.T, path, contents string) { - t.Helper() - mustMkdirAll(t, filepath.Dir(path)) - if err := os.WriteFile(path, []byte(contents), 0o600); err != nil { - t.Fatal(err) - } -} - -func mustMkdirAll(t *testing.T, path string) { - t.Helper() - if err := os.MkdirAll(path, 0o755); err != nil { - t.Fatal(err) - } -} - -func assertSymlinkTarget(t *testing.T, path, want string) { - t.Helper() - got, err := os.Readlink(path) - if err != nil { - t.Fatalf("readlink %s: %v", path, err) - } - if got != want { - t.Errorf("readlink %s = %q, want %q", path, got, want) - } -} - -func assertExists(t *testing.T, path string) { - t.Helper() - if _, err := os.Lstat(path); err != nil { - t.Errorf("expected %s to exist: %v", path, err) - } -} - -func assertMissing(t *testing.T, path string) { - t.Helper() - if _, err := os.Lstat(path); !os.IsNotExist(err) { - t.Errorf("expected %s to be absent; lstat error = %v", path, err) - } -} - -func assertDirectoryEmpty(t *testing.T, path string) { - t.Helper() - entries, err := os.ReadDir(path) - if err != nil { - t.Fatalf("read %s: %v", path, err) - } - if len(entries) != 0 { - t.Errorf("directory %s contains %v, want empty", path, entries) - } -} diff --git a/cmd/simslim/app.go b/cmd/simslim/app.go deleted file mode 100644 index 1ec4f5d..0000000 --- a/cmd/simslim/app.go +++ /dev/null @@ -1,154 +0,0 @@ -package main - -import ( - "context" - "fmt" - "os" - "strings" - "time" - - cli "github.com/urfave/cli/v3" - - "github.com/mobai-app/simslim" -) - -// newApp builds the command tree. It handles subcommand dispatch, the global -// --set flag, and per-command flag parsing. -func newApp() *cli.Command { - jsonFlag := func() cli.Flag { - return &cli.BoolFlag{Name: "json", Usage: "print machine-readable JSON", OnlyOnce: true} - } - preserveBootStateFlag := func(usage string) cli.Flag { - return &cli.BoolFlag{Name: "preserve-boot-state", Usage: usage} - } - - commands := []*cli.Command{ - {Name: "list", Flags: []cli.Flag{jsonFlag(), &cli.BoolFlag{Name: "booted", Usage: "only list booted simulators"}}, Action: cmdList}, - {Name: "profiles", Flags: []cli.Flag{jsonFlag()}, Action: cmdProfiles}, - {Name: "profile", Action: cmdNewProfile}, - {Name: "status", Flags: []cli.Flag{jsonFlag(), &cli.BoolFlag{Name: "dropped", Usage: "list the disabled launchd labels grouped by category"}}, Action: cmdStatus}, - {Name: "verify", Flags: []cli.Flag{ - jsonFlag(), - &cli.StringFlag{Name: "profile", Usage: "verify against a JSON profile file (mutually exclusive with --except/--keep)"}, - &cli.StringFlag{Name: "except", Usage: "comma-separated category IDs the profile leaves fully enabled (see `simslim profiles`)"}, - &cli.StringFlag{Name: "keep", Usage: "comma-separated launchd labels the profile keeps running"}, - }, Action: cmdVerify}, - {Name: "doctor", Flags: []cli.Flag{ - jsonFlag(), - &cli.StringFlag{Name: "requires", Usage: "comma-separated feature IDs the simulator must support (see `simslim doctor --list`)"}, - &cli.BoolFlag{Name: "list", Usage: "list every checkable feature and its backing daemons"}, - }, Action: cmdDoctor}, - {Name: "measure", Flags: []cli.Flag{jsonFlag()}, Action: cmdMeasure}, - {Name: "top", Flags: []cli.Flag{jsonFlag()}, Action: cmdTop}, - {Name: "size", Flags: []cli.Flag{jsonFlag()}, Action: cmdSize}, - {Name: "disk-categories", Flags: []cli.Flag{jsonFlag()}, Action: cmdDiskCategories}, - {Name: "disk-plan", Flags: []cli.Flag{jsonFlag()}, Action: cmdDiskPlan}, - {Name: "disk-clean", Flags: []cli.Flag{ - jsonFlag(), - &cli.StringFlag{Name: "categories", Usage: "comma-separated cleanable disk category IDs"}, - &cli.BoolFlag{Name: "confirm", Usage: "confirm permanent deletion"}, - preserveBootStateFlag("reboot a simulator that was booted before cleanup"), - }, Action: cmdDiskClean}, - {Name: "clone", Flags: []cli.Flag{jsonFlag()}, Action: cmdClone}, - {Name: "repair-clone", Flags: []cli.Flag{jsonFlag()}, Action: cmdRepairClone}, - {Name: "rename", Flags: []cli.Flag{jsonFlag()}, Action: cmdRename}, - {Name: "boot", Flags: []cli.Flag{jsonFlag()}, Action: cmdBoot}, - {Name: "shutdown", Flags: []cli.Flag{jsonFlag()}, Action: cmdShutdown}, - {Name: "erase", Flags: []cli.Flag{jsonFlag()}, Action: cmdErase}, - {Name: "delete", Flags: []cli.Flag{jsonFlag()}, Action: cmdDelete}, - {Name: "on", Flags: []cli.Flag{ - &cli.StringFlag{Name: "profile", Usage: "apply a JSON profile file (mutually exclusive with --except/--keep)"}, - &cli.StringFlag{Name: "except", Usage: "comma-separated category IDs to leave fully enabled (see `simslim profiles`)"}, - &cli.StringFlag{Name: "keep", Usage: "comma-separated launchd labels to keep running"}, - &cli.BoolFlag{Name: "no-reboot", Usage: "stop the daemons in the current boot session without a reboot (works on every runtime; lost at the next reboot on iOS/tvOS < 18.5, watchOS < 11.5, and visionOS < 2.5)"}, - preserveBootStateFlag("return an initially shutdown simulator to shutdown after reconfiguration"), - }, Action: cmdOn}, - {Name: "off", Flags: []cli.Flag{ - preserveBootStateFlag("return an initially shutdown simulator to shutdown after reconfiguration"), - }, Action: cmdOff}, - {Name: "enable", Flags: []cli.Flag{ - jsonFlag(), - &cli.StringFlag{Name: "save", Usage: "also add the services to this profile file, creating it if needed"}, - }, Action: cmdEnable}, - {Name: "disable", Flags: []cli.Flag{ - jsonFlag(), - &cli.StringFlag{Name: "save", Usage: "also remove the services from this profile file, creating it if needed"}, - }, Action: cmdDisable}, - {Name: "watch", Flags: []cli.Flag{ - &cli.BoolFlag{Name: "json", Usage: "print one JSON object per event on stdout (slimming, slimmed, failed, stopped, slimmed_before_boot) instead of log lines"}, - &cli.StringFlag{Name: "profile", Usage: "apply a JSON profile file (mutually exclusive with --except/--keep)"}, - &cli.StringFlag{Name: "except", Usage: "comma-separated category IDs to leave fully enabled (see `simslim profiles`)"}, - &cli.StringFlag{Name: "keep", Usage: "comma-separated launchd labels to keep running"}, - &cli.DurationFlag{Name: "interval", Usage: "how often to rescan for booting simulators", Value: simslim.DefaultWatchInterval}, - }, Action: cmdWatch}, - } - - onUsageError := func(_ context.Context, _ *cli.Command, err error, _ bool) error { - if err != nil && strings.Contains(err.Error(), "flag needs an argument: --set") { - return fmt.Errorf("--set requires a device set name (such as `testing`) or a path") - } - return err - } - for _, c := range commands { - c.OnUsageError = onUsageError - } - - return &cli.Command{ - Name: "simslim", - HideHelp: true, // root help/usage is handled by main's usage() - HideVersion: true, // version output is handled by main - OnUsageError: onUsageError, - Flags: []cli.Flag{ - &cli.StringFlag{ - Name: "set", - Usage: "also scan these device sets (comma-separated name|path)", - Action: func(_ context.Context, _ *cli.Command, value string) error { - sets := simslim.SplitList(value) - if len(sets) == 0 { - return fmt.Errorf("--set requires a device set name (such as `testing`) or a path") - } - for _, set := range sets { - simslim.RegisterDeviceSet(set) - } - return nil - }, - }, - &cli.DurationFlag{ - Name: "boot-timeout", - Usage: "max time for a simulator to boot and reconfigure (e.g. 10m, 15m); raise it for slow CI runners", - Sources: cli.EnvVars("SIMSLIM_BOOT_TIMEOUT"), - Value: simslim.BootTimeout, - Action: func(_ context.Context, _ *cli.Command, d time.Duration) error { - if d <= 0 { - return fmt.Errorf("--boot-timeout must be a positive duration (such as `15m`)") - } - simslim.BootTimeout = d - return nil - }, - }, - &cli.DurationFlag{ - Name: "spawn-timeout", - Usage: "max time for a single launchctl transition inside the simulator (e.g. 2m, 5m); raise it for slow hosts", - Sources: cli.EnvVars("SIMSLIM_SPAWN_TIMEOUT"), - Value: simslim.SpawnTimeout, - Action: func(_ context.Context, _ *cli.Command, d time.Duration) error { - if d <= 0 { - return fmt.Errorf("--spawn-timeout must be a positive duration (such as `2m`)") - } - simslim.SpawnTimeout = d - return nil - }, - }, - }, - Action: func(_ context.Context, cmd *cli.Command) error { - if args := cmd.Args().Slice(); len(args) > 0 { - fmt.Fprintf(os.Stderr, "unknown command %q\n\n", args[0]) - } - usage() - os.Exit(2) - return nil - }, - ExitErrHandler: func(_ context.Context, _ *cli.Command, _ error) {}, - Commands: commands, - } -} diff --git a/cmd/simslim/app_test.go b/cmd/simslim/app_test.go deleted file mode 100644 index ca1ea98..0000000 --- a/cmd/simslim/app_test.go +++ /dev/null @@ -1,214 +0,0 @@ -package main - -import ( - "context" - "os" - "reflect" - "strings" - "testing" - "time" - - "github.com/mobai-app/simslim" -) - -// runApp runs the CLI with stdout/stderr discarded so command output does not -// pollute the test log. It uses `profiles`, which touches neither simctl nor the -// macOS-only guard, to exercise flag and argument parsing through the real tree. -func runApp(t *testing.T, args ...string) error { - t.Helper() - devnull, err := os.OpenFile(os.DevNull, os.O_WRONLY, 0) - if err != nil { - t.Fatalf("open %s: %v", os.DevNull, err) - } - defer devnull.Close() - oldStdout, oldStderr := os.Stdout, os.Stderr - os.Stdout, os.Stderr = devnull, devnull - defer func() { os.Stdout, os.Stderr = oldStdout, oldStderr }() - return newApp().Run(context.Background(), append([]string{"simslim"}, args...)) -} - -// TestAppRegistersDeviceSets verifies the global --set flag registers the extra -// device sets, whether it appears before or after the subcommand, in equals -// form, comma-separated, or repeated (last-wins), and that a blank value errors. -func TestAppRegistersDeviceSets(t *testing.T) { - tests := []struct { - name string - args []string - wantExtra []string // tokens registered beyond the well-known sets - wantError bool - }{ - {name: "absent", args: []string{"profiles"}}, - {name: "before command", args: []string{"--set", "/a", "profiles"}, wantExtra: []string{"/a"}}, - {name: "after command", args: []string{"profiles", "--set", "/a"}, wantExtra: []string{"/a"}}, - {name: "equals form", args: []string{"profiles", "--set=/a"}, wantExtra: []string{"/a"}}, - {name: "comma-separated", args: []string{"--set", "/a,/b", "profiles"}, wantExtra: []string{"/a", "/b"}}, - {name: "comma trims blanks", args: []string{"--set=/a, ,/b", "profiles"}, wantExtra: []string{"/a", "/b"}}, - {name: "repeat is last-wins", args: []string{"--set", "/a", "--set", "/b", "profiles"}, wantExtra: []string{"/b"}}, - {name: "well-known not duplicated", args: []string{"--set", "testing", "profiles"}}, - {name: "blank value errors", args: []string{"--set", " ", "profiles"}, wantError: true}, - } - - for _, tt := range tests { - t.Run(tt.name, func(t *testing.T) { - simslim.ResetDeviceSets() - defer simslim.ResetDeviceSets() - err := runApp(t, tt.args...) - if (err != nil) != tt.wantError { - t.Fatalf("Run(%v) error = %v, wantError %v", tt.args, err, tt.wantError) - } - gotExtra := simslim.ExtraDeviceSetTokens() - if !reflect.DeepEqual(gotExtra, tt.wantExtra) { - t.Errorf("registered extra sets = %v, want %v", gotExtra, tt.wantExtra) - } - }) - } -} - -// TestAppBootTimeoutFlag verifies --boot-timeout and its SIMSLIM_BOOT_TIMEOUT env -// source override simslim.BootTimeout, and that a non-positive duration is rejected. -func TestAppBootTimeoutFlag(t *testing.T) { - const def = 10 * time.Minute - tests := []struct { - name string - args []string - env string // value for SIMSLIM_BOOT_TIMEOUT, "" to leave unset - want time.Duration - wantError bool - }{ - {name: "absent keeps default", args: []string{"profiles"}, want: def}, - {name: "before command", args: []string{"--boot-timeout", "15m", "profiles"}, want: 15 * time.Minute}, - {name: "after command", args: []string{"profiles", "--boot-timeout", "15m"}, want: 15 * time.Minute}, - {name: "equals form", args: []string{"profiles", "--boot-timeout=20m"}, want: 20 * time.Minute}, - {name: "from env", args: []string{"profiles"}, env: "12m", want: 12 * time.Minute}, - {name: "flag overrides env", args: []string{"profiles", "--boot-timeout", "9m"}, env: "12m", want: 9 * time.Minute}, - {name: "zero rejected", args: []string{"profiles", "--boot-timeout", "0"}, want: def, wantError: true}, - {name: "negative rejected", args: []string{"profiles", "--boot-timeout", "-1m"}, want: def, wantError: true}, - } - - for _, tt := range tests { - t.Run(tt.name, func(t *testing.T) { - simslim.ResetDeviceSets() - defer simslim.ResetDeviceSets() - orig := simslim.BootTimeout - simslim.BootTimeout = def - defer func() { simslim.BootTimeout = orig }() - if tt.env != "" { - t.Setenv("SIMSLIM_BOOT_TIMEOUT", tt.env) - } - err := runApp(t, tt.args...) - if (err != nil) != tt.wantError { - t.Fatalf("Run(%v) error = %v, wantError %v", tt.args, err, tt.wantError) - } - if simslim.BootTimeout != tt.want { - t.Errorf("BootTimeout = %v, want %v", simslim.BootTimeout, tt.want) - } - }) - } -} - -// TestAppFlagParsing covers per-command flag parsing: a flag may appear before -// or after a positional argument, --json rejects duplicates, an unknown flag is -// rejected, and an unknown positional fails validation. -func TestAppFlagParsing(t *testing.T) { - tests := []struct { - name string - args []string - wantError bool - }{ - {name: "json flag", args: []string{"profiles", "--json"}}, - {name: "flag before positional", args: []string{"profiles", "--json", "siri"}}, - {name: "flag after positional", args: []string{"profiles", "siri", "--json"}}, - {name: "duplicate json rejected", args: []string{"profiles", "--json", "--json", "siri"}, wantError: true}, - {name: "unknown flag rejected", args: []string{"profiles", "--nope"}, wantError: true}, - {name: "unknown category rejected", args: []string{"profiles", "does-not-exist"}, wantError: true}, - {name: "no-reboot conflicts with preserve-boot-state", args: []string{"on", "--no-reboot", "--preserve-boot-state", "X"}, wantError: true}, - } - - for _, tt := range tests { - t.Run(tt.name, func(t *testing.T) { - simslim.ResetDeviceSets() - defer simslim.ResetDeviceSets() - err := runApp(t, tt.args...) - if (err != nil) != tt.wantError { - t.Fatalf("Run(%v) error = %v, wantError %v", tt.args, err, tt.wantError) - } - }) - } -} - -// TestAppEnableDisableArguments covers the enable and disable argument checks, -// which all fail before any simulator is looked up. -func TestAppEnableDisableArguments(t *testing.T) { - const udid = "00000000-0000-0000-0000-0000000000A1" - tests := []struct { - name string - args []string - want string - }{ - {name: "enable without a UDID", args: []string{"enable"}, want: "expected a simulator UDID"}, - {name: "enable without IDs", args: []string{"enable", udid}, want: "name at least one category ID"}, - {name: "enable an unknown ID", args: []string{"enable", udid, "icloud,nope"}, want: `"nope"`}, - {name: "disable without IDs", args: []string{"disable", udid}, want: "name at least one category ID or managed daemon to disable"}, - {name: "disable --all is gone", args: []string{"disable", udid, "--all"}, want: "flag provided but not defined"}, - } - for _, tt := range tests { - t.Run(tt.name, func(t *testing.T) { - t.Setenv("PATH", t.TempDir()) // without xcrun, a lookup would fail differently - err := runApp(t, tt.args...) - if err == nil || !strings.Contains(err.Error(), tt.want) { - t.Fatalf("Run(%v) error = %v, want %q", tt.args, err, tt.want) - } - }) - } -} - -// TestUDIDAndIDsSplitsCommaLists accepts IDs as separate arguments, as -// comma-separated lists, or both, as in `simslim enable icloud,photos`. -func TestUDIDAndIDsSplitsCommaLists(t *testing.T) { - udid, ids, err := udidAndIDs([]string{"U", "icloud,photos", "com.apple.cloudd"}) - if err != nil || udid != "U" || !reflect.DeepEqual(ids, []string{"icloud", "photos", "com.apple.cloudd"}) { - t.Errorf("udidAndIDs = (%q, %v, %v), want U and [icloud photos com.apple.cloudd]", udid, ids, err) - } -} - -// TestAppSpawnTimeoutFlag verifies --spawn-timeout and its SIMSLIM_SPAWN_TIMEOUT env -// source override simslim.SpawnTimeout, and that a non-positive duration is rejected. -func TestAppSpawnTimeoutFlag(t *testing.T) { - const def = 2 * time.Minute - tests := []struct { - name string - args []string - env string // value for SIMSLIM_SPAWN_TIMEOUT, "" to leave unset - want time.Duration - wantError bool - }{ - {name: "absent keeps default", args: []string{"profiles"}, want: def}, - {name: "before command", args: []string{"--spawn-timeout", "5m", "profiles"}, want: 5 * time.Minute}, - {name: "after command", args: []string{"profiles", "--spawn-timeout", "5m"}, want: 5 * time.Minute}, - {name: "equals form", args: []string{"profiles", "--spawn-timeout=4m"}, want: 4 * time.Minute}, - {name: "from env", args: []string{"profiles"}, env: "3m", want: 3 * time.Minute}, - {name: "flag overrides env", args: []string{"profiles", "--spawn-timeout", "90s"}, env: "3m", want: 90 * time.Second}, - {name: "zero rejected", args: []string{"profiles", "--spawn-timeout", "0"}, want: def, wantError: true}, - {name: "negative rejected", args: []string{"profiles", "--spawn-timeout", "-1m"}, want: def, wantError: true}, - } - - for _, tt := range tests { - t.Run(tt.name, func(t *testing.T) { - simslim.ResetDeviceSets() - defer simslim.ResetDeviceSets() - orig := simslim.SpawnTimeout - simslim.SpawnTimeout = def - defer func() { simslim.SpawnTimeout = orig }() - if tt.env != "" { - t.Setenv("SIMSLIM_SPAWN_TIMEOUT", tt.env) - } - err := runApp(t, tt.args...) - if (err != nil) != tt.wantError { - t.Fatalf("Run(%v) error = %v, wantError %v", tt.args, err, tt.wantError) - } - if simslim.SpawnTimeout != tt.want { - t.Errorf("SpawnTimeout = %v, want %v", simslim.SpawnTimeout, tt.want) - } - }) - } -} diff --git a/cmd/simslim/format_test.go b/cmd/simslim/format_test.go deleted file mode 100644 index 8b4846f..0000000 --- a/cmd/simslim/format_test.go +++ /dev/null @@ -1,20 +0,0 @@ -package main - -import ( - "testing" -) - -func TestTruncatePreservesUnicode(t *testing.T) { - if got, want := truncate("模拟器名称", 4), "模拟器…"; got != want { - t.Fatalf("truncate() = %q, want %q", got, want) - } - if got, want := truncate("short", 10), "short"; got != want { - t.Fatalf("truncate() = %q, want %q", got, want) - } -} - -func TestHumanBytesIncludesKilobytes(t *testing.T) { - if got, want := humanBytes(8<<10), "8 KB"; got != want { - t.Fatalf("humanBytes() = %q, want %q", got, want) - } -} diff --git a/cmd/simslim/main.go b/cmd/simslim/main.go deleted file mode 100644 index 12641f4..0000000 --- a/cmd/simslim/main.go +++ /dev/null @@ -1,1196 +0,0 @@ -package main - -import ( - "context" - "encoding/json" - "errors" - "fmt" - "os" - "os/signal" - "path/filepath" - "runtime" - "sort" - "strings" - "sync" - - "github.com/mattn/go-isatty" - "github.com/mobai-app/simslim" - cli "github.com/urfave/cli/v3" -) - -// version is overwritten at build time via -ldflags "-X main.version=...". -var version = "dev" - -func main() { - if len(os.Args) < 2 { - usage() - os.Exit(2) - } - - switch os.Args[1] { - case "-v", "--version", "version": - fmt.Printf("simslim %s\n", version) - return - case "-h", "--help", "help": - usage() - return - } - - if runtime.GOOS != "darwin" { - fatal("simslim only works on macOS (it drives Apple's simulators).") - } - - ctx, cancel := signal.NotifyContext(context.Background(), os.Interrupt) - defer cancel() - - if err := newApp().Run(ctx, os.Args); err != nil { - fatal(err.Error()) - } -} - -func cmdList(ctx context.Context, cmd *cli.Command) error { - jsonOutput := cmd.Bool("json") - if cmd.Args().Len() != 0 { - return fmt.Errorf("list takes no arguments") - } - devices, err := simslim.ListDevices(ctx) - if err != nil { - return err - } - if cmd.Bool("booted") { - booted := devices[:0] - for _, d := range devices { - if d.State == "Booted" { - booted = append(booted, d) - } - } - devices = booted - } - sort.Slice(devices, func(i, j int) bool { - if devices[i].PlatformName() != devices[j].PlatformName() { - return devices[i].PlatformName() < devices[j].PlatformName() - } - if devices[i].OSVersion != devices[j].OSVersion { - return devices[i].OSVersion > devices[j].OSVersion - } - return devices[i].Name < devices[j].Name - }) - memoryByUDID := map[string]simslim.Measurement{} - memoryErrors := map[string]string{} - if jsonOutput { - bootedUDIDs := make([]string, 0) - for _, device := range devices { - if device.State == "Booted" { - bootedUDIDs = append(bootedUDIDs, device.UDID) - } - } - memoryByUDID, memoryErrors = simslim.MeasureMany(ctx, bootedUDIDs) - } - summaries := make([]simslim.DeviceSummary, 0, len(devices)) - for _, d := range devices { - managed := len((simslim.Profile{}).DesiredForDevice(d)) - tag := "shutdown" - summary := simslim.DeviceSummary{Device: d, ManagedTotal: managed} - if d.State == "Booted" { - tag = "booted" - if measurement, ok := memoryByUDID[d.UDID]; ok { - measured := measurement - summary.Memory = &measured - } - summary.MemoryError = memoryErrors[d.UDID] - if st, _, err := simslim.ReadStatusForDevice(ctx, d); err == nil { - tag = fmt.Sprintf("booted · %d/%d slim", st.ManagedDisabled, managed) - disabled := st.ManagedDisabled - summary.ManagedDisabled = &disabled - } else { - summary.StatusError = err.Error() - } - } - summaries = append(summaries, summary) - if !jsonOutput { - line := fmt.Sprintf("%s %-22s %-14s %s", d.UDID, truncate(d.Name, 22), d.RuntimeName(), tag) - if d.Set != "" && d.Set != "default" { - line += " (" + d.Set + ")" - } - fmt.Println(line) - } - } - if jsonOutput { - return writeJSON(summaries) - } - return nil -} - -func cmdProfiles(_ context.Context, cmd *cli.Command) error { - jsonOutput := cmd.Bool("json") - args := cmd.Args().Slice() - if len(args) > 1 { - return fmt.Errorf("profiles takes at most one category ID (see `simslim profiles`)") - } - if len(args) == 1 { - c, ok := simslim.CategoryByID(args[0]) - if !ok { - return fmt.Errorf("unknown category %q (see `simslim profiles`)", args[0]) - } - if jsonOutput { - return writeJSON(c) - } - fmt.Printf("%-14s %s\n", c.ID, c.Name) - fmt.Printf(" %s\n", c.Description) - fmt.Printf(" %d daemons · ~%d MB idle footprint when enabled\n", len(c.Labels), c.ApproxMemoryMB) - fmt.Printf(" When disabled: %s\n", c.Downside) - fmt.Println("\nDaemons:") - for _, l := range c.Labels { - if desc := c.ServiceDescriptions[l]; desc != "" { - fmt.Printf(" %-44s %s\n", l, desc) - } else { - fmt.Printf(" %s\n", l) - } - } - for _, service := range c.AlwaysEnabled { - fmt.Printf(" %-44s Always on — %s\n", service.Label, service.Reason) - } - return nil - } - if jsonOutput { - return writeJSON(simslim.Categories) - } - for _, c := range simslim.Categories { - fmt.Printf("%-14s %s\n", c.ID, c.Name) - fmt.Printf(" %d daemons · ~%d MB idle footprint when enabled\n", len(c.Labels), c.ApproxMemoryMB) - fmt.Printf(" When disabled: %s\n", c.Downside) - for _, service := range c.AlwaysEnabled { - fmt.Printf(" Always on: %s — %s\n", service.Label, service.Reason) - } - } - fmt.Printf("\n%d daemons across %d categories. Core workflow and deadlock-prone daemons are never disabled.\n", - len(simslim.SlimmableSet()), len(simslim.Categories)) - fmt.Println("Memory estimates are iOS 26.5 clean-boot measurements; they vary by runtime and workload and are not additive.") - return nil -} - -func cmdNewProfile(_ context.Context, cmd *cli.Command) error { - args := cmd.Args().Slice() - if len(args) > 1 { - return fmt.Errorf("profile takes an optional output path") - } - var dest string - if len(args) == 1 { - dest = args[0] - } - - intoDir := false - if dest != "" { - if info, err := os.Stat(dest); err == nil { - if info.IsDir() { - intoDir = true - } else { - return fmt.Errorf("refusing to overwrite %s", dest) - } - } - } - if !stdinIsTerminal() { - return fmt.Errorf("profile is interactive; run it in a terminal") - } - - sp, err := runProfileWizard(os.Stdin, os.Stderr, enterRawMode) - if err != nil { - if errors.Is(err, errWizardCancelled) { - fmt.Fprintln(os.Stderr, "Cancelled; no profile written.") - return nil - } - return err - } - data, err := simslim.MarshalProfile(sp) - if err != nil { - return err - } - fmt.Fprintf(os.Stderr, "Keeping %d feature(s) fully enabled and %d individual daemon(s); slimming the rest.\n", len(sp.Except), len(sp.Keep)) - - path := dest - if intoDir { - path = filepath.Join(dest, simslim.ProfileFileName(sp.Name)) - } - if path == "" { - _, err = os.Stdout.Write(data) - return err - } - - if intoDir { - if _, err := os.Stat(path); err == nil { - os.Stdout.Write(data) - return fmt.Errorf("%s already exists; printed the profile above instead of overwriting it", path) - } - } - if err := os.WriteFile(path, data, 0o644); err != nil { - return fmt.Errorf("write %s: %w", path, err) - } - fmt.Fprintf(os.Stderr, "Wrote %s. Apply it with `simslim on --profile %s`.\n", path, path) - return nil -} - -func cmdStatus(ctx context.Context, cmd *cli.Command) error { - jsonOutput := cmd.Bool("json") - showDropped := cmd.Bool("dropped") - udid, err := oneUDID(cmd.Args().Slice()) - if err != nil { - return err - } - st, disabled, err := simslim.ReadStatus(ctx, udid) - if err != nil { - return err - } - verdict := "stock" - switch { - case st.ManagedDisabled == st.ManagedTotal: - verdict = "slim" - case st.ManagedDisabled > 0: - verdict = "partially slim" - } - var dropped []simslim.DroppedCategory - if showDropped { - dropped = simslim.DroppedCategories(disabled) - } - if jsonOutput { - return writeJSON(simslim.StatusOutput{Status: st, Verdict: verdict, Dropped: dropped}) - } - fmt.Printf("%s: %d/%d managed launchd labels disabled (%s)\n", udid, st.ManagedDisabled, st.ManagedTotal, verdict) - if st.ManagedDisabled > 0 && !st.Persistent { - fmt.Println(" This runtime cannot persist launchd overrides: the state reverts to stock at the next reboot.") - } - if showDropped { - if len(dropped) == 0 { - fmt.Println(" Nothing dropped; every managed launchd label is enabled.") - } - for _, c := range dropped { - fmt.Printf(" %-14s %s — %s\n", c.ID, c.Name, c.Downside) - for _, l := range c.Labels { - fmt.Printf(" %s\n", l) - } - } - } - return nil -} - -func cmdVerify(ctx context.Context, cmd *cli.Command) error { - jsonOutput := cmd.Bool("json") - udid, err := oneUDID(cmd.Args().Slice()) - if err != nil { - return err - } - p, err := simslim.BuildProfile(cmd.String("profile"), cmd.String("except"), cmd.String("keep")) - if err != nil { - return err - } - r, err := simslim.VerifyProfile(ctx, udid, p) - if err != nil { - return err - } - if jsonOutput { - if err := writeJSON(r); err != nil { - return err - } - } else if r.OK { - fmt.Printf("%s matches the profile: all expected disable overrides are applied.\n", udid) - } else { - fmt.Printf("%s does not match the profile (%d missing, %d extra):\n", udid, len(r.Missing), len(r.Extra)) - for _, l := range r.Missing { - fmt.Printf(" missing %s (should be disabled, is enabled)\n", l) - } - for _, l := range r.Extra { - fmt.Printf(" extra %s (disabled beyond the profile)\n", l) - } - fmt.Println("Re-run `simslim on` with the same profile to repair.") - } - if !r.OK { - os.Exit(1) - } - return nil -} - -func cmdDoctor(ctx context.Context, cmd *cli.Command) error { - jsonOutput := cmd.Bool("json") - if cmd.Bool("list") { - if cmd.Args().Len() != 0 { - return fmt.Errorf("doctor --list takes no arguments") - } - if jsonOutput { - return writeJSON(simslim.Features) - } - for _, f := range simslim.Features { - fmt.Printf("%-16s %-38s %s\n", f.ID, f.Name, strings.Join(f.Labels, ", ")) - } - return nil - } - - udid, err := oneUDID(cmd.Args().Slice()) - if err != nil { - return err - } - features, err := simslim.ResolveFeatures(simslim.SplitList(cmd.String("requires"))) - if err != nil { - return err - } - if len(features) == 0 { - return fmt.Errorf("doctor needs at least one feature via --requires (see `simslim doctor --list`)") - } - - _, disabled, err := simslim.ReadStatus(ctx, udid) - if err != nil { - return err - } - report := simslim.DiagnoseFeatures(features, disabled) - report.UDID = udid - - if jsonOutput { - if err := writeJSON(report); err != nil { - return err - } - } else { - broken := 0 - for _, f := range report.Features { - if !f.OK { - broken++ - } - } - fmt.Printf("%s: %d/%d required features OK\n", udid, len(report.Features)-broken, len(report.Features)) - for _, f := range report.Features { - if f.OK { - fmt.Printf(" ok %s\n", f.ID) - } else { - fmt.Printf(" BROKEN %s — %s disabled\n", f.ID, strings.Join(f.Disabled, ", ")) - } - } - } - if !report.OK { - os.Exit(1) - } - return nil -} - -func cmdMeasure(ctx context.Context, cmd *cli.Command) error { - jsonOutput := cmd.Bool("json") - udid, err := oneUDID(cmd.Args().Slice()) - if err != nil { - return err - } - m, err := simslim.Measure(ctx, udid) - if err != nil { - return err - } - if jsonOutput { - return writeJSON(m) - } - fmt.Printf("%s: %d processes, %s memory footprint (phys_footprint)\n", udid, m.Processes, humanBytes(m.Bytes)) - return nil -} - -func cmdTop(ctx context.Context, cmd *cli.Command) error { - args := cmd.Args().Slice() - if len(args) > 1 { - return fmt.Errorf("top takes at most one simulator UDID") - } - var udid string - if len(args) == 1 { - udid = args[0] - } - - // --json and piped output are one-shot; the live TUI needs a real terminal. - if cmd.Bool("json") { - if udid != "" { - procs, err := simslim.MeasureProcesses(ctx, udid) - if err != nil { - return err - } - out := simslim.TopProcesses{UDID: udid, Name: deviceName(ctx, udid), Processes: procs} - for _, p := range procs { - out.TotalBytes += p.Bytes - } - return writeJSON(out) - } - out, err := simslim.FleetSnapshot(ctx, true) - if err != nil { - return err - } - return writeJSON(out) - } - - if !isTerminal(os.Stdout) { - if udid != "" { - procs, err := simslim.MeasureProcesses(ctx, udid) - if err != nil { - return err - } - fmt.Print(staticProcs(simslim.TopProcesses{UDID: udid, Name: deviceName(ctx, udid), Processes: procs})) - return nil - } - out, err := simslim.FleetSnapshot(ctx, false) - if err != nil { - return err - } - fmt.Print(staticFleet(out)) - return nil - } - - return runTopTUI(ctx, udid, deviceName(ctx, udid)) -} - -// deviceName resolves a friendly name for a UDID, falling back to empty on error -// so the caller can degrade to the short UDID. -func deviceName(ctx context.Context, udid string) string { - if udid == "" { - return "" - } - if d, err := simslim.FindDevice(ctx, udid, ""); err == nil { - return d.Name - } - return "" -} - -// isTerminal reports whether f is an interactive terminal, so `top` can fall -// back to a one-shot dump when piped, redirected, or run under a non-tty like -// /dev/null (which is a character device but not a terminal). -func isTerminal(f *os.File) bool { - return isatty.IsTerminal(f.Fd()) || isatty.IsCygwinTerminal(f.Fd()) -} - -func cmdSize(ctx context.Context, cmd *cli.Command) error { - jsonOutput := cmd.Bool("json") - udid, err := oneUDID(cmd.Args().Slice()) - if err != nil { - return err - } - tctx, cancel := context.WithTimeout(ctx, simslim.BootTimeout) - defer cancel() - measurement, err := simslim.DeviceDiskUsage(tctx, udid) - if err != nil { - return err - } - if jsonOutput { - return writeJSON(measurement) - } - fmt.Printf("%s: %s on disk\n", udid, humanBytes(measurement.Bytes)) - return nil -} - -func cmdDiskCategories(_ context.Context, cmd *cli.Command) error { - jsonOutput := cmd.Bool("json") - if cmd.Args().Len() != 0 { - return fmt.Errorf("disk-categories takes no arguments") - } - if jsonOutput { - return writeJSON(simslim.DiskCleanupCategories) - } - for _, category := range simslim.DiskCleanupCategories { - availability := "cleanable" - if !category.CanClean { - availability = "measured only" - } - fmt.Printf("%-22s %-28s %s · %s\n", category.ID, category.Name, category.Risk, availability) - fmt.Printf(" %s\n", category.Downside) - } - return nil -} - -func cmdDiskPlan(ctx context.Context, cmd *cli.Command) error { - jsonOutput := cmd.Bool("json") - udid, err := oneUDID(cmd.Args().Slice()) - if err != nil { - return err - } - tctx, cancel := context.WithTimeout(ctx, simslim.BootTimeout) - defer cancel() - plan, err := simslim.PlanDiskCleanup(tctx, udid) - if err != nil { - return err - } - if jsonOutput { - return writeJSON(plan) - } - fmt.Printf("%s: %s currently cleanable\n", udid, humanBytes(plan.CleanableBytes)) - for _, category := range plan.Categories { - availability := "" - if !category.CanClean { - availability = " (iOS-managed; measured only)" - } - fmt.Printf(" %-22s %8s%s\n", category.ID, humanBytes(category.Bytes), availability) - } - if len(plan.Storage) > 0 { - fmt.Println(" Stored data (read only)") - for _, storage := range plan.Storage { - fmt.Printf(" %-20s %8s\n", storage.ID, humanBytes(storage.Bytes)) - } - } - return nil -} - -func cmdDiskClean(ctx context.Context, cmd *cli.Command) error { - jsonOutput := cmd.Bool("json") - udid, err := oneUDID(cmd.Args().Slice()) - if err != nil { - return err - } - if !cmd.Bool("confirm") { - return fmt.Errorf("disk-clean permanently deletes data; pass --confirm after reviewing `simslim disk-plan %s`", udid) - } - categoryIDs := simslim.SplitList(cmd.String("categories")) - if _, err := simslim.ValidateDiskCleanupSelection(categoryIDs); err != nil { - return err - } - tctx, cancel := context.WithTimeout(ctx, simslim.BootTimeout) - defer cancel() - result, err := simslim.CleanDeviceDisk(tctx, udid, categoryIDs, cmd.Bool("preserve-boot-state")) - if err != nil { - return err - } - if jsonOutput { - return writeJSON(result) - } - fmt.Printf("Cleaned %s and reclaimed %s. Generated contents stay deleted; on-demand assets may download again when needed.\n", udid, humanBytes(result.ReclaimedBytes)) - return nil -} - -func cmdClone(ctx context.Context, cmd *cli.Command) error { - jsonOutput := cmd.Bool("json") - args := cmd.Args().Slice() - if len(args) != 2 { - return fmt.Errorf("clone expects a simulator UDID and a new name") - } - name, err := simslim.NormalizeSimulatorName(args[1]) - if err != nil { - return err - } - - tctx, cancel := context.WithTimeout(ctx, simslim.CloneOperationTimeout()) - defer cancel() - newUDID, err := simslim.CloneDevice(tctx, args[0], name) - if err != nil { - return err - } - result := simslim.SimulatorMutationOutput{Action: "clone", UDID: newUDID, Name: name, SourceUDID: args[0]} - if jsonOutput { - return writeJSON(result) - } - fmt.Printf("Cloned %s as %q (%s).\n", args[0], name, newUDID) - return nil -} - -func cmdRepairClone(ctx context.Context, cmd *cli.Command) error { - jsonOutput := cmd.Bool("json") - args := cmd.Args().Slice() - if len(args) != 2 { - return fmt.Errorf("repair-clone expects the source UDID and cloned simulator UDID") - } - - tctx, cancel := context.WithTimeout(ctx, simslim.CloneOperationTimeout()) - defer cancel() - if err := simslim.RepairClonedDevice(tctx, args[0], args[1]); err != nil { - return err - } - result := simslim.SimulatorMutationOutput{ - Action: "repair-clone", - UDID: args[1], - SourceUDID: args[0], - } - if jsonOutput { - return writeJSON(result) - } - fmt.Printf( - "Repaired clone %s and verified no links or open files into specified source %s.\n", - args[1], - args[0], - ) - return nil -} - -func cmdRename(ctx context.Context, cmd *cli.Command) error { - jsonOutput := cmd.Bool("json") - args := cmd.Args().Slice() - if len(args) != 2 { - return fmt.Errorf("rename expects a simulator UDID and a new name") - } - name, err := simslim.NormalizeSimulatorName(args[1]) - if err != nil { - return err - } - - tctx, cancel := context.WithTimeout(ctx, simslim.ShutdownTimeout) - defer cancel() - if err := simslim.RenameDevice(tctx, args[0], name); err != nil { - return err - } - result := simslim.SimulatorMutationOutput{Action: "rename", UDID: args[0], Name: name} - if jsonOutput { - return writeJSON(result) - } - fmt.Printf("Renamed %s to %q.\n", args[0], name) - return nil -} - -func cmdErase(ctx context.Context, cmd *cli.Command) error { - jsonOutput := cmd.Bool("json") - udid, err := oneUDID(cmd.Args().Slice()) - if err != nil { - return err - } - - tctx, cancel := context.WithTimeout(ctx, simslim.BootTimeout) - defer cancel() - if err := simslim.EraseDevice(tctx, udid); err != nil { - return err - } - result := simslim.SimulatorMutationOutput{Action: "erase", UDID: udid} - if jsonOutput { - return writeJSON(result) - } - fmt.Printf("Erased simulator %s.\n", udid) - return nil -} - -func cmdDelete(ctx context.Context, cmd *cli.Command) error { - jsonOutput := cmd.Bool("json") - udid, err := oneUDID(cmd.Args().Slice()) - if err != nil { - return err - } - - tctx, cancel := context.WithTimeout(ctx, simslim.BootTimeout) - defer cancel() - if err := simslim.DeleteDevice(tctx, udid); err != nil { - return err - } - result := simslim.SimulatorMutationOutput{Action: "delete", UDID: udid} - if jsonOutput { - return writeJSON(result) - } - fmt.Printf("Deleted simulator %s.\n", udid) - return nil -} - -func cmdBoot(ctx context.Context, cmd *cli.Command) error { - jsonOutput := cmd.Bool("json") - udid, err := oneUDID(cmd.Args().Slice()) - if err != nil { - return err - } - - // Resolve the exact device first so a simctl alias such as "all" can never - // enter the boot path, consistent with erase/delete. - device, err := simslim.FindDevice(ctx, udid, "") - if err != nil { - return err - } - result := simslim.SimulatorMutationOutput{Action: "boot", UDID: udid} - if device.State == "Booted" { - if jsonOutput { - return writeJSON(result) - } - fmt.Printf("Simulator %s is already booted.\n", udid) - return nil - } - - // Booting and waiting for services can take ~a minute; keep an interactive - // caller informed. Suppressed under --json so machine consumers that read a - // combined stdout/stderr stream get clean JSON. - if !jsonOutput { - fmt.Fprintf(os.Stderr, "Booting %s...\n", udid) - } - tctx, cancel := context.WithTimeout(ctx, simslim.BootTimeout) - defer cancel() - if err := simslim.BootAndWait(tctx, device.Set, udid); err != nil { - return err - } - if jsonOutput { - return writeJSON(result) - } - fmt.Printf("Booted %s.\n", udid) - return nil -} - -func cmdShutdown(ctx context.Context, cmd *cli.Command) error { - jsonOutput := cmd.Bool("json") - udid, err := oneUDID(cmd.Args().Slice()) - if err != nil { - return err - } - - // Resolve the exact device first so a simctl alias such as "all" can never - // enter the shutdown path, consistent with erase/delete. - device, err := simslim.FindDevice(ctx, udid, "") - if err != nil { - return err - } - result := simslim.SimulatorMutationOutput{Action: "shutdown", UDID: udid} - if device.State != "Booted" { - if jsonOutput { - return writeJSON(result) - } - fmt.Printf("Simulator %s is already shut down.\n", udid) - return nil - } - - tctx, cancel := context.WithTimeout(ctx, simslim.ShutdownTimeout) - defer cancel() - if err := simslim.Shutdown(tctx, device.Set, udid); err != nil { - return err - } - if err := simslim.WaitShutdown(tctx, device.Set, udid, simslim.ShutdownTimeout); err != nil { - return err - } - if jsonOutput { - return writeJSON(result) - } - fmt.Printf("Shut down %s.\n", udid) - return nil -} - -func cmdOn(ctx context.Context, cmd *cli.Command) error { - preserveBootState := cmd.Bool("preserve-boot-state") - noReboot := cmd.Bool("no-reboot") - if noReboot && preserveBootState { - return fmt.Errorf("--no-reboot cannot be combined with --preserve-boot-state: shutting the simulator down discards a no-reboot slim") - } - udid, err := oneUDID(cmd.Args().Slice()) - if err != nil { - return err - } - - p, err := simslim.BuildProfile(cmd.String("profile"), cmd.String("except"), cmd.String("keep")) - if err != nil { - return err - } - // Resolve once: this pins the device's set (routing every simctl call below, - // including a parallel-testing clone), fails fast on an unknown UDID, and - // tells us whether to restore a shutdown state afterward. - device, err := simslim.FindDevice(ctx, udid, "") - if err != nil { - return err - } - report := simslim.Reporter(func(msg string) { fmt.Fprintln(os.Stderr, msg) }) - tctx, cancel := context.WithTimeout(ctx, simslim.BootTimeout) - defer cancel() - if noReboot { - return onNoReboot(tctx, device, p, report) - } - startedShutdown := device.State == "Shutdown" - originallyShutdown := preserveBootState && startedShutdown - - if startedShutdown { - fmt.Fprintf(os.Stderr, "Slimming %s: disabling %d background services while it is off, then booting it slim.\n", udid, len(p.DesiredForDevice(device))) - } else { - fmt.Fprintf(os.Stderr, "Slimming %s: disabling %d background services. The simulator will reboot to apply the changes.\n", udid, len(p.DesiredForDevice(device))) - } - changed, operationErr := simslim.EnableSlim(tctx, device.Set, udid, p, report) - if originallyShutdown { - shutdownErr := returnToShutdown(ctx, device.Set, udid) - if operationErr != nil && shutdownErr != nil { - return fmt.Errorf("%v; additionally could not restore original shutdown state: %w", operationErr, shutdownErr) - } - if shutdownErr != nil { - return shutdownErr - } - } - if operationErr != nil { - return operationErr - } - if changed { - switch { - case originallyShutdown: - fmt.Println("Done. Simulator reconfigured slim and returned to shutdown.") - case startedShutdown: - fmt.Println("Done. Simulator reconfigured slim and booted.") - default: - fmt.Println("Done. Simulator reconfigured and rebooted slim.") - } - } else { - if originallyShutdown { - fmt.Println("Already slim. Original shutdown state restored.") - } else { - fmt.Println("Already slim. Nothing to change.") - } - } - return nil -} - -// onNoReboot is `on --no-reboot`: stop the profile's daemons now, no reboot. -// The closing line says what the next boot brings, since on iOS < 18.5 the -// state is gone after a reboot and someone will otherwise report that as a bug. -func onNoReboot(ctx context.Context, device simslim.Device, p simslim.Profile, report simslim.Reporter) error { - fmt.Fprintf(os.Stderr, "Slimming %s for this boot session: stopping %d background services without a reboot.\n", device.UDID, len(p.DesiredForDevice(device))) - changed, err := simslim.EnableSlimNoReboot(ctx, device.Set, device.UDID, p, report) - if err != nil { - return err - } - if changed { - fmt.Println("Done. Simulator slimmed for this boot session without a reboot.") - } else { - fmt.Println("Already slim. Confirmed every profiled daemon is stopped for this boot session.") - } - if device.SupportsPersistentOverrides() { - fmt.Println("The disable overrides are also stored, so the next boot should come up slim; `simslim verify` after a reboot confirms it.") - } else { - fmt.Printf("%s cannot persist overrides: the simulator returns to stock at its next boot, so re-run this command after every boot.\n", device.RuntimeName()) - } - return nil -} - -// cmdWatch slims every simulator until Ctrl-C: a shut-down one before it boots, -// by writing its launchd overrides, and every one no-reboot as it boots. It is -// also the hook for xcodebuild parallel-testing clones, which are created stock -// and deleted per run: point --set at the parallel-testing device set and run -// this alongside the test invocation. -func cmdWatch(ctx context.Context, cmd *cli.Command) error { - p, err := simslim.BuildProfile(cmd.String("profile"), cmd.String("except"), cmd.String("keep")) - if err != nil { - return err - } - if cmd.Bool("json") { - var mu sync.Mutex - encoder := json.NewEncoder(os.Stdout) - events := func(e simslim.WatchEvent) { - mu.Lock() - defer mu.Unlock() - _ = encoder.Encode(e) - } - return simslim.WatchWithEvents(ctx, p, cmd.Duration("interval"), nil, events) - } - report := simslim.Reporter(func(msg string) { fmt.Fprintln(os.Stderr, msg) }) - sets := append([]string{"default", "testing"}, simslim.ExtraDeviceSetTokens()...) - fmt.Fprintf(os.Stderr, "Watching device sets [%s]; slimming each simulator before it boots where its runtime allows, and no-reboot as it boots. Ctrl-C to stop.\n", strings.Join(sets, ", ")) - return simslim.Watch(ctx, p, cmd.Duration("interval"), report) -} - -func cmdOff(ctx context.Context, cmd *cli.Command) error { - preserveBootState := cmd.Bool("preserve-boot-state") - udid, err := oneUDID(cmd.Args().Slice()) - if err != nil { - return err - } - device, err := simslim.FindDevice(ctx, udid, "") - if err != nil { - return err - } - startedShutdown := device.State == "Shutdown" - originallyShutdown := preserveBootState && startedShutdown - if startedShutdown { - fmt.Fprintf(os.Stderr, "Restoring %s to stock while it is off, then booting it.\n", udid) - } else { - fmt.Fprintf(os.Stderr, "Restoring %s to stock. The simulator will reboot to apply the changes.\n", udid) - } - report := simslim.Reporter(func(msg string) { fmt.Fprintln(os.Stderr, msg) }) - tctx, cancel := context.WithTimeout(ctx, simslim.BootTimeout) - defer cancel() - changed, operationErr := simslim.DisableSlim(tctx, device.Set, udid, report) - if originallyShutdown { - shutdownErr := returnToShutdown(ctx, device.Set, udid) - if operationErr != nil && shutdownErr != nil { - return fmt.Errorf("%v; additionally could not restore original shutdown state: %w", operationErr, shutdownErr) - } - if shutdownErr != nil { - return shutdownErr - } - } - if operationErr != nil { - return operationErr - } - if changed { - switch { - case originallyShutdown: - fmt.Println("Done. All daemons re-enabled and simulator returned to shutdown.") - case startedShutdown: - fmt.Println("Done. All daemons re-enabled and simulator booted.") - default: - fmt.Println("Done. All daemons re-enabled and simulator rebooted.") - } - } else { - if originallyShutdown { - fmt.Println("Already stock. Original shutdown state restored.") - } else { - fmt.Println("Already stock. Nothing to change.") - } - } - return nil -} - -// cmdEnable re-enables categories or daemons on a booted simulator without a -// reboot; --save also records them in a profile file. -func cmdEnable(ctx context.Context, cmd *cli.Command) error { - jsonOutput := cmd.Bool("json") - udid, ids, err := udidAndIDs(cmd.Args().Slice()) - if err != nil { - return err - } - tctx, cancel := context.WithTimeout(ctx, simslim.BootTimeout) - defer cancel() - out, err := simslim.EnableServices(tctx, udid, ids, cmd.String("save"), progress(jsonOutput)) - if err != nil { - return err - } - if jsonOutput { - return writeJSON(out) - } - if out.Live { - fmt.Printf("Enabled %d services on %s without a reboot.\n", len(out.Labels), udid) - } - if len(out.NotStarted) > 0 { - fmt.Printf(" launchd starts %d of them at the next boot, not in this one: %s\n", len(out.NotStarted), strings.Join(out.NotStarted, ", ")) - } - printSaved(out) - return nil -} - -// cmdDisable is the inverse of enable: it stops categories or daemons on a -// booted simulator now, without a reboot; --save also removes them from a -// profile file. -func cmdDisable(ctx context.Context, cmd *cli.Command) error { - jsonOutput := cmd.Bool("json") - udid, ids, err := udidAndIDs(cmd.Args().Slice()) - if err != nil { - return err - } - tctx, cancel := context.WithTimeout(ctx, simslim.BootTimeout) - defer cancel() - out, err := simslim.DisableServices(tctx, udid, ids, cmd.String("save"), progress(jsonOutput)) - if err != nil { - return err - } - if jsonOutput { - return writeJSON(out) - } - switch { - case !out.Live: - case len(out.Labels) == 0: - fmt.Printf("Nothing to stop on %s.\n", udid) - default: - fmt.Printf("Stopped %d services on %s without a reboot.\n", len(out.Labels), udid) - } - if len(out.StillEnabled) > 0 { - fmt.Printf(" %d stay enabled for another fully enabled category or the platform: %s\n", len(out.StillEnabled), strings.Join(out.StillEnabled, ", ")) - } - printSaved(out) - return nil -} - -// printSaved closes enable and disable with what persists: the saved profile, -// or a reminder that the next `on` or `watch` pass applies its profile again. -func printSaved(out simslim.ServicesOutput) { - switch { - case out.Saved == "": - fmt.Println("This lasts until the next `on` or `watch` pass; pass --save to keep it in a profile.") - case out.Live: - fmt.Printf("Saved to %s. Apply it later with `simslim on %s --profile %s`.\n", out.Saved, out.UDID, out.Saved) - default: - fmt.Printf("Saved to %s; nothing was applied, the simulator is not booted. Apply it with `simslim on %s --profile %s`.\n", out.Saved, out.UDID, out.Saved) - } -} - -// udidAndIDs reads ` [ids...]`, where each ID argument may itself be a -// comma-separated list, as in `simslim enable icloud,photos`. The -// library says when the IDs are missing. -func udidAndIDs(args []string) (string, []string, error) { - if len(args) == 0 { - return "", nil, fmt.Errorf("expected a simulator UDID (see `simslim list`), then category IDs or launchd labels (see `simslim profiles`)") - } - var ids []string - for _, arg := range args[1:] { - ids = append(ids, simslim.SplitList(arg)...) - } - return args[0], ids, nil -} - -// progress reports to stderr, except under --json, where consumers reading a -// combined stream must get clean JSON. -func progress(jsonOutput bool) simslim.Reporter { - if jsonOutput { - return nil - } - return func(msg string) { fmt.Fprintln(os.Stderr, msg) } -} - -func returnToShutdown(ctx context.Context, set, udid string) error { - shutdownCtx, cancel := context.WithTimeout(ctx, simslim.ShutdownTimeout) - defer cancel() - if err := simslim.Shutdown(shutdownCtx, set, udid); err != nil { - return fmt.Errorf("restore original shutdown state: %w", err) - } - if err := simslim.WaitShutdown(shutdownCtx, set, udid, simslim.ShutdownTimeout); err != nil { - return fmt.Errorf("restore original shutdown state: %w", err) - } - return nil -} - -func oneUDID(args []string) (string, error) { - if len(args) != 1 { - return "", fmt.Errorf("expected exactly one simulator UDID (see `simslim list`)") - } - return args[0], nil -} - -func truncate(s string, n int) string { - runes := []rune(s) - if len(runes) <= n { - return s - } - if n <= 1 { - return "…" - } - return string(runes[:n-1]) + "…" -} - -func humanBytes(b int64) string { - switch { - case b >= 1<<30: - return fmt.Sprintf("%.2f GB", float64(b)/(1<<30)) - case b >= 1<<20: - return fmt.Sprintf("%.0f MB", float64(b)/(1<<20)) - case b >= 1<<10: - return fmt.Sprintf("%.0f KB", float64(b)/(1<<10)) - default: - return fmt.Sprintf("%d B", b) - } -} - -func fatal(msg string) { - fmt.Fprintln(os.Stderr, "simslim: "+msg) - os.Exit(1) -} - -func usage() { - fmt.Print(`simslim runs more iOS, tvOS, watchOS, and visionOS simulators on the same Mac by disabling the -background daemons a simulator does not need. - -USAGE - simslim [args] - -GLOBAL OPTIONS - --set Also scan these device sets (comma-separated). The default - and Xcode ` + "`testing`" + ` (parallel-testing) sets are always - scanned; use this to add a set at a custom path. - --boot-timeout dur Max time to boot and reconfigure a simulator (default 10m; - e.g. ` + "`15m`" + `). Raise it for slow CI runners. Also settable - via the SIMSLIM_BOOT_TIMEOUT environment variable. - --spawn-timeout dur Max time for a single launchctl transition inside the - simulator (default 2m). Raise it for hosts where a busy - first boot makes individual spawns very slow. Also - settable via the SIMSLIM_SPAWN_TIMEOUT environment - variable. - -COMMANDS - list List available simulators and their slim status - --booted Only list booted simulators - profiles [id] Show the daemon categories a slim boot disables; - pass a category ID to list that category's daemons - profile [path] Interactively build a --profile JSON file (writes to - path or into a directory, or stdout when omitted) - on Slim a simulator (persist disables + reboot slim) - --profile path Apply a committed JSON profile (see below); mutually - exclusive with --except/--keep - --except ids Leave these categories enabled (comma-separated) - --keep labels Keep these individual daemons running (comma-separated) - --no-reboot Stop the daemons in the current boot session without a - reboot. Works on every runtime, including iOS 17.x and - 18.3, where it is the only way to slim; there the state - is gone at the next reboot - --preserve-boot-state - Return an initially shutdown simulator to shutdown - off Restore a simulator to stock (re-enable + reboot) - --preserve-boot-state - Return an initially shutdown simulator to shutdown - enable Re-enable categories or individual daemons on a booted - simulator now, without a reboot. IDs are category IDs - or launchd labels, comma- or space-separated. Like - ` + "`on --no-reboot`" + `, it lasts until the next ` + "`on`" + ` or ` + "`watch`" + ` - pass applies its profile again - --save path Also add them to this profile file ("except" for a - category, "keep" for a daemon), creating it from the - default profile if needed; on a simulator that is not - booted, only the file changes - disable Stop categories or daemons on a booted simulator now, - without a reboot. A daemon shared with another category - that is fully enabled keeps running. To go back to a - profile, run ` + "`on --no-reboot --profile path`" + ` - --save path Also remove them from this profile file - watch Slim every simulator until Ctrl-C: a shut-down one before - it boots (iOS/tvOS 18.5+, watchOS 11.5+, visionOS 2.5+), - so even its first boot starts none of the profile's - daemons, and every one no-reboot as it boots. The hook - for xcodebuild parallel-testing clones, which are - created stock and deleted per run; point --set at the - parallel-testing device set - --profile path Apply a committed JSON profile (see below); mutually - exclusive with --except/--keep - --except ids Leave these categories enabled (comma-separated) - --keep labels Keep these individual daemons running (comma-separated) - --interval dur How often to rescan for booting simulators (default 3s) - --json One JSON object per event on stdout, a stable interface - for wrappers: wait for "slimmed" after a boot before - enabling services on it - status Report how slim a booted simulator is - --dropped Also list the disabled daemons grouped by category - verify Check that a booted simulator's disable overrides still - match a profile exactly; exits non-zero and lists the - drift otherwise. Catches a silently stock recreated or - erased device; re-run ` + "`on`" + ` to repair - --profile path Verify against a committed JSON profile; mutually - exclusive with --except/--keep - --except ids The profile's enabled categories (comma-separated) - --keep labels The profile's kept daemons (comma-separated) - doctor Check required features against a booted simulator; - exits non-zero if slimming has broken any of them - --requires ids Comma-separated feature IDs to verify - --list List every checkable feature and its daemons - measure Report a booted simulator's memory footprint - top [udid] Live fleet monitor: booted simulators and their RAM, - CPU, and process counts. Enter a row to drill into a - simulator's per-daemon footprint. Pass a UDID to open - that drill-down directly. --json prints a one-shot snapshot - size Report a simulator's allocated disk footprint - disk-categories Show cleanup and protected system-asset categories - disk-plan Measure reclaimable and stored data without deleting - disk-clean Permanently delete selected per-device data - --categories ids Comma-separated cleanable category IDs - --confirm Required acknowledgement of permanent deletion - --preserve-boot-state - Reboot a simulator that was booted before cleanup - clone Clone apps, data, settings, and the service profile - repair-clone - Repair source-bound state in an existing clone - rename Rename a simulator - boot Boot a simulator and wait for its services - shutdown Shut down a booted simulator - erase Erase a simulator's apps, data, and settings - delete Permanently delete a simulator - --json Print machine-readable JSON (also supported by list, - profiles, status, verify, doctor, enable, disable, and - simulator-management commands) - version Print the version - -Disabling is persistent (stored in the simulator's launchd overrides) and fully -reversible with ` + "`simslim off`" + `. Deadlock-prone daemons are never touched. -` + "`simslim enable`" + ` and ` + "`simslim disable`" + ` change a booted simulator live and keep -no state; with --save they also edit a profile, the only record of a slim -simulator, which ` + "`on`" + `, ` + "`watch`" + `, and ` + "`verify`" + ` read back. - -A ` + "`--profile`" + ` file is JSON you commit alongside your project and apply per run -(for example a ci.json and a dev.json). Its "except" and "keep" arrays match the -flags of the same name: - - { "name": "ci", "except": ["search", "store"], "keep": ["com.apple.apsd"] } - -Cleanup permanently removes existing cache, log, diagnostic, and temporary-file -contents; Erase does not bring that history back, although new generated data -appears as iOS and apps run. Downloaded language data is opt-in and may return -when a feature needs it. Required Siri assets are informational only because iOS -restores them after deletion. simslim never modifies the shared iOS runtime. - - https://github.com/mobai-app/simslim · by MobAI (https://mobai.run) -`) -} - -// writeJSON renders the machine-readable output the GUI and other integrations -// decode. It goes to stdout; progress chatter goes to stderr. -func writeJSON(value any) error { - encoder := json.NewEncoder(os.Stdout) - encoder.SetIndent("", " ") - return encoder.Encode(value) -} diff --git a/cmd/simslim/top.go b/cmd/simslim/top.go deleted file mode 100644 index ab6c385..0000000 --- a/cmd/simslim/top.go +++ /dev/null @@ -1,651 +0,0 @@ -package main - -import ( - "context" - "fmt" - "sort" - "strconv" - "strings" - "time" - - tea "github.com/charmbracelet/bubbletea" - "github.com/charmbracelet/lipgloss" - - "github.com/mobai-app/simslim" -) - -const ( - topRefresh = 2 * time.Second // fleet/process memory refresh cadence - diskTTL = 30 * time.Second // disk usage is slow, so refresh it rarely -) - -var ( - topHeaderStyle = lipgloss.NewStyle().Bold(true) - topSelStyle = lipgloss.NewStyle().Reverse(true) - topFaintStyle = lipgloss.NewStyle().Faint(true) -) - -// runTopTUI launches the interactive fleet monitor. initialUDID, when set, opens -// straight into that simulator's per-daemon drill-down. -func runTopTUI(ctx context.Context, initialUDID, initialName string) error { - m := topModel{ctx: ctx, disk: map[string]int64{}, sortCol: sortRAM, sortDesc: true} - if initialUDID != "" { - m.view = viewDrill - m.selUDID = initialUDID - m.selName = initialName - } - _, err := tea.NewProgram(m, tea.WithContext(ctx), tea.WithAltScreen()).Run() - return err -} - -type topView int - -const ( - viewFleet topView = iota - viewDrill -) - -// sortCol selects the column both the fleet table and the drill-down sort on. -type sortCol int - -const ( - sortRAM sortCol = iota - sortCPU - sortProc - sortDisk - sortName - sortState - sortOS -) - -// sortKeys maps a keypress to the column it sorts by, in header order: -// name, os, state, proc, cpu, ram, disk. Vim-nav keys (h/j/k/l) are excluded. -var sortKeys = map[string]sortCol{ - "n": sortName, "o": sortOS, "s": sortState, "p": sortProc, "c": sortCPU, "m": sortRAM, "d": sortDisk, -} - -type ( - tickMsg time.Time - fleetMsg struct { - out simslim.TopOutput - err error - } - diskMsg map[string]int64 - procMsg struct { - udid string - procs []simslim.Process - err error - } -) - -type topModel struct { - ctx context.Context - view topView - width, height int - - sims []simslim.TopSim - total int64 - cursor int - cursorUDID string // the selected sim; keeps the cursor anchored across live re-sorts - err error - loaded bool // first fleet snapshot has arrived - - disk map[string]int64 - diskAt time.Time - diskBusy bool // a du sweep is in flight; don't start another - sortCol sortCol - sortDesc bool - - selUDID string - selName string - procs []simslim.Process - procErr error - scroll int -} - -func (m topModel) Init() tea.Cmd { - return tea.Batch(m.refreshFleet(), tickCmd(), m.refreshProcs()) -} - -func tickCmd() tea.Cmd { - return tea.Tick(topRefresh, func(t time.Time) tea.Msg { return tickMsg(t) }) -} - -func (m topModel) refreshFleet() tea.Cmd { - ctx := m.ctx - return func() tea.Msg { - out, err := simslim.FleetSnapshot(ctx, false) - return fleetMsg{out: out, err: err} - } -} - -// refreshDisk measures disk for the given udids (or the current fleet when nil). -func (m topModel) refreshDisk(udids []string) tea.Cmd { - ctx := m.ctx - if udids == nil { - for _, s := range m.sims { - udids = append(udids, s.UDID) - } - } - return func() tea.Msg { - out := diskMsg{} - for _, u := range udids { - if du, err := simslim.DeviceDiskUsage(ctx, u); err == nil { - out[u] = du.Bytes - } - } - return out - } -} - -func (m topModel) refreshProcs() tea.Cmd { - if m.view != viewDrill || m.selUDID == "" { - return nil - } - ctx, udid := m.ctx, m.selUDID - return func() tea.Msg { - procs, err := simslim.MeasureProcesses(ctx, udid) - return procMsg{udid: udid, procs: procs, err: err} - } -} - -func (m topModel) Update(msg tea.Msg) (tea.Model, tea.Cmd) { - switch msg := msg.(type) { - case tea.WindowSizeMsg: - m.width, m.height = msg.Width, msg.Height - return m, nil - - case tickMsg: - cmds := []tea.Cmd{tickCmd(), m.refreshFleet()} - if c := m.refreshProcs(); c != nil { - cmds = append(cmds, c) - } - if !m.diskBusy && !m.diskAt.IsZero() && time.Since(m.diskAt) > diskTTL { - m.diskBusy = true - cmds = append(cmds, m.refreshDisk(nil)) - } - return m, tea.Batch(cmds...) - - case fleetMsg: - m.err = msg.err - if msg.err != nil { - return m, nil // keep showing the previous snapshot; footer reports the error - } - m.loaded = true - m.sims, m.total = msg.out.Sims, msg.out.TotalBytes - m.applySort() - m.reanchor() - - var missing []string - for _, s := range m.sims { - if _, ok := m.disk[s.UDID]; !ok { - missing = append(missing, s.UDID) - } - } - if len(missing) > 0 && !m.diskBusy { - m.diskBusy = true - return m, m.refreshDisk(missing) - } - return m, nil - - case diskMsg: - m.diskBusy = false - for u, b := range msg { - m.disk[u] = b - } - m.diskAt = time.Now() - if m.sortCol == sortDisk { - m.applySort() - m.reanchor() - } - return m, nil - - case procMsg: - if msg.udid == m.selUDID { - m.procs, m.procErr = msg.procs, msg.err - m.sortProcs() - if m.scroll >= len(m.procs) { - m.scroll = max(0, len(m.procs)-1) - } - } - return m, nil - - case tea.KeyMsg: - return m.handleKey(msg) - } - return m, nil -} - -func (m topModel) handleKey(msg tea.KeyMsg) (tea.Model, tea.Cmd) { - switch msg.String() { - case "q", "ctrl+c": - return m, tea.Quit - case "up", "k": - if m.view == viewFleet && m.cursor > 0 { - m.cursor-- - m.cursorUDID = m.sims[m.cursor].UDID - } else if m.view == viewDrill && m.scroll > 0 { - m.scroll-- - } - case "down", "j": - if m.view == viewFleet && m.cursor < len(m.sims)-1 { - m.cursor++ - m.cursorUDID = m.sims[m.cursor].UDID - } else if m.view == viewDrill && m.scroll < len(m.procs)-1 { - m.scroll++ - } - case "enter", "right", "l": - if m.view == viewFleet && m.cursor < len(m.sims) { - s := m.sims[m.cursor] - m.view, m.selUDID, m.selName = viewDrill, s.UDID, s.Name - m.procs, m.procErr, m.scroll = nil, nil, 0 - return m, m.refreshProcs() - } - case "esc", "left", "h": - if m.view == viewDrill { - m.view, m.selUDID, m.procs = viewFleet, "", nil - } - default: - if col, ok := sortKeys[msg.String()]; ok { - if m.view == viewDrill && col != sortRAM && col != sortCPU && col != sortName { - return m, nil - } - m.setSort(col) - } - } - return m, nil -} - -// reanchor points the cursor back at the selected sim after a re-sort or -// refresh reorders (or removes) rows. -func (m *topModel) reanchor() { - if m.cursorUDID != "" { - for i, s := range m.sims { - if s.UDID == m.cursorUDID { - m.cursor = i - return - } - } - m.cursorUDID = "" - } - if m.cursor >= len(m.sims) { - m.cursor = max(0, len(m.sims)-1) - } -} - -// setSort switches the sort column, or flips direction when the column is -// already active, then re-sorts the current view. -func (m *topModel) setSort(col sortCol) { - if m.sortCol == col { - m.sortDesc = !m.sortDesc - } else { - m.sortCol, m.sortDesc = col, true - } - m.applySort() - m.reanchor() - m.sortProcs() -} - -// applySort orders the fleet by the active column and direction. -func (m *topModel) applySort() { - less := func(a, b simslim.TopSim) bool { - switch m.sortCol { - case sortCPU: - return simCPU(a) < simCPU(b) - case sortProc: - return simProcs(a) < simProcs(b) - case sortDisk: - return m.disk[a.UDID] < m.disk[b.UDID] - case sortName: - return a.Name < b.Name - case sortState: - return simDisabled(a) < simDisabled(b) - case sortOS: - if a.PlatformName() != b.PlatformName() { - return a.PlatformName() < b.PlatformName() - } - return osLess(a.OSVersion, b.OSVersion) - default: - return simBytes(a) < simBytes(b) - } - } - sort.SliceStable(m.sims, func(i, j int) bool { - if m.sortDesc { - return less(m.sims[j], m.sims[i]) - } - return less(m.sims[i], m.sims[j]) - }) -} - -// sortProcs orders the drill-down. Only RAM/CPU/name apply to processes; other -// columns fall back to RAM so a fleet sort choice still behaves sensibly here. -func (m *topModel) sortProcs() { - less := func(a, b simslim.Process) bool { - switch m.sortCol { - case sortCPU: - return a.CPU < b.CPU - case sortName: - return a.Command < b.Command - default: - return a.Bytes < b.Bytes - } - } - sort.SliceStable(m.procs, func(i, j int) bool { - if m.sortDesc { - return less(m.procs[j], m.procs[i]) - } - return less(m.procs[i], m.procs[j]) - }) -} - -func (m topModel) View() string { - if m.view == viewDrill { - return m.drillView() - } - return m.fleetView() -} - -func (m topModel) fleetView() string { - var b strings.Builder - b.WriteString(topHeaderStyle.Render(m.fleetHeader())) - b.WriteByte('\n') - - if m.err != nil && !m.loaded { - b.WriteString(topFaintStyle.Render(m.err.Error())) - return b.String() - } - if !m.loaded { - b.WriteString(topFaintStyle.Render("Loading booted simulators…")) - b.WriteByte('\n') - return b.String() - } - if len(m.sims) == 0 { - b.WriteString(topFaintStyle.Render("No booted simulators. Boot one with `simslim boot `.")) - b.WriteByte('\n') - return b.String() + m.footer() - } - - nw := m.nameWidth() - for i, s := range m.sims { - row := fmt.Sprintf("%-*s %-14s %-6s %5s %6s %8s %8s", - nw, truncate(fmt.Sprintf("%s · %s", s.Name, shortUDID(s.UDID)), nw), - osLabel(s), stateLabel(s), procCount(s), cpuLabel(s), ramLabel(s), diskLabel(m.disk, s.UDID)) - if i == m.cursor { - b.WriteString(topSelStyle.Render(row)) - } else { - b.WriteString(row) - } - b.WriteByte('\n') - } - return b.String() + m.footer() -} - -// sortArrow returns the direction indicator when col is the active sort column. -func (m topModel) sortArrow(col sortCol) string { - if m.sortCol != col { - return "" - } - if m.sortDesc { - return "▼" - } - return "▲" -} - -func (m topModel) fleetHeader() string { - return fmt.Sprintf("%-*s %-14s %-6s %5s %6s %8s %8s", - m.nameWidth(), "SIMULATOR"+m.sortArrow(sortName), "OS"+m.sortArrow(sortOS), "STATE"+m.sortArrow(sortState), - "PROC"+m.sortArrow(sortProc), "CPU"+m.sortArrow(sortCPU), "RAM"+m.sortArrow(sortRAM), "DISK"+m.sortArrow(sortDisk)) -} - -// fleetFixedCols is every non-name column plus the single spaces between all -// seven columns: OS(14)+STATE(6)+PROC(5)+CPU(6)+RAM(8)+DISK(8) + 6 separators. -const fleetFixedCols = 53 - -// nameWidth flexes the SIMULATOR column to fill the terminal: it grows when -// there is room and shrinks (down to a floor) when there is not. -func (m topModel) nameWidth() int { - if m.width <= 0 { - return 30 // no WindowSizeMsg yet - } - switch w := m.width - fleetFixedCols; { - case w < 16: - return 16 - case w > 60: - return 60 - default: - return w - } -} - -func (m topModel) tableWidth() int { return m.nameWidth() + fleetFixedCols } - -func (m topModel) footer() string { - summary := fmt.Sprintf("%d booted · total %s", len(m.sims), fmtBytes(m.total)) - hint := "↑↓ select · ↵ open · sort n·o·s·p·c·m·d · q quit" - s := strings.Repeat("─", m.tableWidth()) + "\n" + summary + " · " + hint - if m.err != nil { - s += "\nrefresh error: " + m.err.Error() - } - return topFaintStyle.Render(s) -} - -func (m topModel) drillView() string { - var b strings.Builder - title := m.selName - if title == "" { - title = shortUDID(m.selUDID) - } - b.WriteString(topHeaderStyle.Render(fmt.Sprintf("%s — daemons by %s", title, m.drillSortLabel()))) - b.WriteString("\n\n") - - if m.procErr != nil { - b.WriteString(topFaintStyle.Render(m.procErr.Error())) - b.WriteString("\n\n") - b.WriteString(topFaintStyle.Render("esc back · q quit")) - return b.String() - } - if len(m.procs) == 0 { - b.WriteString(topFaintStyle.Render("measuring…")) - b.WriteString("\n\n") - b.WriteString(topFaintStyle.Render("esc back · q quit")) - return b.String() - } - - b.WriteString(topHeaderStyle.Render(fmt.Sprintf("%8s %6s %s", - "RAM"+m.sortArrow(sortRAM), "CPU"+m.sortArrow(sortCPU), "COMMAND"+m.sortArrow(sortName)))) - b.WriteByte('\n') - - rows := max(1, m.visibleRows()) - start := clampScroll(m.scroll, len(m.procs), rows) - end := min(len(m.procs), start+rows) - for _, p := range m.procs[start:end] { - b.WriteString(fmt.Sprintf("%8s %5.1f%% %s\n", fmtBytes(p.Bytes), p.CPU, p.Command)) - } - - pos := fmt.Sprintf("%d–%d of %d", start+1, end, len(m.procs)) - b.WriteString(topFaintStyle.Render(fmt.Sprintf("%s · ↑↓ scroll · sort m·c·n · esc back · q quit", pos))) - return b.String() -} - -// drillSortLabel names the drill-down's effective sort column (fleet-only -// columns fall back to RAM there, see sortProcs). -func (m topModel) drillSortLabel() string { - switch m.sortCol { - case sortCPU: - return "CPU" - case sortName: - return "command" - default: - return "RAM" - } -} - -// visibleRows is the process-list height: total minus title, blank, header, footer. -func (m topModel) visibleRows() int { - if m.height == 0 { - return 20 - } - return m.height - 5 -} - -// --- sort value helpers (absent memory/status sorts last under descending) --- - -func simBytes(s simslim.TopSim) int64 { - if s.Memory == nil { - return -1 - } - return s.Memory.Bytes -} - -func simCPU(s simslim.TopSim) float64 { - if s.Memory == nil { - return -1 - } - return s.Memory.CPU -} - -func simProcs(s simslim.TopSim) int { - if s.Memory == nil { - return -1 - } - return s.Memory.Processes -} - -func simDisabled(s simslim.TopSim) int { - if s.ManagedDisabled == nil { - return -1 - } - return *s.ManagedDisabled -} - -// osLess compares dotted version strings numerically ("9.0" < "26.4", which -// lexical order gets wrong). Non-numeric segments compare lexically; a missing -// version sorts first. -func osLess(a, b string) bool { - as, bs := strings.Split(a, "."), strings.Split(b, ".") - for i := 0; i < len(as) && i < len(bs); i++ { - ai, aerr := strconv.Atoi(as[i]) - bi, berr := strconv.Atoi(bs[i]) - if aerr == nil && berr == nil { - if ai != bi { - return ai < bi - } - continue - } - if as[i] != bs[i] { - return as[i] < bs[i] - } - } - return len(as) < len(bs) -} - -// --- formatting helpers --- - -func stateLabel(s simslim.TopSim) string { - if s.StatusError != "" || s.ManagedDisabled == nil { - return "?" - } - switch { - case *s.ManagedDisabled == s.ManagedTotal: - return "slim" - case *s.ManagedDisabled > 0: - return "part" - default: - return "stock" - } -} - -func osLabel(s simslim.TopSim) string { - if s.OSVersion == "" { - return "?" - } - return truncate(s.RuntimeName(), 14) -} - -func procCount(s simslim.TopSim) string { - if s.Memory == nil { - return "—" - } - return fmt.Sprintf("%d", s.Memory.Processes) -} - -func cpuLabel(s simslim.TopSim) string { - if s.Memory == nil { - return "—" - } - return fmt.Sprintf("%.0f%%", s.Memory.CPU) -} - -func ramLabel(s simslim.TopSim) string { - if s.Memory == nil { - if s.MemoryError != "" { - return "err" - } - return "—" - } - return fmtBytes(s.Memory.Bytes) -} - -func diskLabel(disk map[string]int64, udid string) string { - if b, ok := disk[udid]; ok { - return fmtBytes(b) - } - return "…" -} - -func fmtBytes(b int64) string { - const unit = 1024 - if b < unit { - return fmt.Sprintf("%dB", b) - } - div, exp := int64(unit), 0 - for n := b / unit; n >= unit; n /= unit { - div *= unit - exp++ - } - return fmt.Sprintf("%.1f%c", float64(b)/float64(div), "KMGTPE"[exp]) -} - -func shortUDID(u string) string { - if len(u) > 8 { - return u[:8] - } - return u -} - -func clampScroll(scroll, total, rows int) int { - if scroll < 0 { - return 0 - } - if scroll > total-rows { - return max(0, total-rows) - } - return scroll -} - -// --- static (non-TTY) renderers, reused by cmdTop when stdout is piped --- - -func staticFleet(out simslim.TopOutput) string { - var b strings.Builder - fmt.Fprintf(&b, "%-30s %-14s %-6s %5s %6s %8s\n", "SIMULATOR", "OS", "STATE", "PROC", "CPU", "RAM") - for _, s := range out.Sims { - fmt.Fprintf(&b, "%-30s %-14s %-6s %5s %6s %8s\n", - truncate(fmt.Sprintf("%s · %s", s.Name, shortUDID(s.UDID)), 30), - osLabel(s), stateLabel(s), procCount(s), cpuLabel(s), ramLabel(s)) - } - fmt.Fprintf(&b, "%d booted · total %s\n", len(out.Sims), fmtBytes(out.TotalBytes)) - return b.String() -} - -func staticProcs(tp simslim.TopProcesses) string { - var b strings.Builder - name := tp.Name - if name == "" { - name = shortUDID(tp.UDID) - } - fmt.Fprintf(&b, "%s — daemons by RAM\n%8s %6s %s\n", name, "RAM", "CPU", "COMMAND") - for _, p := range tp.Processes { - fmt.Fprintf(&b, "%8s %5.1f%% %s\n", fmtBytes(p.Bytes), p.CPU, p.Command) - } - return b.String() -} diff --git a/cmd/simslim/top_test.go b/cmd/simslim/top_test.go deleted file mode 100644 index f6d4788..0000000 --- a/cmd/simslim/top_test.go +++ /dev/null @@ -1,162 +0,0 @@ -package main - -import ( - "strings" - "testing" - - "github.com/mobai-app/simslim" -) - -func TestFmtBytes(t *testing.T) { - cases := map[int64]string{ - 0: "0B", - 512: "512B", - 1024: "1.0K", - 1536: "1.5K", - 1 << 20: "1.0M", - 900 * 1 << 20: "900.0M", - 1 << 30: "1.0G", - 3*1<<30 + 1<<29: "3.5G", - } - for in, want := range cases { - if got := fmtBytes(in); got != want { - t.Errorf("fmtBytes(%d) = %q, want %q", in, got, want) - } - } -} - -func TestStateLabel(t *testing.T) { - disabled := func(n int) *int { return &n } - tests := []struct { - name string - sim simslim.TopSim - want string - }{ - {"slim", simslim.TopSim{ManagedDisabled: disabled(158), ManagedTotal: 158}, "slim"}, - {"partial", simslim.TopSim{ManagedDisabled: disabled(40), ManagedTotal: 158}, "part"}, - {"stock", simslim.TopSim{ManagedDisabled: disabled(0), ManagedTotal: 158}, "stock"}, - {"unknown", simslim.TopSim{StatusError: "not booted"}, "?"}, - {"nil", simslim.TopSim{}, "?"}, - } - for _, tt := range tests { - if got := stateLabel(tt.sim); got != tt.want { - t.Errorf("%s: stateLabel = %q, want %q", tt.name, got, tt.want) - } - } -} - -func TestApplySort(t *testing.T) { - sim := func(name string, procs int, bytes int64, cpu float64) simslim.TopSim { - return simslim.TopSim{Device: simslim.Device{UDID: name, Name: name}, Memory: &simslim.Measurement{Processes: procs, Bytes: bytes, CPU: cpu}} - } - base := []simslim.TopSim{ - sim("a", 100, 300, 5), - sim("b", 50, 100, 30), - sim("c", 200, 200, 1), - } - order := func(m *topModel) string { - var s string - for _, x := range m.sims { - s += x.Name - } - return s - } - - m := &topModel{disk: map[string]int64{}, sortCol: sortRAM, sortDesc: true} - m.sims = append([]simslim.TopSim(nil), base...) - m.applySort() - if got := order(m); got != "acb" { // RAM desc: a=300, c=200, b=100 - t.Errorf("RAM desc order = %s, want acb", got) - } - - m.setSort(sortCPU) // switch column -> desc by cpu: 30,5,1 - if got := order(m); got != "bac" { - t.Errorf("CPU desc order = %s, want bac", got) - } - - m.setSort(sortCPU) // same column -> toggle to asc: 1,5,30 - if got := order(m); got != "cab" { - t.Errorf("CPU asc order = %s, want cab", got) - } - - m.setSort(sortProc) // desc by procs: 200,100,50 - if got := order(m); got != "cab" { - t.Errorf("PROC desc order = %s, want cab", got) - } -} - -func TestOSLess(t *testing.T) { - tests := []struct { - a, b string - want bool - }{ - {"9.0", "26.4", true}, // numeric, not lexical ("9" > "2" lexically) - {"26.4", "9.0", false}, - {"17.5", "18.3", true}, - {"26.4", "26.10", true}, // minor compares numerically too - {"18.3", "18.3", false}, // equal - {"18", "18.3", true}, // shorter prefix sorts first - {"", "17.5", true}, // missing version sorts first - } - for _, tt := range tests { - if got := osLess(tt.a, tt.b); got != tt.want { - t.Errorf("osLess(%q, %q) = %v, want %v", tt.a, tt.b, got, tt.want) - } - } -} - -func TestReanchor(t *testing.T) { - sim := func(name string, bytes int64) simslim.TopSim { - return simslim.TopSim{Device: simslim.Device{UDID: name, Name: name}, Memory: &simslim.Measurement{Bytes: bytes}} - } - m := &topModel{disk: map[string]int64{}, sortCol: sortRAM, sortDesc: true} - m.sims = []simslim.TopSim{sim("a", 300), sim("b", 200), sim("c", 100)} - m.cursor, m.cursorUDID = 1, "b" - - // b's RAM overtakes a's; after re-sort the cursor must follow b to row 0. - m.sims[1].Memory.Bytes = 400 - m.applySort() - m.reanchor() - if m.cursor != 0 || m.sims[m.cursor].UDID != "b" { - t.Errorf("cursor = %d (%s), want 0 (b)", m.cursor, m.sims[m.cursor].UDID) - } - - // The selected sim disappears (shut down): cursor clamps, anchor resets. - m.sims = m.sims[1:2] // only "a" remains - m.reanchor() - if m.cursor != 0 || m.cursorUDID != "" { - t.Errorf("after removal cursor = %d, anchor = %q; want 0 and empty", m.cursor, m.cursorUDID) - } -} - -func TestStaticFleet(t *testing.T) { - mem := &simslim.Measurement{Processes: 70, Bytes: 900 * 1 << 20, CPU: 12} - out := simslim.TopOutput{ - Sims: []simslim.TopSim{{Device: simslim.Device{UDID: "ABCD1234-5678", Name: "iPhone 15"}, Memory: mem}}, - TotalBytes: 900 * 1 << 20, - } - got := staticFleet(out) - for _, want := range []string{"iPhone 15", "ABCD1234", "70", "900.0M", "1 booted"} { - if !strings.Contains(got, want) { - t.Errorf("staticFleet output missing %q\n%s", want, got) - } - } -} - -func TestFleetShowsAndSortsPlatforms(t *testing.T) { - m := topModel{sortCol: sortOS, sims: []simslim.TopSim{ - {Device: simslim.Device{Name: "Watch", Platform: "watchOS", OSVersion: "11.5"}}, - {Device: simslim.Device{Name: "TV", Platform: "tvOS", OSVersion: "26.0"}}, - {Device: simslim.Device{Name: "Phone", Platform: "iOS", OSVersion: "26.5"}}, - {Device: simslim.Device{Name: "Old TV", Platform: "tvOS", OSVersion: "18.5"}}, - }} - m.applySort() - for i, want := range []string{"iOS 26.5", "tvOS 18.5", "tvOS 26.0", "watchOS 11.5"} { - if got := osLabel(m.sims[i]); got != want { - t.Errorf("OS label at %d = %q, want %q", i, got, want) - } - if got := staticFleet(simslim.TopOutput{Sims: m.sims}); !strings.Contains(got, want) { - t.Errorf("static fleet missing %q: %s", want, got) - } - } -} diff --git a/cmd/simslim/wizard.go b/cmd/simslim/wizard.go deleted file mode 100644 index 1680fdc..0000000 --- a/cmd/simslim/wizard.go +++ /dev/null @@ -1,363 +0,0 @@ -package main - -import ( - "bufio" - "errors" - "fmt" - "io" - "os" - "os/exec" - "strconv" - "strings" - - "github.com/mobai-app/simslim" -) - -// errWizardCancelled signals the user quit the builder; callers exit cleanly. -var errWizardCancelled = errors.New("cancelled") - -// stdinIsTerminal reports whether stdin is an interactive terminal. -func stdinIsTerminal() bool { - fi, err := os.Stdin.Stat() - if err != nil { - return false - } - return fi.Mode()&os.ModeCharDevice != 0 -} - -// enterRawMode puts the terminal into raw, no-echo mode on the alternate screen -// so the selector can read keystrokes and own the display. It returns the row -// count and a restore func. It uses stty to avoid a terminal-handling dependency. -func enterRawMode() (func(), int, error) { - stty := func(args ...string) *exec.Cmd { - c := exec.Command("stty", args...) - c.Stdin = os.Stdin - return c - } - saved, err := stty("-g").Output() - if err != nil { - return nil, 0, fmt.Errorf("read terminal state: %w", err) - } - rows := terminalRows(stty) - if err := stty("raw", "-echo").Run(); err != nil { - return nil, 0, fmt.Errorf("enter raw mode: %w", err) - } - fmt.Fprint(os.Stderr, "\x1b[?1049h\x1b[?25l") // alternate screen + hide cursor - return func() { - fmt.Fprint(os.Stderr, "\x1b[?25h\x1b[?1049l") // restore cursor + primary screen - _ = stty(strings.TrimSpace(string(saved))).Run() - }, rows, nil -} - -// terminalRows reports the terminal height, defaulting to 24. -func terminalRows(stty func(...string) *exec.Cmd) int { - out, err := stty("size").Output() - if err != nil { - return 24 - } - fields := strings.Fields(string(out)) - if len(fields) == 0 { - return 24 - } - n, err := strconv.Atoi(fields[0]) - if err != nil || n < 6 { - return 24 - } - return n -} - -// runProfileWizard interactively assembles a simslim.SlimProfile. Prompts go to out, -// kept off stdout so the JSON stays redirectable. enterRaw switches the terminal -// into per-keystroke mode and reports its height (a no-op in tests). -func runProfileWizard(in io.Reader, out io.Writer, enterRaw func() (func(), int, error)) (simslim.SlimProfile, error) { - r := bufio.NewReader(in) - readLine := func(label string) string { - fmt.Fprint(out, label) - line, _ := r.ReadString('\n') - return strings.TrimSpace(line) - } - - fmt.Fprintln(out, "Create a slim profile.") - fmt.Fprintln(out) - name := readLine("Name (optional): ") - description := readLine("Description (optional): ") - - restore, rows, err := enterRaw() - if err != nil { - return simslim.SlimProfile{}, err - } - defer restore() - - except, keep, cancelled := selectProfile(r, out, rows) - if cancelled { - return simslim.SlimProfile{}, errWizardCancelled - } - - // Catalog order, and drop keeps inside an enabled feature (redundant). - var exceptIDs, keptLabels []string - for _, c := range simslim.Categories { - if except[c.ID] { - exceptIDs = append(exceptIDs, c.ID) - continue - } - for _, l := range c.Labels { - if keep[l] { - keptLabels = append(keptLabels, l) - } - } - } - return simslim.SlimProfile{Name: name, Description: description, Except: exceptIDs, Keep: keptLabels}, nil -} - -// key is a normalized keystroke from readKey. -type key int - -const ( - keyOther key = iota - keyUp - keyDown - keyLeft - keyRight - keyEnter - keySpace - keyRune - keyCancel // Ctrl-C -) - -// readKey reads one keystroke, decoding arrow sequences. The rune is set for keyRune. -func readKey(r *bufio.Reader) (key, rune) { - b, err := r.ReadByte() - if err != nil { - return keyCancel, 0 - } - switch b { - case '\r', '\n': - return keyEnter, 0 - case ' ': - return keySpace, 0 - case 3: // Ctrl-C - return keyCancel, 0 - case 0x1b: // arrow keys arrive as ESC [ A/B/C/D - if b1, err := r.ReadByte(); err != nil || b1 != '[' { - return keyOther, 0 - } - switch b2, _ := r.ReadByte(); b2 { - case 'A': - return keyUp, 0 - case 'B': - return keyDown, 0 - case 'C': - return keyRight, 0 - case 'D': - return keyLeft, 0 - } - return keyOther, 0 - default: - return keyRune, rune(b) - } -} - -// selectProfile runs the feature checklist: space keeps a whole feature, → drills -// into its daemons. Returns the chosen Except and Keep sets. See the footer for keys. -func selectProfile(r *bufio.Reader, out io.Writer, termRows int) (except, keep map[string]bool, cancelled bool) { - except = map[string]bool{} - keep = map[string]bool{} - header := []string{ - "simslim.Features to keep enabled — everything unchecked is slimmed.", - "[x] whole feature kept · [~] some daemons kept", - } - footer := "↑/↓ move · space keep feature · → pick daemons · a all · n none · enter save · q cancel" - visible := viewportRows(termRows, len(header)) - cursor, top := 0, 0 - for { - rows := categoryRows(except, keep) - top = windowTop(top, cursor, visible, len(rows)) - drawChecklist(out, header, rows, footer, cursor, top, visible) - k, ch := readKey(r) - switch { - case k == keyUp, k == keyRune && ch == 'k': - cursor = clampCursor(cursor-1, len(rows)) - case k == keyDown, k == keyRune && ch == 'j': - cursor = clampCursor(cursor+1, len(rows)) - case k == keyEnter: - return except, keep, false - case k == keyCancel, k == keyRune && (ch == 'q' || ch == 'Q'): - return nil, nil, true - case k == keySpace: - toggleMember(except, simslim.Categories[cursor].ID) - case k == keyRight, k == keyRune && ch == 'l': - if selectDaemons(r, out, simslim.Categories[cursor], keep, termRows) { - return nil, nil, true - } - case k == keyRune && (ch == 'a' || ch == 'A'): - for _, c := range simslim.Categories { - except[c.ID] = true - } - case k == keyRune && (ch == 'n' || ch == 'N'): - for id := range except { - delete(except, id) - } - } - } -} - -// selectDaemons runs one feature's daemon checklist, mutating keep in place. ←/h -// returns to the feature list; Ctrl-C aborts the whole wizard (via cancelled). -func selectDaemons(r *bufio.Reader, out io.Writer, c simslim.Category, keep map[string]bool, termRows int) (cancelled bool) { - header := []string{ - c.Name + " — keep individual daemons enabled.", - "Unchecked daemons in this feature are slimmed.", - } - footer := "↑/↓ move · space keep daemon · a all · n none · ← back · q cancel" - visible := viewportRows(termRows, len(header)) - cursor, top := 0, 0 - for { - rows := daemonRows(c, keep) - top = windowTop(top, cursor, visible, len(rows)) - drawChecklist(out, header, rows, footer, cursor, top, visible) - k, ch := readKey(r) - switch { - case k == keyUp, k == keyRune && ch == 'k': - cursor = clampCursor(cursor-1, len(rows)) - case k == keyDown, k == keyRune && ch == 'j': - cursor = clampCursor(cursor+1, len(rows)) - case k == keyLeft, k == keyEnter, k == keyRune && (ch == 'h' || ch == 'q' || ch == 'Q'): - return false - case k == keyCancel: - return true - case k == keySpace: - toggleMember(keep, c.Labels[cursor]) - case k == keyRune && (ch == 'a' || ch == 'A'): - for _, l := range c.Labels { - keep[l] = true - } - case k == keyRune && (ch == 'n' || ch == 'N'): - for _, l := range c.Labels { - delete(keep, l) - } - } - } -} - -// categoryRows renders the feature list. Marker: [x] fully kept, [~] some daemons -// kept, [ ] slimmed. -func categoryRows(except, keep map[string]bool) []string { - rows := make([]string, len(simslim.Categories)) - for i, c := range simslim.Categories { - box := "[ ]" - suffix := "" - switch { - case except[c.ID]: - box = "[x]" - default: - if n := categoryKeepCount(c, keep); n > 0 { - box = "[~]" - suffix = fmt.Sprintf(" (%d kept)", n) - } - } - rows[i] = fmt.Sprintf("%s %-14s %s%s", box, c.ID, c.Name, suffix) - } - return rows -} - -// daemonRows renders one feature's daemons with a [x]/[ ] keep marker. -func daemonRows(c simslim.Category, keep map[string]bool) []string { - rows := make([]string, len(c.Labels)) - for i, l := range c.Labels { - box := "[ ]" - if keep[l] { - box = "[x]" - } - line := fmt.Sprintf("%s %s", box, l) - if desc := c.ServiceDescriptions[l]; desc != "" { - line = fmt.Sprintf("%s %-44s %s", box, l, desc) - } - rows[i] = truncate(line, 76) - } - return rows -} - -func categoryKeepCount(c simslim.Category, keep map[string]bool) int { - n := 0 - for _, l := range c.Labels { - if keep[l] { - n++ - } - } - return n -} - -// drawChecklist repaints the screen: header, a windowed slice of rows with a ❯ -// cursor, and a footer. It clears first, so each call fully replaces the frame. -func drawChecklist(out io.Writer, header, rows []string, footer string, cursor, top, visible int) { - fmt.Fprint(out, "\x1b[H\x1b[J") // home + clear to end of screen - for _, h := range header { - fmt.Fprintf(out, "%s\r\n", h) - } - end := top + visible - if end > len(rows) { - end = len(rows) - } - for i := top; i < end; i++ { - pointer := " " - if i == cursor { - pointer = "❯ " - } - fmt.Fprintf(out, "%s%s\r\n", pointer, rows[i]) - } - more := "" - if top > 0 { - more += " ↑more" - } - if end < len(rows) { - more += " ↓more" - } - fmt.Fprintf(out, "\r\n%s%s", footer, more) -} - -// viewportRows is how many list rows fit given the terminal height and header. -func viewportRows(termRows, headerLines int) int { - v := termRows - headerLines - 2 // one blank line + one footer line - if v < 3 { - return 3 - } - return v -} - -// windowTop scrolls the viewport so the cursor stays visible. -func windowTop(top, cursor, visible, total int) int { - if total <= visible { - return 0 - } - if cursor < top { - top = cursor - } - if cursor >= top+visible { - top = cursor - visible + 1 - } - if top > total-visible { - top = total - visible - } - if top < 0 { - top = 0 - } - return top -} - -func clampCursor(v, n int) int { - if v < 0 { - return 0 - } - if v > n-1 { - return n - 1 - } - return v -} - -func toggleMember(set map[string]bool, key string) { - if set[key] { - delete(set, key) - } else { - set[key] = true - } -} diff --git a/cmd/simslim/wizard_test.go b/cmd/simslim/wizard_test.go deleted file mode 100644 index 53fef3a..0000000 --- a/cmd/simslim/wizard_test.go +++ /dev/null @@ -1,167 +0,0 @@ -package main - -import ( - "io" - "os" - "path/filepath" - "reflect" - "strings" - "testing" - - "github.com/mobai-app/simslim" -) - -// writeProfile writes contents to a temp file and returns its path. -func writeProfile(t *testing.T, contents string) string { - t.Helper() - path := filepath.Join(t.TempDir(), "profile.json") - if err := os.WriteFile(path, []byte(contents), 0o600); err != nil { - t.Fatalf("write profile: %v", err) - } - return path -} - -func TestRunProfileWizard(t *testing.T) { - tests := []struct { - name string - input string - wantName string - wantDesc string - wantExcept []string - wantKeep []string - }{ - { - name: "space keeps whole features siri and search", - input: "ci\nUI test runs\n" + arrowDown + space + arrowDown + space + enter, - wantName: "ci", - wantDesc: "UI test runs", - wantExcept: []string{"siri", "search"}, // catalog order, not visit order - }, - { - name: "vim key navigates features", - input: "\n\n" + "j" + space + enter, - wantExcept: []string{"siri"}, - }, - { - name: "toggle feature twice clears", - input: "\n\n" + space + space + enter, - wantExcept: nil, - }, - { - name: "all then none clears features", - input: "\n\n" + "an" + enter, - wantExcept: nil, - }, - { - name: "enter with nothing checked", - input: "\n\n" + enter, - wantExcept: nil, - }, - { - name: "unbound keys are ignored", - input: "\n\n" + "zZ" + space + enter, - wantExcept: []string{"widgets"}, // z/Z do nothing; space keeps the cursor row - }, - { - name: "arrow up clamps at the top", - input: "\n\n" + arrowUp + space + enter, - wantExcept: []string{"widgets"}, - }, - { - // Drill into siri (row 2), keep its first daemon, back out, save. - name: "drill in keeps an individual daemon", - input: "\n\n" + arrowDown + arrowRight + space + arrowLeft + enter, - wantKeep: []string{"com.apple.assistant_cdmd"}, - }, - { - // A kept daemon is dropped when its whole feature is also kept. - name: "feature kept prunes its daemon keeps", - input: "\n\n" + arrowDown + space + arrowRight + space + arrowLeft + enter, - wantExcept: []string{"siri"}, - wantKeep: nil, - }, - } - for _, tt := range tests { - t.Run(tt.name, func(t *testing.T) { - sp, err := runProfileWizard(strings.NewReader(tt.input), io.Discard, noRawMode) - if err != nil { - t.Fatalf("runProfileWizard() error = %v", err) - } - if sp.Name != tt.wantName { - t.Errorf("Name = %q, want %q", sp.Name, tt.wantName) - } - if sp.Description != tt.wantDesc { - t.Errorf("Description = %q, want %q", sp.Description, tt.wantDesc) - } - if !reflect.DeepEqual(sp.Except, tt.wantExcept) { - t.Errorf("Except = %v, want %v", sp.Except, tt.wantExcept) - } - if !reflect.DeepEqual(sp.Keep, tt.wantKeep) { - t.Errorf("Keep = %v, want %v", sp.Keep, tt.wantKeep) - } - }) - } -} - -// TestRunProfileWizardCancel confirms q reports cancellation. -func TestRunProfileWizardCancel(t *testing.T) { - if _, err := runProfileWizard(strings.NewReader("\n\nq"), io.Discard, noRawMode); err != errWizardCancelled { - t.Errorf("runProfileWizard(q) error = %v, want errWizardCancelled", err) - } -} - -// TestRunProfileWizardSelectAll confirms "a" checks every category so the -// resulting Except list covers the full catalog in order. -func TestRunProfileWizardSelectAll(t *testing.T) { - sp, err := runProfileWizard(strings.NewReader("\n\na"+enter), io.Discard, noRawMode) - if err != nil { - t.Fatalf("runProfileWizard() error = %v", err) - } - if len(sp.Except) != len(simslim.Categories) { - t.Fatalf("Except has %d entries, want %d", len(sp.Except), len(simslim.Categories)) - } - for i, c := range simslim.Categories { - if sp.Except[i] != c.ID { - t.Errorf("Except[%d] = %q, want %q", i, sp.Except[i], c.ID) - } - } -} - -// TestWizardOutputRoundTrips confirms a wizard result marshals to JSON that -// loads back into an equivalent simslim.Profile. -func TestWizardOutputRoundTrips(t *testing.T) { - sp, err := runProfileWizard(strings.NewReader("ci\n\n"+arrowDown+space+arrowDown+space+enter), io.Discard, noRawMode) - if err != nil { - t.Fatalf("runProfileWizard() error = %v", err) - } - data, err := simslim.MarshalProfile(sp) - if err != nil { - t.Fatalf("simslim.MarshalProfile() error = %v", err) - } - path := writeProfile(t, string(data)) - p, err := simslim.LoadSlimProfile(path) - if err != nil { - t.Fatalf("simslim.LoadSlimProfile() error = %v", err) - } - want := map[string]bool{"siri": true, "search": true} - if !reflect.DeepEqual(p.ExceptCategories, want) { - t.Errorf("round-tripped ExceptCategories = %v, want %v", p.ExceptCategories, want) - } -} - -// noRawMode is the enterRaw hook for tests: it skips terminal manipulation and -// hands back a no-op restore plus a fixed height, so the wizard reads scripted -// keystrokes from a plain reader. -func noRawMode() (func(), int, error) { return func() {}, 24, nil } - -// Keystroke sequences the wizard consumes after the two (name, description) -// lines. Categories are ordered widgets, siri, search, ... so one arrowDown -// lands on siri, two on search. -const ( - arrowDown = "\x1b[B" - arrowUp = "\x1b[A" - arrowRight = "\x1b[C" - arrowLeft = "\x1b[D" - space = " " - enter = "\r" -) diff --git a/device_set_test.go b/device_set_test.go deleted file mode 100644 index 58dbd1b..0000000 --- a/device_set_test.go +++ /dev/null @@ -1,59 +0,0 @@ -package simslim - -import ( - "reflect" - "testing" -) - -func TestSimctlArgsForSet(t *testing.T) { - t.Run("default set omits --set", func(t *testing.T) { - got := simctlArgsForSet("", "boot", "UDID") - want := []string{"simctl", "boot", "UDID"} - if !reflect.DeepEqual(got, want) { - t.Errorf("simctlArgsForSet() = %v, want %v", got, want) - } - }) - t.Run("named set injects --set before the subcommand", func(t *testing.T) { - got := simctlArgsForSet("testing", "boot", "UDID") - want := []string{"simctl", "--set", "testing", "boot", "UDID"} - if !reflect.DeepEqual(got, want) { - t.Errorf("simctlArgsForSet() = %v, want %v", got, want) - } - }) - t.Run("simctlArgs maps a set name to its --set token", func(t *testing.T) { - got := simctlArgs("testing", "list", "devices", "-j") - want := []string{"simctl", "--set", "testing", "list", "devices", "-j"} - if !reflect.DeepEqual(got, want) { - t.Errorf("simctlArgs() = %v, want %v", got, want) - } - if got := simctlArgs("default", "list"); !reflect.DeepEqual(got, []string{"simctl", "list"}) { - t.Errorf("simctlArgs(default) = %v, want no --set", got) - } - }) -} - -func TestDeviceSetToken(t *testing.T) { - if got := deviceSetToken("default"); got != "" { - t.Errorf("deviceSetToken(default) = %q, want empty", got) - } - if got := deviceSetToken("testing"); got != "testing" { - t.Errorf("deviceSetToken(testing) = %q, want testing", got) - } - if deviceSetToken("unknown-set") != "" { - t.Error("an unknown set name should fall back to the default token") - } -} - -func TestRegisterDeviceSetRoutes(t *testing.T) { - extraDeviceSets = nil - defer func() { extraDeviceSets = nil }() - RegisterDeviceSet("/custom/set") - // A registered set becomes discoverable like any other. - if deviceSetToken("/custom/set") != "/custom/set" { - t.Errorf("registered set not resolvable by name") - } - // A custom set's simctl args carry it as --set. - if got := simctlArgsForSet("/custom/set", "boot", "U"); !reflect.DeepEqual(got, []string{"simctl", "--set", "/custom/set", "boot", "U"}) { - t.Errorf("simctlArgsForSet(custom) = %v", got) - } -} diff --git a/disabled_store.go b/disabled_store.go deleted file mode 100644 index f7e0874..0000000 --- a/disabled_store.go +++ /dev/null @@ -1,169 +0,0 @@ -package simslim - -import ( - "bytes" - "encoding/xml" - "errors" - "fmt" - "io" - "io/fs" - "os" - "path/filepath" - "sort" -) - -// launchd_sim is a host process, so a simulator's launchd disable overrides are -// not in the device's data directory: they live in the same per-device host -// directory as its launchd.log, keyed only by UDID. launchd_sim reads the file -// when it starts and rewrites it on every `launchctl disable`/`enable`, which is -// why the overrides survive `simctl erase` but not `simctl clone`. -// -// disabledStoreRoot is a var so tests can redirect it away from the real host path. -var disabledStoreRoot = "/private/var/tmp" - -func disabledStoreDir(udid string) string { - return filepath.Join(disabledStoreRoot, "com.apple.CoreSimulator.SimDevice."+udid) -} - -func disabledStorePath(udid string) string { - return filepath.Join(disabledStoreDir(udid), "disabled.plist") -} - -// readDisabledStore returns the labels the store marks disabled, mirroring -// readDisabled's contract: a label absent from the result is enabled. A device -// that has never booted has no store, which is the same thing as nothing -// disabled, so a missing file is not an error. -func readDisabledStore(udid string) (map[string]bool, error) { - entries, err := readStoreEntries(udid) - if err != nil { - return nil, err - } - disabled := map[string]bool{} - for label, off := range entries { - if off { - disabled[label] = true - } - } - return disabled, nil -} - -// readStoreEntries returns every entry verbatim, including the explicit -// false (enabled) entries the runtime writes for itself, which a merge must -// preserve. -func readStoreEntries(udid string) (map[string]bool, error) { - f, err := os.Open(disabledStorePath(udid)) - if errors.Is(err, fs.ErrNotExist) { - return map[string]bool{}, nil - } - if err != nil { - return nil, err - } - defer f.Close() - return parseStoreEntries(f) -} - -// writeDisabledStore merges the transitions into the store, leaving every other -// entry exactly as it was: the runtime writes its own explicit-enable entries -// here, and labels outside the managed set are never simslim's business. The -// write is atomic so launchd_sim can never read a half-written store. -func writeDisabledStore(udid string, toDisable, toEnable []string) error { - entries, err := readStoreEntries(udid) - if err != nil { - return err - } - for _, label := range toDisable { - entries[label] = true - } - for _, label := range toEnable { - entries[label] = false - } - dir := disabledStoreDir(udid) - if err := os.MkdirAll(dir, 0o700); err != nil { - return fmt.Errorf("create launchd disable store: %w", err) - } - temp, err := os.CreateTemp(dir, "disabled.plist.*") - if err != nil { - return fmt.Errorf("write launchd disable store: %w", err) - } - defer os.Remove(temp.Name()) - if _, err := temp.Write(encodeStoreEntries(entries)); err != nil { - temp.Close() - return fmt.Errorf("write launchd disable store: %w", err) - } - if err := temp.Close(); err != nil { - return fmt.Errorf("write launchd disable store: %w", err) - } - if err := os.Chmod(temp.Name(), 0o644); err != nil { - return fmt.Errorf("write launchd disable store: %w", err) - } - if err := os.Rename(temp.Name(), disabledStorePath(udid)); err != nil { - return fmt.Errorf("write launchd disable store: %w", err) - } - return nil -} - -// encodeStoreEntries renders the store in the same XML plist shape launchd_sim -// writes, sorted so a rewrite that changes nothing produces an identical file. -func encodeStoreEntries(entries map[string]bool) []byte { - var b bytes.Buffer - b.WriteString(xml.Header) - b.WriteString("\n") - b.WriteString("\n\n") - for _, label := range sortedKeys(entries) { - b.WriteString("\t") - xml.EscapeText(&b, []byte(label)) - b.WriteString("\n\t<") - if entries[label] { - b.WriteString("true") - } else { - b.WriteString("false") - } - b.WriteString("/>\n") - } - b.WriteString("\n\n") - return b.Bytes() -} - -func sortedKeys(entries map[string]bool) []string { - labels := make([]string, 0, len(entries)) - for label := range entries { - labels = append(labels, label) - } - sort.Strings(labels) - return labels -} - -// parseStoreEntries reads the flat label| dict that -// launchd_sim writes. Anything else in the file is ignored rather than rejected, -// so an unexpected value type cannot make the store unreadable. -func parseStoreEntries(r io.Reader) (map[string]bool, error) { - entries := map[string]bool{} - decoder := xml.NewDecoder(r) - label := "" - for { - token, err := decoder.Token() - if errors.Is(err, io.EOF) { - return entries, nil - } - if err != nil { - return nil, fmt.Errorf("parse launchd disable store: %w", err) - } - start, ok := token.(xml.StartElement) - if !ok { - continue - } - switch start.Name.Local { - case "key": - var text string - if err := decoder.DecodeElement(&text, &start); err != nil { - return nil, fmt.Errorf("parse launchd disable store: %w", err) - } - label = text - case "true", "false": - if label != "" { - entries[label] = start.Name.Local == "true" - label = "" - } - } - } -} diff --git a/disabled_store_test.go b/disabled_store_test.go deleted file mode 100644 index 45c29ff..0000000 --- a/disabled_store_test.go +++ /dev/null @@ -1,144 +0,0 @@ -package simslim - -import ( - "os" - "path/filepath" - "testing" -) - -// storeFixture is the shape launchd_sim writes: a flat dict of label to bool, -// where true means disabled and false means an explicit enable. -const storeFixture = ` - - - - com.apple.assistantd - - com.apple.nanonewscd - - com.apple.tipsd - - - -` - -func TestReadDisabledStoreParsesLaunchdPlist(t *testing.T) { - udid := "00000000-0000-0000-0000-0000000000AA" - seedStore(t, udid, storeFixture) - - got, err := readDisabledStore(udid) - if err != nil { - t.Fatalf("readDisabledStore: %v", err) - } - want := map[string]bool{"com.apple.assistantd": true, "com.apple.tipsd": true} - if len(got) != len(want) { - t.Fatalf("readDisabledStore() = %v, want %v", got, want) - } - for label := range want { - if !got[label] { - t.Errorf("label %q not reported as disabled", label) - } - } -} - -func TestWriteDisabledStorePreservesEntriesItDoesNotOwn(t *testing.T) { - udid := "00000000-0000-0000-0000-0000000000BB" - seedStore(t, udid, ` - - - com.apple.assistantd - - com.apple.nanonewscd - - com.example.unmanaged - - - -`) - - if err := writeDisabledStore(udid, []string{"com.apple.tipsd"}, []string{"com.apple.assistantd"}); err != nil { - t.Fatalf("writeDisabledStore: %v", err) - } - - got, err := readStoreEntries(udid) - if err != nil { - t.Fatalf("readStoreEntries: %v", err) - } - want := map[string]bool{ - "com.apple.tipsd": true, // newly disabled - "com.apple.assistantd": false, // re-enabled - "com.apple.nanonewscd": false, // the runtime's own entry, untouched - "com.example.unmanaged": true, // never simslim's business, untouched - } - if len(got) != len(want) { - t.Fatalf("store entries = %v, want %v", got, want) - } - for label, off := range want { - if got[label] != off { - t.Errorf("entry %q = %t, want %t", label, got[label], off) - } - } -} - -func TestWriteDisabledStoreSeedsANeverBootedDevice(t *testing.T) { - udid := "00000000-0000-0000-0000-0000000000CC" - useTempStoreRoot(t) - - if err := writeDisabledStore(udid, []string{"com.apple.tipsd"}, nil); err != nil { - t.Fatalf("writeDisabledStore: %v", err) - } - - disabled, err := readDisabledStore(udid) - if err != nil { - t.Fatalf("readDisabledStore: %v", err) - } - if !disabled["com.apple.tipsd"] { - t.Errorf("seeded store = %v, want com.apple.tipsd disabled", disabled) - } - info, err := os.Stat(disabledStoreDir(udid)) - if err != nil { - t.Fatalf("stat store dir: %v", err) - } - if got := info.Mode().Perm(); got != 0o700 { - t.Errorf("store dir mode = %o, want 700 to match CoreSimulator", got) - } -} - -func TestReadDisabledStoreTreatsAMissingStoreAsNothingDisabled(t *testing.T) { - useTempStoreRoot(t) - - disabled, err := readDisabledStore("00000000-0000-0000-0000-0000000000DD") - if err != nil { - t.Fatalf("readDisabledStore on a never-booted device: %v", err) - } - if len(disabled) != 0 { - t.Errorf("readDisabledStore() = %v, want empty", disabled) - } -} - -// useTempStoreRoot redirects the store root at a temp dir for the test's lifetime. -func useTempStoreRoot(t *testing.T) string { - t.Helper() - root := t.TempDir() - orig := disabledStoreRoot - disabledStoreRoot = root - t.Cleanup(func() { disabledStoreRoot = orig }) - return root -} - -// seedStore points the store root at a temp dir and writes raw contents for udid. -func seedStore(t *testing.T, udid, contents string) string { - t.Helper() - root := useTempStoreRoot(t) - dir := filepath.Join(root, "com.apple.CoreSimulator.SimDevice."+udid) - if err := os.MkdirAll(dir, 0o700); err != nil { - t.Fatal(err) - } - path := filepath.Join(dir, "disabled.plist") - if contents != "" { - if err := os.WriteFile(path, []byte(contents), 0o644); err != nil { - t.Fatal(err) - } - } - return path -} diff --git a/disk.go b/disk.go deleted file mode 100644 index cd4f80b..0000000 --- a/disk.go +++ /dev/null @@ -1,42 +0,0 @@ -package simslim - -import ( - "context" - "fmt" - "os/exec" - "path/filepath" - "strconv" - "strings" -) - -// deviceDiskUsage reports allocated filesystem blocks for one exact simulator -// device directory. It deliberately resolves the UDID through simctl first so -// aliases such as "all" can never become filesystem paths. -func DeviceDiskUsage(ctx context.Context, udid string) (DiskMeasurement, error) { - _, dataDirectory, err := simulatorDataDirectory(ctx, udid) - if err != nil { - return DiskMeasurement{}, err - } - devicePath := filepath.Dir(dataDirectory) - out, err := exec.CommandContext(ctx, "du", "-sk", devicePath).CombinedOutput() - if err != nil { - return DiskMeasurement{}, fmt.Errorf("measure simulator disk usage: %w: %s", err, strings.TrimSpace(string(out))) - } - bytes, err := parseDUDiskUsage(out) - if err != nil { - return DiskMeasurement{}, err - } - return DiskMeasurement{Bytes: bytes}, nil -} - -func parseDUDiskUsage(output []byte) (int64, error) { - fields := strings.Fields(string(output)) - if len(fields) == 0 { - return 0, fmt.Errorf("du returned no disk usage") - } - kib, err := strconv.ParseInt(fields[0], 10, 64) - if err != nil || kib < 0 { - return 0, fmt.Errorf("parse du disk usage %q", fields[0]) - } - return kib * 1024, nil -} diff --git a/disk_cleanup.go b/disk_cleanup.go deleted file mode 100644 index a88c812..0000000 --- a/disk_cleanup.go +++ /dev/null @@ -1,531 +0,0 @@ -package simslim - -import ( - "context" - "fmt" - "os" - "path/filepath" - "sort" - "strings" - "syscall" -) - -// DiskCleanupCategory describes one tightly allowlisted class of per-device -// data. Runtime files are deliberately outside this model: an iOS runtime is -// shared by many simulators and must only be managed by Xcode/simctl. -type DiskCleanupCategory struct { - ID string `json:"id"` - Name string `json:"name"` - Description string `json:"description"` - Downside string `json:"downside"` - Recovery string `json:"recovery"` - Risk string `json:"risk"` - DefaultSelected bool `json:"defaultSelected"` - CanClean bool `json:"canClean"` -} - -var DiskCleanupCategories = []DiskCleanupCategory{ - { - ID: "caches", - Name: "System & App Caches", - Description: "Generated cache files belonging to iOS and installed apps.", - Downside: "Next launches may be slower; downloaded or offline cache content can disappear.", - Recovery: "Old cache contents stay deleted; apps build new caches as needed.", - Risk: "Lower risk", - DefaultSelected: true, - CanClean: true, - }, - { - ID: "logs", - Name: "Logs & Diagnostics", - Description: "Unified logs, signposts, symbol text, crash logs, and app log folders.", - Downside: "Existing diagnostic and crash history is deleted.", - Recovery: "Old history stays deleted; future runs create new logs.", - Risk: "Lower risk", - DefaultSelected: true, - CanClean: true, - }, - { - ID: "temporary", - Name: "Temporary Files", - Description: "Files in simulator and app temporary directories.", - Downside: "Apps that misuse temporary storage may lose in-progress work.", - Recovery: "Old contents stay deleted; apps create new temporary files as needed.", - Risk: "Lower risk", - DefaultSelected: true, - CanClean: true, - }, - { - ID: "linguistic-data", - Name: "Downloaded Language Data", - Description: "On-demand language models used by Siri, Search, and text analysis.", - Downside: "Language-aware features may be limited until iOS downloads the package again.", - Recovery: "iOS downloads the language package again when a feature needs it.", - Risk: "Restored on demand", - DefaultSelected: false, - CanClean: true, - }, - { - ID: "required-siri-assets", - Name: "Required Siri Assets", - Description: "Siri understanding, speech, voice, and accessibility downloads restored by iOS.", - Downside: "Manual deletion is unsupported, and iOS promptly downloads required assets again.", - Recovery: "Required assets return automatically after boot.", - Risk: "System managed", - DefaultSelected: false, - CanClean: false, - }, -} - -type DiskCleanupCategoryMeasurement struct { - DiskCleanupCategory - Bytes int64 `json:"bytes"` - Targets int `json:"targets"` -} - -type DiskCleanupPlan struct { - UDID string `json:"udid"` - TotalBytes int64 `json:"totalBytes"` - CleanableBytes int64 `json:"cleanableBytes"` - Categories []DiskCleanupCategoryMeasurement `json:"categories"` - Storage []DiskStorageMeasurement `json:"storage"` -} - -type DiskCleanupResult struct { - UDID string `json:"udid"` - CategoryIDs []string `json:"categoryIds"` - BeforeBytes int64 `json:"beforeBytes"` - AfterBytes int64 `json:"afterBytes"` - ReclaimedBytes int64 `json:"reclaimedBytes"` - WasBooted bool `json:"wasBooted"` - BootStateRestored bool `json:"bootStateRestored"` -} - -func diskCleanupCategoryByID(id string) (DiskCleanupCategory, bool) { - for _, category := range DiskCleanupCategories { - if category.ID == id { - return category, true - } - } - return DiskCleanupCategory{}, false -} - -// simulatorDataDirectory returns the device's on-disk data directory, taken -// straight from the dataPath simctl reports. It is validated as a real directory -// before the disk commands touch it -// every deletion is separately confined to it by clearDirectoryContents. -func simulatorDataDirectory(ctx context.Context, udid string) (Device, string, error) { - device, err := FindDevice(ctx, udid, "") - if err != nil { - return Device{}, "", err - } - dataDirectory := device.DataPath - if dataDirectory == "" { - return Device{}, "", fmt.Errorf("simctl reported no data path for %s", udid) - } - info, err := os.Lstat(dataDirectory) - if err != nil { - return Device{}, "", fmt.Errorf("locate simulator data: %w", err) - } - if !info.IsDir() || info.Mode()&os.ModeSymlink != 0 { - return Device{}, "", fmt.Errorf("simulator data path is not a real directory: %s", dataDirectory) - } - return device, dataDirectory, nil -} - -func PlanDiskCleanup(ctx context.Context, udid string) (DiskCleanupPlan, error) { - _, dataDirectory, err := simulatorDataDirectory(ctx, udid) - if err != nil { - return DiskCleanupPlan{}, err - } - return diskCleanupPlanAt(udid, dataDirectory) -} - -func diskCleanupPlanAt(udid, dataDirectory string) (DiskCleanupPlan, error) { - plan := DiskCleanupPlan{UDID: udid} - for _, category := range DiskCleanupCategories { - targets, err := diskCleanupTargets(dataDirectory, category.ID) - if err != nil { - return DiskCleanupPlan{}, fmt.Errorf("scan %s: %w", category.Name, err) - } - measurement := DiskCleanupCategoryMeasurement{ - DiskCleanupCategory: category, - Targets: len(targets), - } - for _, target := range targets { - bytes, err := allocatedSize(target) - if err != nil { - return DiskCleanupPlan{}, fmt.Errorf("measure %s: %w", target, err) - } - measurement.Bytes += bytes - } - plan.TotalBytes += measurement.Bytes - if category.CanClean { - plan.CleanableBytes += measurement.Bytes - } - plan.Categories = append(plan.Categories, measurement) - } - storage, err := diskStorageMeasurements(dataDirectory) - if err != nil { - return DiskCleanupPlan{}, err - } - plan.Storage = storage - return plan, nil -} - -func CleanDeviceDisk(ctx context.Context, udid string, categoryIDs []string, preserveBootState bool) (DiskCleanupResult, error) { - device, dataDirectory, err := simulatorDataDirectory(ctx, udid) - if err != nil { - return DiskCleanupResult{}, err - } - categoryIDs, err = ValidateDiskCleanupSelection(categoryIDs) - if err != nil { - return DiskCleanupResult{}, err - } - - wasBooted := device.State == "Booted" - if wasBooted { - if _, _, err := shutdownIfBooted(ctx, udid); err != nil { - return DiskCleanupResult{}, err - } - } - - result, cleanupErr := cleanDiskAt(udid, dataDirectory, categoryIDs) - result.WasBooted = wasBooted - if wasBooted && preserveBootState { - if bootErr := BootAndWait(ctx, device.Set, udid); bootErr != nil { - if cleanupErr != nil { - return result, fmt.Errorf("%v; additionally could not restore boot state: %w", cleanupErr, bootErr) - } - return result, fmt.Errorf("disk cleanup finished, but could not restore boot state: %w", bootErr) - } - result.BootStateRestored = true - } - return result, cleanupErr -} - -func cleanDiskAt(udid, dataDirectory string, categoryIDs []string) (DiskCleanupResult, error) { - categoryIDs, err := ValidateDiskCleanupSelection(categoryIDs) - if err != nil { - return DiskCleanupResult{}, err - } - beforePlan, err := diskCleanupPlanAt(udid, dataDirectory) - if err != nil { - return DiskCleanupResult{}, err - } - beforeBytes := selectedCleanupBytes(beforePlan, categoryIDs) - - for _, id := range categoryIDs { - targets, err := diskCleanupTargets(dataDirectory, id) - if err != nil { - return DiskCleanupResult{}, err - } - for _, target := range targets { - if err := clearDirectoryContents(dataDirectory, target); err != nil { - return DiskCleanupResult{}, fmt.Errorf("clean %s: %w", target, err) - } - } - } - - afterPlan, err := diskCleanupPlanAt(udid, dataDirectory) - if err != nil { - return DiskCleanupResult{}, err - } - afterBytes := selectedCleanupBytes(afterPlan, categoryIDs) - reclaimed := beforeBytes - afterBytes - if reclaimed < 0 { - reclaimed = 0 - } - return DiskCleanupResult{ - UDID: udid, - CategoryIDs: categoryIDs, - BeforeBytes: beforeBytes, - AfterBytes: afterBytes, - ReclaimedBytes: reclaimed, - }, nil -} - -func ValidateDiskCleanupSelection(ids []string) ([]string, error) { - seen := map[string]bool{} - validated := make([]string, 0, len(ids)) - for _, id := range ids { - id = strings.TrimSpace(id) - if id == "" || seen[id] { - continue - } - category, ok := diskCleanupCategoryByID(id) - if !ok { - return nil, fmt.Errorf("unknown disk cleanup category %q", id) - } - if !category.CanClean { - return nil, fmt.Errorf("disk cleanup category %q is measured only and cannot be cleaned", id) - } - seen[id] = true - validated = append(validated, id) - } - if len(validated) == 0 { - return nil, fmt.Errorf("select at least one cleanable disk category") - } - sort.Strings(validated) - return validated, nil -} - -func selectedCleanupBytes(plan DiskCleanupPlan, ids []string) int64 { - selected := map[string]bool{} - for _, id := range ids { - selected[id] = true - } - var total int64 - for _, category := range plan.Categories { - if selected[category.ID] { - total += category.Bytes - } - } - return total -} - -func diskCleanupTargets(dataDirectory, categoryID string) ([]string, error) { - var targets []string - var err error - switch categoryID { - case "caches": - targets, err = findNamedDirectories(dataDirectory, "Caches", nil) - case "temporary": - targets, err = findNamedDirectories(dataDirectory, "tmp", map[string]bool{"Caches": true}) - case "logs": - targets = []string{ - filepath.Join(dataDirectory, "Library", "Logs"), - filepath.Join(dataDirectory, "var", "log"), - filepath.Join(dataDirectory, "var", "db", "diagnostics"), - filepath.Join(dataDirectory, "var", "db", "uuidtext"), - } - var discovered []string - discovered, err = findNamedDirectories(dataDirectory, "Logs", map[string]bool{"Caches": true, "tmp": true}) - targets = append(targets, discovered...) - case "linguistic-data": - targets, err = linguisticDataTargets(dataDirectory) - case "required-siri-assets": - targets, err = requiredSiriAssetTargets(dataDirectory) - default: - return nil, fmt.Errorf("unknown disk cleanup category %q", categoryID) - } - if err != nil { - return nil, err - } - return compactExistingTargets(dataDirectory, targets) -} - -func findNamedDirectories(root, name string, excludedAncestors map[string]bool) ([]string, error) { - var targets []string - bundleDirectory := filepath.Join(root, "Containers", "Bundle") - err := filepath.WalkDir(root, func(current string, entry os.DirEntry, walkErr error) error { - if walkErr != nil { - return walkErr - } - if !entry.IsDir() || current == root { - return nil - } - // Packaged resources are durable even when named Caches, Logs, or tmp. - if current == bundleDirectory { - return filepath.SkipDir - } - if isProtectedCleanupSubtree(entry.Name()) { - return filepath.SkipDir - } - if excludedAncestors[entry.Name()] { - return filepath.SkipDir - } - if entry.Name() == name { - targets = append(targets, current) - return filepath.SkipDir - } - return nil - }) - return targets, err -} - -// isProtectedCleanupSubtree keeps durable user content and system-managed -// assets out of name-based discovery. An app may legitimately create a folder -// named Caches, Logs, or tmp below Documents; its name alone does not make that -// content disposable. -func isProtectedCleanupSubtree(name string) bool { - switch name { - case "Documents", "Mobile Documents", "Media", "MobileAsset": - return true - default: - return false - } -} - -func linguisticDataTargets(dataDirectory string) ([]string, error) { - target := filepath.Join( - dataDirectory, - "private", - "var", - "MobileAsset", - "AssetsV2", - "com_apple_MobileAsset_LinguisticData", - ) - return compactExistingTargets(dataDirectory, []string{target}) -} - -func requiredSiriAssetTargets(dataDirectory string) ([]string, error) { - assetsRoot := filepath.Join(dataDirectory, "private", "var", "MobileAsset", "AssetsV2") - entries, err := os.ReadDir(assetsRoot) - if os.IsNotExist(err) { - return nil, nil - } - if err != nil { - return nil, err - } - prefixes := []string{ - "com_apple_MobileAsset_UAF_Siri_", - "com_apple_MobileAsset_TTS", - "com_apple_MobileAsset_VoiceServices_", - "com_apple_MobileAsset_VoiceTrigger", - } - var targets []string - for _, entry := range entries { - if !entry.IsDir() { - continue - } - for _, prefix := range prefixes { - if strings.HasPrefix(entry.Name(), prefix) { - targets = append(targets, filepath.Join(assetsRoot, entry.Name())) - break - } - } - } - return targets, nil -} - -func compactExistingTargets(root string, candidates []string) ([]string, error) { - unique := map[string]bool{} - var targets []string - for _, candidate := range candidates { - candidate = filepath.Clean(candidate) - if err := requireDescendant(root, candidate); err != nil { - return nil, err - } - info, err := os.Lstat(candidate) - if os.IsNotExist(err) { - continue - } - if err != nil { - return nil, err - } - if !info.IsDir() || info.Mode()&os.ModeSymlink != 0 || unique[candidate] { - continue - } - if err := requireResolvedDescendant(root, candidate); err != nil { - return nil, err - } - unique[candidate] = true - targets = append(targets, candidate) - } - sort.Slice(targets, func(i, j int) bool { - if len(targets[i]) != len(targets[j]) { - return len(targets[i]) < len(targets[j]) - } - return targets[i] < targets[j] - }) - compacted := targets[:0] - for _, target := range targets { - covered := false - for _, parent := range compacted { - relative, _ := filepath.Rel(parent, target) - if relative != "." && relative != ".." && !strings.HasPrefix(relative, ".."+string(filepath.Separator)) { - covered = true - break - } - } - if !covered { - compacted = append(compacted, target) - } - } - return compacted, nil -} - -func requireDescendant(root, target string) error { - root = filepath.Clean(root) - target = filepath.Clean(target) - relative, err := filepath.Rel(root, target) - if err != nil { - return fmt.Errorf("resolve cleanup path: %w", err) - } - if relative == "." || relative == ".." || strings.HasPrefix(relative, ".."+string(filepath.Separator)) { - return fmt.Errorf("refusing cleanup path outside simulator data: %s", target) - } - return nil -} - -// requireResolvedDescendant rejects targets whose existing path components -// traverse a symlink outside root. Lexical containment alone cannot catch an -// intermediate symlink such as data/var -> /some/other/location. -func requireResolvedDescendant(root, target string) error { - resolvedRoot, err := filepath.EvalSymlinks(root) - if err != nil { - return fmt.Errorf("resolve cleanup root: %w", err) - } - resolvedTarget, err := filepath.EvalSymlinks(target) - if err != nil { - return fmt.Errorf("resolve cleanup target: %w", err) - } - if err := requireDescendant(resolvedRoot, resolvedTarget); err != nil { - return fmt.Errorf("refusing symlinked cleanup path %s: %w", target, err) - } - return nil -} - -func allocatedSize(root string) (int64, error) { - var total int64 - err := filepath.WalkDir(root, func(current string, entry os.DirEntry, walkErr error) error { - if walkErr != nil { - return walkErr - } - info, err := entry.Info() - if err != nil { - return err - } - if stat, ok := info.Sys().(*syscall.Stat_t); ok { - total += stat.Blocks * 512 - } else { - total += info.Size() - } - return nil - }) - return total, err -} - -func clearDirectoryContents(dataDirectory, target string) error { - if err := requireDescendant(dataDirectory, target); err != nil { - return err - } - info, err := os.Lstat(target) - if os.IsNotExist(err) { - return nil - } - if err != nil { - return err - } - if !info.IsDir() || info.Mode()&os.ModeSymlink != 0 { - return fmt.Errorf("refusing to clear non-directory target %s", target) - } - if err := requireResolvedDescendant(dataDirectory, target); err != nil { - return err - } - entries, err := os.ReadDir(target) - if err != nil { - return err - } - for _, entry := range entries { - child := filepath.Join(target, entry.Name()) - if err := requireDescendant(dataDirectory, child); err != nil { - return err - } - if err := os.RemoveAll(child); err != nil { - return err - } - } - return nil -} diff --git a/disk_cleanup_test.go b/disk_cleanup_test.go deleted file mode 100644 index 4e1e3bd..0000000 --- a/disk_cleanup_test.go +++ /dev/null @@ -1,287 +0,0 @@ -package simslim - -import ( - "os" - "path/filepath" - "strings" - "testing" -) - -func TestDiskCleanupCategoriesAreUniqueAndSafeByDefault(t *testing.T) { - seen := map[string]bool{} - for _, category := range DiskCleanupCategories { - if category.ID == "" || seen[category.ID] { - t.Fatalf("invalid or duplicate disk cleanup category %q", category.ID) - } - seen[category.ID] = true - if category.DefaultSelected && !category.CanClean { - t.Fatalf("measured-only category %q must not be selected by default", category.ID) - } - } - if category, ok := diskCleanupCategoryByID("required-siri-assets"); !ok || category.CanClean { - t.Fatal("required Siri assets must remain measured-only") - } - if category, ok := diskCleanupCategoryByID("linguistic-data"); !ok || !category.CanClean || category.DefaultSelected { - t.Fatal("downloaded language data must be cleanable but opt-in") - } -} - -func TestDiskCleanupRecoveryModelsStayDistinct(t *testing.T) { - for _, id := range []string{"caches", "logs", "temporary"} { - category, ok := diskCleanupCategoryByID(id) - if !ok { - t.Fatalf("missing cleanup category %q", id) - } - if !strings.Contains(category.Recovery, "deleted") { - t.Errorf("cleanup category %q must say old contents stay deleted: %q", id, category.Recovery) - } - } - - assets, ok := diskCleanupCategoryByID("required-siri-assets") - if !ok { - t.Fatal("missing required Siri asset category") - } - if !strings.Contains(assets.Recovery, "return automatically") { - t.Errorf("system assets must describe automatic restoration: %q", assets.Recovery) - } - language, ok := diskCleanupCategoryByID("linguistic-data") - if !ok || !strings.Contains(language.Recovery, "downloads") { - t.Errorf("language data must describe on-demand recovery: %q", language.Recovery) - } - if language.Risk != "Restored on demand" { - t.Errorf("language data must label its restoration behavior: %q", language.Risk) - } -} - -func TestDiskCleanupPlanAndCleanStayInsideAllowlist(t *testing.T) { - dataDirectory := filepath.Join(t.TempDir(), "data") - cacheDirectory := filepath.Join(dataDirectory, "Library", "Caches") - tempDirectory := filepath.Join(dataDirectory, "Containers", "Data", "Application", "A", "tmp") - diagnosticsDirectory := filepath.Join(dataDirectory, "var", "db", "diagnostics") - uuidTextDirectory := filepath.Join(dataDirectory, "var", "db", "uuidtext") - requiredSiriDirectory := filepath.Join(dataDirectory, "private", "var", "MobileAsset", "AssetsV2", "com_apple_MobileAsset_UAF_Siri_Understanding") - linguisticDirectory := filepath.Join(dataDirectory, "private", "var", "MobileAsset", "AssetsV2", "com_apple_MobileAsset_LinguisticData") - unrelatedAssetDirectory := filepath.Join(dataDirectory, "private", "var", "MobileAsset", "AssetsV2", "com_apple_MobileAsset_PKITrustStore") - appDocumentDirectory := filepath.Join(dataDirectory, "Containers", "Data", "Application", "A", "Documents") - userNamedCache := filepath.Join(appDocumentDirectory, "Caches", "keep-cache.bin") - userNamedLogs := filepath.Join(appDocumentDirectory, "Logs", "keep-log.txt") - userNamedTemp := filepath.Join(appDocumentDirectory, "tmp", "keep-temp.bin") - assetNamedCache := filepath.Join(requiredSiriDirectory, "Caches", "keep-asset-cache.bin") - - writeTestFile(t, filepath.Join(cacheDirectory, "cache.bin"), 32*1024) - writeTestFile(t, filepath.Join(tempDirectory, "temp.bin"), 16*1024) - writeTestFile(t, filepath.Join(diagnosticsDirectory, "log.tracev3"), 24*1024) - writeTestFile(t, filepath.Join(uuidTextDirectory, "symbols"), 24*1024) - writeTestFile(t, filepath.Join(requiredSiriDirectory, "model.bin"), 64*1024) - writeTestFile(t, filepath.Join(linguisticDirectory, "language-model.bin"), 48*1024) - writeTestFile(t, filepath.Join(unrelatedAssetDirectory, "trust.bin"), 64*1024) - writeTestFile(t, filepath.Join(appDocumentDirectory, "user.db"), 64*1024) - writeTestFile(t, userNamedCache, 32*1024) - writeTestFile(t, userNamedLogs, 32*1024) - writeTestFile(t, userNamedTemp, 32*1024) - writeTestFile(t, assetNamedCache, 32*1024) - - plan, err := diskCleanupPlanAt("TEST-UDID", dataDirectory) - if err != nil { - t.Fatalf("diskCleanupPlanAt() error = %v", err) - } - measurements := map[string]DiskCleanupCategoryMeasurement{} - for _, measurement := range plan.Categories { - measurements[measurement.ID] = measurement - } - for _, id := range []string{"caches", "logs", "temporary", "linguistic-data", "required-siri-assets"} { - if measurements[id].Bytes == 0 { - t.Errorf("category %q should report test data", id) - } - } - if plan.CleanableBytes == 0 || plan.TotalBytes <= plan.CleanableBytes { - t.Errorf("unexpected plan totals: cleanable=%d total=%d", plan.CleanableBytes, plan.TotalBytes) - } - - result, err := cleanDiskAt("TEST-UDID", dataDirectory, []string{"temporary", "logs", "caches", "linguistic-data"}) - if err != nil { - t.Fatalf("cleanDiskAt() error = %v", err) - } - if result.ReclaimedBytes == 0 { - t.Error("cleanup should reclaim allocated bytes") - } - for _, removed := range []string{ - filepath.Join(cacheDirectory, "cache.bin"), - filepath.Join(tempDirectory, "temp.bin"), - filepath.Join(diagnosticsDirectory, "log.tracev3"), - filepath.Join(uuidTextDirectory, "symbols"), - filepath.Join(linguisticDirectory, "language-model.bin"), - } { - if _, err := os.Lstat(removed); !os.IsNotExist(err) { - t.Errorf("cleanup left %s", removed) - } - } - for _, preservedDirectory := range []string{ - cacheDirectory, - tempDirectory, - diagnosticsDirectory, - uuidTextDirectory, - linguisticDirectory, - } { - if info, err := os.Lstat(preservedDirectory); err != nil || !info.IsDir() { - t.Errorf("cleanup must preserve directory %s", preservedDirectory) - } - } - for _, preserved := range []string{ - filepath.Join(requiredSiriDirectory, "model.bin"), - filepath.Join(unrelatedAssetDirectory, "trust.bin"), - filepath.Join(appDocumentDirectory, "user.db"), - userNamedCache, - userNamedLogs, - userNamedTemp, - assetNamedCache, - } { - if _, err := os.Lstat(preserved); err != nil { - t.Errorf("cleanup touched non-cleanable data %s: %v", preserved, err) - } - } -} - -func TestDiskCleanupPreservesInstalledBundles(t *testing.T) { - for _, test := range []struct { - categoryID string - name string - }{ - {"caches", "Caches"}, - {"logs", "Logs"}, - {"temporary", "tmp"}, - } { - t.Run(test.categoryID, func(t *testing.T) { - dataDirectory := filepath.Join(t.TempDir(), "data") - bundleDirectory := filepath.Join(dataDirectory, "Containers", "Bundle", "Application") - appDirectory := filepath.Join(bundleDirectory, "APP", "Example.app") - var resources []string - for _, directory := range []string{ - appDirectory, - filepath.Join(appDirectory, "PlugIns", "Example.appex"), - filepath.Join(appDirectory, "Frameworks", "Example.framework"), - } { - resource := filepath.Join(directory, test.name, "keep.bin") - writeTestFile(t, resource, 4096) - resources = append(resources, resource) - } - cleanupDirectory := filepath.Join(dataDirectory, "Containers", "Data", "Application", "DATA", "Library", test.name) - if test.categoryID == "temporary" { - cleanupDirectory = filepath.Join(dataDirectory, "Containers", "Data", "Application", "DATA", "tmp") - } - cleanupFile := filepath.Join(cleanupDirectory, "remove.bin") - writeTestFile(t, cleanupFile, 8192) - cleanupBytes, err := allocatedSize(cleanupDirectory) - if err != nil { - t.Fatal(err) - } - bundleBytes, err := allocatedSize(bundleDirectory) - if err != nil { - t.Fatal(err) - } - - plan, err := diskCleanupPlanAt("TEST-UDID", dataDirectory) - if err != nil { - t.Fatal(err) - } - if plan.CleanableBytes != cleanupBytes { - t.Errorf("cleanable bytes = %d, want only disposable data: %d", plan.CleanableBytes, cleanupBytes) - } - for _, category := range plan.Categories { - if category.ID == test.categoryID && category.Targets != 1 { - t.Errorf("cleanup targets = %d, want only the app data directory", category.Targets) - } - } - for _, storage := range plan.Storage { - if storage.ID == "installed-apps" && storage.Bytes != bundleBytes { - t.Errorf("installed app bytes = %d, want %d", storage.Bytes, bundleBytes) - } - } - - if _, err := cleanDiskAt("TEST-UDID", dataDirectory, []string{test.categoryID}); err != nil { - t.Fatal(err) - } - for _, resource := range resources { - if _, err := os.Stat(resource); err != nil { - t.Errorf("cleanup touched installed bundle resource %s: %v", resource, err) - } - } - if _, err := os.Stat(cleanupFile); !os.IsNotExist(err) { - t.Errorf("disposable file was not removed: %v", err) - } - if info, err := os.Stat(cleanupDirectory); err != nil || !info.IsDir() { - t.Errorf("cleanup must preserve the disposable directory: %v", err) - } - }) - } -} - -func TestDiskCleanupRejectsIntermediateSymlink(t *testing.T) { - root := t.TempDir() - dataDirectory := filepath.Join(root, "data") - outsideLogDirectory := filepath.Join(root, "outside", "log") - outsideFile := filepath.Join(outsideLogDirectory, "keep.log") - writeTestFile(t, outsideFile, 4096) - if err := os.MkdirAll(dataDirectory, 0o755); err != nil { - t.Fatal(err) - } - if err := os.Symlink(filepath.Dir(outsideLogDirectory), filepath.Join(dataDirectory, "var")); err != nil { - t.Fatal(err) - } - - if _, err := cleanDiskAt("TEST-UDID", dataDirectory, []string{"logs"}); err == nil { - t.Fatal("cleanup should reject a target reached through an intermediate symlink") - } - if _, err := os.Lstat(outsideFile); err != nil { - t.Fatalf("cleanup touched data outside the simulator root: %v", err) - } -} - -func TestDiskCleanupDoesNotFollowSymlinks(t *testing.T) { - root := t.TempDir() - dataDirectory := filepath.Join(root, "data") - cacheDirectory := filepath.Join(dataDirectory, "Library", "Caches") - outsideDirectory := filepath.Join(root, "outside") - outsideFile := filepath.Join(outsideDirectory, "keep.txt") - writeTestFile(t, outsideFile, 4096) - if err := os.MkdirAll(cacheDirectory, 0o755); err != nil { - t.Fatal(err) - } - if err := os.Symlink(outsideDirectory, filepath.Join(cacheDirectory, "outside-link")); err != nil { - t.Fatal(err) - } - - if _, err := cleanDiskAt("TEST-UDID", dataDirectory, []string{"caches"}); err != nil { - t.Fatalf("cleanDiskAt() error = %v", err) - } - if _, err := os.Lstat(outsideFile); err != nil { - t.Fatalf("cleanup followed a symlink outside simulator data: %v", err) - } -} - -func TestDiskCleanupRejectsUnsafeTargetsAndMeasuredOnlyCategory(t *testing.T) { - root := t.TempDir() - dataDirectory := filepath.Join(root, "data") - if err := os.MkdirAll(dataDirectory, 0o755); err != nil { - t.Fatal(err) - } - if err := requireDescendant(dataDirectory, dataDirectory); err == nil { - t.Error("requireDescendant should reject the data root itself") - } - if err := requireDescendant(dataDirectory, root); err == nil { - t.Error("requireDescendant should reject a parent directory") - } - if _, err := ValidateDiskCleanupSelection([]string{"required-siri-assets"}); err == nil { - t.Error("measured-only MobileAsset cleanup must be rejected") - } -} - -func writeTestFile(t *testing.T, target string, size int) { - t.Helper() - if err := os.MkdirAll(filepath.Dir(target), 0o755); err != nil { - t.Fatal(err) - } - if err := os.WriteFile(target, make([]byte, size), 0o644); err != nil { - t.Fatal(err) - } -} diff --git a/disk_inventory.go b/disk_inventory.go deleted file mode 100644 index 3c3c34f..0000000 --- a/disk_inventory.go +++ /dev/null @@ -1,171 +0,0 @@ -package simslim - -import ( - "fmt" - "os" - "path/filepath" - "syscall" -) - -// DiskStorageMeasurement is a read-only breakdown of durable per-simulator -// storage. These rows are deliberately separate from cleanup categories so -// documents, app bundles, and user data can never become selected for deletion. -type DiskStorageMeasurement struct { - ID string `json:"id"` - Name string `json:"name"` - Description string `json:"description"` - Bytes int64 `json:"bytes"` -} - -var diskStorageCategories = []DiskStorageMeasurement{ - { - ID: "installed-apps", - Name: "Installed Apps", - Description: "Developer-installed app and test-runner bundles. Built-in apps live in the shared runtime.", - }, - { - ID: "documents", - Name: "Documents", - Description: "Files in app and app-group Documents directories.", - }, - { - ID: "app-data", - Name: "App Data", - Description: "Preferences, databases, and support files outside Documents and cleanup categories.", - }, - { - ID: "user-media", - Name: "User Media", - Description: "Photos, videos, downloads, and other files in the simulator media library.", - }, -} - -func diskStorageMeasurements(dataDirectory string) ([]DiskStorageMeasurement, error) { - measurements := make([]DiskStorageMeasurement, 0, len(diskStorageCategories)) - for _, category := range diskStorageCategories { - measurement := category - var err error - switch category.ID { - case "installed-apps": - measurement.Bytes, err = allocatedSizeOfExistingDirectories( - dataDirectory, - []string{filepath.Join(dataDirectory, "Containers", "Bundle", "Application")}, - ) - case "documents": - var targets []string - targets, err = appDocumentTargets(dataDirectory) - if err == nil { - measurement.Bytes, err = allocatedSizeOfExistingDirectories(dataDirectory, targets) - } - case "app-data": - measurement.Bytes, err = appDataSize(dataDirectory) - case "user-media": - measurement.Bytes, err = allocatedSizeOfExistingDirectories( - dataDirectory, - []string{filepath.Join(dataDirectory, "Media")}, - ) - default: - err = fmt.Errorf("unknown disk storage category %q", category.ID) - } - if err != nil { - return nil, fmt.Errorf("measure %s: %w", category.Name, err) - } - measurements = append(measurements, measurement) - } - return measurements, nil -} - -func appDocumentTargets(dataDirectory string) ([]string, error) { - var candidates []string - for _, root := range []string{ - filepath.Join(dataDirectory, "Containers", "Data", "Application"), - filepath.Join(dataDirectory, "Containers", "Shared", "AppGroup"), - } { - entries, err := os.ReadDir(root) - if os.IsNotExist(err) { - continue - } - if err != nil { - return nil, err - } - for _, entry := range entries { - if entry.IsDir() { - candidates = append(candidates, filepath.Join(root, entry.Name(), "Documents")) - } - } - } - return compactExistingTargets(dataDirectory, candidates) -} - -func appDataSize(dataDirectory string) (int64, error) { - excluded := map[string]bool{ - "Caches": true, - "Documents": true, - "Logs": true, - "tmp": true, - } - var total int64 - for _, root := range []string{ - filepath.Join(dataDirectory, "Containers", "Data", "Application"), - filepath.Join(dataDirectory, "Containers", "Shared", "AppGroup"), - } { - info, err := os.Lstat(root) - if os.IsNotExist(err) { - continue - } - if err != nil { - return 0, err - } - if !info.IsDir() || info.Mode()&os.ModeSymlink != 0 { - continue - } - if err := requireResolvedDescendant(dataDirectory, root); err != nil { - return 0, err - } - bytes, err := allocatedSizeExcludingNames(root, excluded) - if err != nil { - return 0, err - } - total += bytes - } - return total, nil -} - -func allocatedSizeOfExistingDirectories(root string, candidates []string) (int64, error) { - targets, err := compactExistingTargets(root, candidates) - if err != nil { - return 0, err - } - var total int64 - for _, target := range targets { - bytes, err := allocatedSize(target) - if err != nil { - return 0, err - } - total += bytes - } - return total, nil -} - -func allocatedSizeExcludingNames(root string, excluded map[string]bool) (int64, error) { - var total int64 - err := filepath.WalkDir(root, func(current string, entry os.DirEntry, walkErr error) error { - if walkErr != nil { - return walkErr - } - if current != root && entry.IsDir() && excluded[entry.Name()] { - return filepath.SkipDir - } - info, err := entry.Info() - if err != nil { - return err - } - if stat, ok := info.Sys().(*syscall.Stat_t); ok { - total += stat.Blocks * 512 - } else { - total += info.Size() - } - return nil - }) - return total, err -} diff --git a/disk_inventory_test.go b/disk_inventory_test.go deleted file mode 100644 index 3484d35..0000000 --- a/disk_inventory_test.go +++ /dev/null @@ -1,126 +0,0 @@ -package simslim - -import ( - "path/filepath" - "testing" -) - -func TestDiskStorageMeasurementsSeparateDurableDataFromCleanup(t *testing.T) { - dataDirectory := filepath.Join(t.TempDir(), "data") - installedApp := filepath.Join( - dataDirectory, - "Containers", - "Bundle", - "Application", - "APP-CONTAINER", - "Example.app", - "Example", - ) - documents := filepath.Join( - dataDirectory, - "Containers", - "Data", - "Application", - "DATA-CONTAINER", - "Documents", - ) - appSupport := filepath.Join( - dataDirectory, - "Containers", - "Data", - "Application", - "DATA-CONTAINER", - "Library", - "Application Support", - ) - cacheDirectory := filepath.Join( - dataDirectory, - "Containers", - "Data", - "Application", - "DATA-CONTAINER", - "Library", - "Caches", - ) - logDirectory := filepath.Join( - dataDirectory, - "Containers", - "Data", - "Application", - "DATA-CONTAINER", - "Library", - "Logs", - ) - tempDirectory := filepath.Join( - dataDirectory, - "Containers", - "Data", - "Application", - "DATA-CONTAINER", - "tmp", - ) - mediaDirectory := filepath.Join(dataDirectory, "Media", "DCIM", "100APPLE") - - writeTestFile(t, installedApp, 32*1024) - writeTestFile(t, filepath.Join(documents, "project.data"), 24*1024) - writeTestFile(t, filepath.Join(appSupport, "database.sqlite"), 20*1024) - writeTestFile(t, filepath.Join(cacheDirectory, "response.cache"), 64*1024) - writeTestFile(t, filepath.Join(logDirectory, "app.log"), 64*1024) - writeTestFile(t, filepath.Join(tempDirectory, "work.tmp"), 64*1024) - writeTestFile(t, filepath.Join(mediaDirectory, "photo.heic"), 28*1024) - - measurements, err := diskStorageMeasurements(dataDirectory) - if err != nil { - t.Fatalf("diskStorageMeasurements() error = %v", err) - } - byID := map[string]DiskStorageMeasurement{} - for _, measurement := range measurements { - byID[measurement.ID] = measurement - } - for _, id := range []string{"installed-apps", "documents", "app-data", "user-media"} { - if byID[id].Bytes == 0 { - t.Errorf("storage category %q should report test data", id) - } - } - - appDataBefore := byID["app-data"].Bytes - writeTestFile(t, filepath.Join(cacheDirectory, "larger.cache"), 512*1024) - measurements, err = diskStorageMeasurements(dataDirectory) - if err != nil { - t.Fatalf("diskStorageMeasurements() after cache growth error = %v", err) - } - for _, measurement := range measurements { - if measurement.ID == "app-data" && measurement.Bytes != appDataBefore { - t.Errorf( - "app-data must exclude cleanable caches: before=%d after=%d", - appDataBefore, - measurement.Bytes, - ) - } - } -} - -func TestDiskCleanupPlanIncludesReadOnlyStorageBreakdown(t *testing.T) { - dataDirectory := filepath.Join(t.TempDir(), "data") - writeTestFile( - t, - filepath.Join(dataDirectory, "Containers", "Bundle", "Application", "APP", "Example.app", "Example"), - 4096, - ) - writeTestFile( - t, - filepath.Join(dataDirectory, "Containers", "Data", "Application", "DATA", "Documents", "keep.txt"), - 4096, - ) - - plan, err := diskCleanupPlanAt("TEST-UDID", dataDirectory) - if err != nil { - t.Fatalf("diskCleanupPlanAt() error = %v", err) - } - if len(plan.Storage) != len(diskStorageCategories) { - t.Fatalf("storage rows = %d, want %d", len(plan.Storage), len(diskStorageCategories)) - } - if plan.CleanableBytes != 0 { - t.Fatalf("durable storage must never count as cleanable: %d", plan.CleanableBytes) - } -} diff --git a/disk_test.go b/disk_test.go deleted file mode 100644 index 5fb3246..0000000 --- a/disk_test.go +++ /dev/null @@ -1,19 +0,0 @@ -package simslim - -import "testing" - -func TestParseDUDiskUsage(t *testing.T) { - got, err := parseDUDiskUsage([]byte("4747728\t/simulator/path\n")) - if err != nil { - t.Fatalf("parseDUDiskUsage() error = %v", err) - } - if got != 4_861_673_472 { - t.Errorf("parseDUDiskUsage() = %d, want 4861673472", got) - } - - for _, invalid := range []string{"", "nope /simulator/path", "-1 /simulator/path"} { - if _, err := parseDUDiskUsage([]byte(invalid)); err == nil { - t.Errorf("parseDUDiskUsage(%q) unexpectedly succeeded", invalid) - } - } -} diff --git a/docs/parity-check.md b/docs/parity-check.md new file mode 100644 index 0000000..9e1330b --- /dev/null +++ b/docs/parity-check.md @@ -0,0 +1,127 @@ +# Go-vs-Swift parity check + +The Swift port reached parity and the Go tree was removed from this repository (see +[remove-go.md](remove-go.md)); this script remains as a regression check against the last Go +build, tagged `go-reference-final`. + +`scripts/parity.sh` runs the same commands through that Go build and the current Swift CLI and diffs the +normalized stdout, stderr and exit code, run by hand on a Mac with Xcode, a simulator runtime, python3 and +Go. Docker or Linux cannot run it: simslim needs macOS, `xcrun simctl` and real simulators. The Go side is +built from a sibling worktree of the tag (`../simslim-go-reference`, created once and reused), not from +this repository's working tree. + +```sh +git pull +scripts/parity.sh # read-only: no simulator is changed +scripts/parity.sh --mutating # + on/off/enable/disable/clone/... on a scratch simulator +scripts/parity.sh --mutating --watch # + watch --json events (slow, and slims every shut-down simulator) +``` + +Results go to `build/parity//`: `report.txt` holds every diff, and `go/` and `swift/` hold the +raw and normalized output of each command. Exit status is 1 if anything differs. + +## Prerequisite check: Go toolchain + +The only thing in this repository that still wants a Go toolchain is `scripts/parity.sh`. Determine +availability without installing anything: + +```sh +command -v go >/dev/null 2>&1 && echo "go: available" || echo "go: unavailable" +``` + +Never install Go (via Homebrew, `asdf`, or otherwise) to satisfy this check — its absence is a valid +environment, not a failure to fix. + +### Go available + +Run the regular gate plus a parity pass: + +```sh +make app-check # gui swift-format lint, build-app.sh syntax, Info.plist lint +make swift-lint # swift-format --strict over swift/Sources and swift/Tests +make swift-test # swift test +make verify-deps # system modules only, no network, no third-party libs +scripts/parity.sh # Go-vs-Swift parity, read-only; add --mutating for a scratch-simulator run +``` + +### Go unavailable + +`scripts/parity.sh` fails outright (exits 2 with "go not found (or set GO_BIN)"); everything else is +Go-free, so just skip that one script: + +```sh +make app-check +make swift-lint +make swift-test +make verify-deps +``` + +## What it covers + +- **Static:** `help`, `version`, `profiles` (every category), `doctor --list`, `disk-categories`, `list`, + `top --json`, and usage errors, including `on all`, `erase all` and `delete all`, which must never reach + simctl. +- **Per simulator (read-only):** `status`, `verify`, `doctor`, `measure`, `size`, `disk-plan`. +- **`--mutating`:** creates `simslim-parity-`, then for each CLI in turn resets it and runs `on`, `off`, + `on --except`, `on --keep`, `on --profile`, `on --no-reboot`, `enable`, `disable`, `doctor`, `shutdown`, + `rename`, `clone`, `repair-clone`, `erase`. `on` and `off` are compared as text (they take no `--json`). + After the slimming steps, after `shutdown`, and after `clone`/`erase` it also saves the contents of the + host-side `disabled.plist`, so persisted overrides are compared, not only the printed text. The + scratch simulator and its clone are deleted on exit unless you pass `--keep-device`. +- **`--watch`:** compares the sequence of `watch --json` event names for a simulator created and booted while + `watch` runs. + +## Normalization + +UDIDs, the home directory, binary paths, durations and the version string are masked. With "shape" mode +(`measure`, `top`) all numbers are masked too, since live memory differs between two runs. JSON is +re-serialized with sorted keys, and `null` equals `[]`. + +## Differences already known (from the code review) + +Expected, and harmless to the macOS app; they appear in the report as diffs unless noted: + +- `top --json` with no booted simulators: Go `"sims": null`, Swift `[]` (masked by the normalizer). +- `disk-clean`, `erase`, `delete` on a Booting or Shutting Down simulator: Swift refuses, Go proceeds. +- `clone`: Swift fails if the device list call fails, and its `lsof` containment is stricter. +- `disk-plan` fails in Swift when any path component of a target is a symlink; Go accepts a link that + stays inside the data directory. +- Profile file parsing: Swift rejects trailing text and accepts trailing commas and a BOM; duplicate keys + keep the first value in Swift and the last in Go. +- Non-JSON error text for file and I/O errors differs (Foundation vs Go wording). +- `simslim --json list` is accepted by Swift only; `watch extra-arg` is an error in Swift only. +- Ctrl-C during `on`, `off` and `clone` does not run Go's cleanup in Swift. +- `mutating/*.store` can transiently see a truncated, missing, or parseable-but-incomplete host-side + `disabled.plist`, because CoreSimulator's `launchd_sim` rewrites it asynchronously (see "Open question" + below). `snapstore()` trusts a read only after two identical ones in a row (up to ~4.5s), treats a file + absent for ~1.5s as really absent, and otherwise writes "store did not settle" to the step's stderr so the + comparison fails visibly. +- `watch/events`: Go's run goes first and slims every shut-down simulator it finds on startup, including + any pre-existing ones, not just the scratch devices this script creates; Swift's run then sees those + already slim and correctly emits no `slimmed_before_boot` for them, since `preslimDevice` only reports a + non-zero delta. The two runs can disagree on how many `slimmed_before_boot` events there are purely from + this ordering, with no behavior difference between the tools. Confirmed by reading the host-side + `disabled.plist` directly: the label count matched the `services` field Go reported. + +Anything else in `report.txt` is a real difference to investigate. When one is intentional, add it to this +list; when it is a bug, fix the Swift side and re-run. + +## Open question: `disabled.plist` lags live changes + +Observed on the maintainer's Mac; not yet explained. The host-side +`/private/var/tmp/com.apple.CoreSimulator.SimDevice./disabled.plist` is CoreSimulator's own +undocumented bookkeeping. Both CLIs check the authoritative in-guest `launchctl print-disabled` state before +reporting success, and that matched between Go and Swift in every trial. + +1. Right after `on` returns, the file can be mid-rewrite (truncated at a block boundary, or parseable but + missing entries) and settles within seconds. This showed up more often with the Swift CLI than with Go, + possibly only because Go's commands take slightly longer to return. Both tools write their own part of + the file atomically (temp file and `rename(2)`). +2. After a live `enable`, `disable` or `on --no-reboot`, which never write the store directly, the file was + seen to stay stale for the Swift CLI well past any reasonable retry window, while an in-guest check showed + both tools had disabled the same labels. This is why the script snapshots the store after `shutdown` + instead of right after `on --no-reboot`. If the file still differs there, the Swift live path does not + persist what Go's does, which is worth investigating. + +Also open: whether anything else that reads this file right after a live call (the macOS app, `watch`'s +pre-boot seeding) must tolerate the same staleness. diff --git a/docs/remove-go.md b/docs/remove-go.md new file mode 100644 index 0000000..a929501 --- /dev/null +++ b/docs/remove-go.md @@ -0,0 +1,93 @@ +# Removing the Go stack + +**Status: done.** The Go tree was removed, tagged `go-reference-final` first. `scripts/parity.sh` was kept +(per the choice below) and now builds its Go binary from a sibling worktree of that tag instead of +`./cmd/simslim`; `swift/Tools/gen_catalog.py` was deleted, since it had nothing left to read, and the +`Generated/` files it produced are now ordinary hand-maintained source. This page is kept as the record of +how, and as a reference if the Go tree ever needs resurrecting. + +The macOS app and the release already used the Swift CLI alone (`make app` needed no Go; `release.yml` +shipped only the Swift tarball) before Go was removed. The Go tree had been kept for two jobs only: + +1. **Parity reference:** `scripts/parity.sh` builds the Go CLI and diffs it against the Swift one. +2. **Catalog source:** `swift/Tools/gen_catalog.py` reads `profiles.go`, `service_descriptions.go`, + `features.go` and `profiles_test.go` as text to produce the files under `swift/**/Generated/`. + +Remove Go when you no longer need either. This page is the checklist. Do it as one commit (or two: +tag, then delete) on its own branch, after a final green parity run. + +## Before you delete anything + +1. Run the last parity check, read-only and mutating, on a Mac that has Go: + `scripts/parity.sh --mutating` (see [parity-check.md](parity-check.md)). Fix or accept every diff. +2. Tag the last commit that still has the Go tree, so the reference stays buildable: + ```sh + git tag go-reference-final # on the last commit that contains the Go sources + git push origin go-reference-final + ``` +3. Confirm the app and CLI work without Go: `VERSION=0.0.0 make app`, `make swift-test`, + `make verify-deps`. + +## What to delete + +| Path | Why it can go | +|---|---| +| `*.go` at the repo root (library and tests), `cmd/` | The Go library and CLI. | +| `go.mod`, `go.sum` | No Go module left. | +| `packaging/homebrew/` | Template for the Go build's Homebrew formula; `release.yml` no longer uses it. | +| `swift/Tools/gen_catalog.py` | The generator reads Go sources; without them it has nothing to read. | + +## What to edit + +- **`swift/**/Generated/*.swift` (`CatalogData.swift`, `ForbiddenLabels.swift`, and any other file + `gen_catalog.py` emitted):** these become ordinary hand-maintained source. Remove the "generated, do not + edit" banner and the mention of the Go files, keep the copyright line. They start with + `// swift-format-ignore-file`; keep it (the tables are long) or remove it and run `make format`. +- **`Makefile`:** delete the `cli`, `test`, `check`, `format` (the `gofmt` line), `swift-gen` and + `swift-gen-check` targets and their `.PHONY` entries. Keep `app`, `app-check`, `swift-lint`, + `swift-test`, `verify-deps`; make `format` run only `swift-format`. +- **`scripts/build-app.sh`:** remove the `SIMSLIM_CLI_IMPL` switch, the `go` branch of the CLI build, the + `GO_ARCH` mapping and the Go-availability check. Keep the Swift branch unconditional. +- **`.github/workflows/ci.yml`:** delete the `go-reference` job and `make swift-gen-check` from the + `swift` job. +- **`scripts/parity.sh`:** keep it only if you still want to compare against a Go build. Then it must build + `GO_BIN` from the `go-reference-final` tag (`git worktree add --detach ../simslim-go-reference go-reference-final`) instead of + `./cmd/simslim`; change the build step and its header comment accordingly. If you drop parity checks + entirely, delete it, `scripts/parity-normalize.py` and `parity-check.md`. +- **`scripts/verify-deps.sh`:** nothing to change; its only Go reference is a comment noting the help credit + line was copied from the Go CLI (reword it if you like). +- **`CLAUDE.md`:** rewrite the intro ("Go CLI plus SwiftUI app"), the Commands section, the Architecture and + Conventions sections (they describe the Go packages, `urfave/cli`, `bubbletea`) and the safety-invariant + references to `profiles_test.go`/`delta()` so they point at the Swift sources and tests. Remove the + "keep both implementations in step" rule and the `make swift-gen` rule. +- **`CONTRIBUTING.md`:** remove the Go gate (`make check`, `make format` Go half) and the paragraph about + keeping both implementations in step. +- **`README.md`:** remove the "Upstream Go version (MobAI)" install block and the Go library section, or + turn them into a link to the upstream repository. Keep the credit to MobAI/Interlap, the license line and the + copyright lines, and the Status paragraph (reword it to say parity was checked against the Go reference + tagged `go-reference-final`). +- **`docs/swift-port-plan.md`:** mark the Go removal done; add the tag name. +- **Other docs** (`docs/category-memory.md`, `docs/disk-cleanup.md`): search them for `.go` file names and + `go ` commands and point them at the Swift sources. + +## After the change + +```sh +git grep -n -i -E '\bgo (build|test|vet)|\.go\b|go\.mod|gen_catalog|SIMSLIM_CLI_IMPL|GO_BIN' +make app-check swift-lint swift-test verify-deps +VERSION=0.0.0 make app +``` + +The `git grep` should only match the places that deliberately mention the Go reference (README credit, the +parity docs, this page). Everything else is a leftover. Then run the app once (`open build/SimSlim.app`) and +confirm the CI `swift` job is green. + +## Things to keep in mind + +- **The catalog stops being checked against a source of truth.** Today a mistake in a daemon list fails + `swift-gen-check`. After removal the Swift catalog tests (`ProfilesTests`, `FeaturesTests`, the forbidden + labels test) are the only guard, so keep them. +- **Upstream changes no longer flow in for free.** To adopt a later upstream fix, diff against the + `go-reference-final` tag or the upstream repository and port it by hand. +- **Rollback:** the tag keeps the whole Go tree recoverable (`git checkout go-reference-final -- `). + The app also still accepts `SIMSLIM_CLI=` at runtime to run any other `simslim` binary. diff --git a/docs/swift-port-plan.md b/docs/swift-port-plan.md new file mode 100644 index 0000000..15e13aa --- /dev/null +++ b/docs/swift-port-plan.md @@ -0,0 +1,176 @@ +# simslim Swift port: plan + +Status: **Done.** M1 to M6: every Go command ported with the `--json` contract kept. M7: parity checked +against the Go build via `scripts/parity.sh` (read-only, `--mutating`, and `--watch`), no behavioral +differences found; see [parity-check.md](parity-check.md). M8: `make app` bundles the Swift CLI. The Go +tree has since been removed (tag `go-reference-final` keeps it recoverable); see +[remove-go.md](remove-go.md). +Branch: `swift-port` (no upstream). + +## 1. Goal and non-goals + +**Goal.** A `simslim` CLI built only with the Xcode toolchain already on the Mac, with no Go toolchain and no third-party code, whose dependencies can be verified by a short script anyone can run. It keeps the existing `--json` contract, so `gui/*.swift` keeps working unchanged. + +**Non-goals.** +- Changing behavior or adding features during the port. +- Linux or CI portability (the tool is macOS-only already). +- Replacing the SwiftUI app. Only its bundled CLI changes. + +## 2. Size of the job (from the Go source) + +| Area | Go files | Lines | +|---|---|---| +| CLI commands and dispatch | `cmd/simslim/main.go`, `app.go` | ~1350 | +| Live TUI (`top`) | `cmd/simslim/top.go` | ~650 | +| Profile wizard | `cmd/simslim/wizard.go` | ~360 | +| Clone / repair-clone | `clone.go` | ~880 | +| simctl wrapper | `simctl.go` | ~675 | +| Disk cleanup / inventory | `disk_cleanup.go`, `disk_inventory.go`, `disk.go` | ~740 | +| Allowlist, categories, descriptions | `profiles.go`, `service_descriptions.go`, `features.go` | ~810 | +| Slim engine | `slim.go`, `disabled_store.go`, `launchd_batch.go`, `verify.go` | ~710 | +| watch | `watch.go`, `watch_dirs_darwin.go` | ~520 | +| live enable/disable, profiles on disk | `live.go`, `profile_file.go`, `profile_save.go` | ~640 | +| measure / fleet / output | `measure.go`, `fleet.go`, `output.go` | ~420 | +| **Total non-test** | | **~12.7k** | +| Tests | 40 `_test.go` files | ~4.9k | + +Expect roughly 9 to 12k lines of Swift. This is an estimate, not a measurement. + +## 3. Dependency policy: controlled and independently verifiable + +### 3.1 The rule + +The only code the Swift tool may use is: + +1. The Swift standard library. +2. Apple system modules: `Foundation`, `Darwin`, `Dispatch` (CLI); additionally `AppKit` and `SwiftUI` (the existing GUI). +3. Test-only, toolchain-bundled: `XCTest` or `Testing`, plus `swift-format` from Xcode for lint. + +No Swift packages, no vendored source, no downloaded binaries, no plugins, no build scripts that fetch anything. Every item in this list ships inside Xcode, so approving Xcode approves it. + +### 3.2 Layout choices that keep this checkable + +- **SwiftPM with an empty dependency list.** `swift/Package.swift` declares `dependencies: []`. This gives `swift build` and `swift test` without any third-party code. The GUI keeps its current bare-`swiftc` build in `scripts/build-app.sh`. +- **Three targets:** `SimSlimKit` (library, all logic), `simslim` (executable, argument parsing and printing only), `SimSlimKitTests`. This mirrors the Go split where the library never writes to stdout. +- **One place for subprocesses.** All `Process` use lives in `Subprocess.swift`. Each executable is an absolute path from a closed enum: `/usr/bin/xcrun`, `/usr/bin/plutil`, `/usr/bin/du`, `/usr/bin/pgrep`, `/bin/ps`, `/usr/bin/top`, `/usr/sbin/lsof`, `/bin/stty`. No `PATH` lookup. This is stricter than the Go version, which resolves most of them through `PATH`. +- **One place for the filesystem roots it may mutate**, with the same guards as `requireDescendant` / `requireResolvedDescendant`. + +### 3.3 Verification gate: `scripts/verify-deps.sh` + +A single script, run by `make check` and runnable by the security team on a clean checkout. It must pass or the build fails. + +| # | Check | How | +|---|---|---| +| 1 | No packages | `swift/Package.swift` has `dependencies: []`; `Package.resolved` absent; no `Packages/`, `vendor/`, `.build/checkouts` | +| 2 | Imports are allowlisted | grep every `import` in `swift/` and `gui/`; any module outside the allowlist fails | +| 3 | No network APIs | grep for `URLSession`, `URLRequest`, `URL(string:` with a scheme, `NWConnection`, `CFNetwork`, `Network` import, sockets | +| 4 | Subprocess closure | every `Process()` is in `Subprocess.swift`; every executable path is in the enum | +| 5 | Linked libraries | `otool -L` on the release binary; every entry must be under `/usr/lib` or `/System/Library`; compared to a committed `expected-libs.txt` | +| 6 | Symbols | `nm` / `strings` on the release binary must show no network symbols | +| 7 | No fetching in the build | grep `Package.swift`, `Makefile`, and scripts for `curl`, `wget`, `git clone`, `http(s)://` | +| 8 | Test hooks absent from release | the release binary does not contain the test-override env var names (see 4.2) | +| 9 | Runtime network check (optional) | run `list`, `status`, `--json` commands under `sandbox-exec` with `(deny network*)` and confirm they still work | + +`docs/DEPENDENCIES.md` records the result in plain words: the allowlist, the expected `otool -L` output, and "third-party packages: none". It is generated, so it cannot drift from the code. + +### 3.4 Reproducibility and provenance + +- Build with `-file-prefix-map` so paths do not leak into the binary. Build twice and compare hashes. Treat byte-identical output as a goal and report if it isn't achieved (Swift determinism is not guaranteed). +- `scripts/sbom.sh` prints the toolchain version, the allowlisted modules, and the linked system libraries. It will say "third-party: none". +- Ad-hoc codesign as today. Notarization is a separate decision and needs an Apple developer identity. + +## 4. Test strategy + +### 4.1 Layer 1: pure unit tests (run anywhere, in `make check`) + +Port the Go tests that encode safety or contract: +- `profiles_test`: allowlist invariants, `forbiddenLabels`, every category has a positive memory estimate, descriptions cover every label. +- `features_test`, `profile_file_test`, `profile_save_test`. +- Delta logic scoped to the managed set (the "only managed labels are ever mutated" invariant). +- Parsing: `simctl list -j`, `print-disabled`, `launchctl list`, `disabled.plist`. +- Disk-cleanup path guards, including the symlink cases. +- `--confirm` refusal. + +### 4.2 Layer 2: component tests with a fake `xcrun` + +Mirrors `simctl_test.go`. `SimctlRunning` is a protocol, and unit tests inject a fake. For black-box CLI tests there is a debug-only override of the executable paths, compiled under `#if DEBUG`. The release binary must not contain it (gate check 8). + +### 4.3 Layer 3: contract tests against the GUI + +`gui/Models.swift` already decodes the CLI's JSON. A test compiles `Models.swift` into the test target and decodes the Swift CLI's `--json` output for every command. If a field is renamed or dropped, the build breaks, instead of the GUI breaking at runtime. A second check compares the key sets of each JSON output with the Go tool's, using fixtures recorded once from the Go binary on a machine that has Go. + +### 4.4 Layer 4: integration tests on real simulators (opt-in) + +Enabled only with `SIMSLIM_INTEGRATION=1`; never part of `make check`. + +Safety rules: +- Run in an **isolated device set** (`--set `), never the default set. +- Create a dedicated throwaway device with `simctl create`, record its UDID, and **refuse to touch any UDID that is not in that record**. +- Always clean up in teardown, including on failure. Delete only the recorded UDID. +- Abort before doing anything if the device cannot be created. + +Scenarios: list and status on a clean device; `on` then `verify`; reboot and confirm persistence; `off`; `on --no-reboot`; live `enable` and `disable` with `--save`; offline fast path; `doctor`; `measure`; `clone` and `repair-clone`; `disk-plan` (read-only) and `disk-clean --confirm` on the throwaway device only; `watch` seeing a new device. + +### 4.5 Side-by-side parity (needs Go, so the personal Mac) + +For the same throwaway device, run the Go and Swift tools and compare: `--json` output (modulo timing fields), and the resulting disabled-label set. Xcode 27.2 is newer than the Xcode 26.6 the upstream CI pins, so any difference is first checked against plain `simctl` before blaming the port. + +## 5. Milestones + +Each milestone ends with: gate script green, unit tests green, and a short written note of what was verified and what was not. + +- **M0 Scaffold.** `swift/` package, empty dependencies, `verify-deps.sh`, `DEPENDENCIES.md` generation, CI wiring, fake-xcrun harness. +- **M1 Core model.** Allowlist (`profiles.go`, `service_descriptions.go`, `features.go`) as data, delta logic, profile files. All invariant tests ported first. +- **M2 simctl and read-only commands.** `Subprocess`, `simctl` wrapper, `list`, `profiles`, `status`, `verify`, `doctor`, `measure`, `size`, `disk-categories`, `disk-plan`, with JSON contract tests. +- **M3 Slimming.** `on`, `off`, `on --no-reboot`, the `launchctl` pool (8 workers), `disabled.plist` offline fast path, `unloadInBatch`, launchd retry delays. +- **M4 Live and management.** `enable`, `disable`, `--save`, `boot`, `shutdown`, `rename`, `erase`, `delete`, `clone`, `repair-clone`, `disk-clean`. The destructive ones get the most review. +- **M5 watch.** kqueue directory watch, pre-slim of new devices, `watch --json` events. +- **M6 Interactive.** `top` live view (plain ANSI redraw, no TUI library) and the `profile` wizard (`stty` raw mode). +- **M7 Integration and parity.** Layer 4 and 4.5 runs, fix differences. +- **M8 Cutover.** `build-app.sh` bundles the Swift CLI, Go removed from the app build, README and `CLAUDE.md` updated. The Go tree stays until you decide to remove it. + +## 6. Risks + +- **Undocumented behavior.** `disabled.plist` location and format is a CoreSimulator internal. The Go tool already treats it as best effort and falls back to `launchctl`; the port keeps that fallback. +- **Xcode 27 differences.** `simctl` output or runtime layout may differ from what upstream tested. Surfaces in M2 and M7. +- **Concurrency.** Go's goroutines and contexts map to Swift concurrency. The pool, timeouts (`BootTimeout`, `SpawnTimeout`, `ShutdownTimeout`) and cancellation (`slimPass`) need careful porting, with tests. +- **`top` and wizard.** Reimplementing terminal UI without a library is the most visible behavior change. Scope can be cut here if needed. +- **Fork drift.** After the port, upstream Go fixes do not flow in automatically. +- **Licensing.** The port is a derivative of MIT code; keep `LICENSE` and the copyright notice. +- **Security-team acceptance.** Self-built code from this repo is a policy question for your team, not something this plan assumes. + +## 7. Decisions (resolved) + +1. **Scope: reduced first.** The priority is the RAM effect when running many simulators. The first release covers the CLI commands that produce it: `list`, `profiles`, `status`, `verify`, `doctor`, `measure`, `on` (including `--no-reboot` and `--profile`), `off`, `enable`/`disable` (with `--save`), `boot`, `shutdown`, and `watch`. See section 8 for what is deferred. +2. **Location:** `swift/` inside this repo. +3. **Go tree:** kept until cutover only, as the parity reference. At cutover, tag the last Go commit and remove the tree. Upstream stays reachable through a git remote. Reason: `go.mod` and `go.sum` would otherwise keep the 19 third-party modules in the tree and weaken the "no third-party code" claim. +4. **Dependency gate:** run by hand with `make verify-deps`. No CI wiring for now; revisit later. +5. **Independent review: yes**, scoped to the mutating core (slim engine, `live.go`, `disabled_store.go`, `profile_save.go`) and, later, to any deferred destructive code before it is ported. + +## 8. Deferred (follow-up tasks) + +These are not in the first release. The SwiftUI app depends on several of them, so the app keeps bundling the Go CLI until they are ported. No cutover of the app happens before then. + +| Item | Why deferred | Notes | +|---|---|---| +| `top` live view | Ported in M5b | Done: raw-mode terminal, alternate screen, 2 s refresh; one-shot and `--json` output as before. | +| `profile` wizard | Ported in M5d | Done: pure `WizardModel` plus a termios raw-mode reader; no `stty`. | +| `clone`, `repair-clone` | Ported in M5e, independently reviewed | Done. Every Go command now exists in the Swift CLI. | +| `rename`, `erase`, `delete` | Ported in M5a, independently reviewed | Done. | +| `size`, `disk-categories`, `disk-plan`, `disk-clean` | Ported in M5c, independently reviewed | Done. | +| App cutover to the Swift CLI | Requires all of the above | Then remove the Go tree. | + +## 9. Revised milestones for the first release + +- **M0** Scaffold: package, subprocess layer, dependency gate, `make verify-deps`. +- **M1** Core model: allowlist, categories, features, delta logic, profile files, with the invariant tests ported first. +- **M2** simctl and read-only commands: `list`, `profiles`, `status`, `verify`, `doctor`, `measure`. **Done** (167 tests; every command checked through a fake host; the app's real `gui/Models.swift` decodes the JSON; `measure` cross-checked against `pgrep`/`ps`/`top` on a real Mac). Also run against a live throwaway simulator in an isolated device set (Xcode 27.2, iOS 27.2). +- **M3a** Slimming: `on`, `off`, `on --no-reboot`, `boot`, `shutdown`, offline fast path, batch unload, 8-worker pool. **Done** (222 tests; 12 mutations in the slimming core, all caught; live run on a throwaway simulator: 246 to 83 processes, about 10.5 GB to 2.7 GB, slim persists across shutdown and boot, `off` restores stock). Awaiting the independent review of this core. +- **M3b** Live `enable`/`disable` and `--save` (`live.go`, `profile_save.go`): **Done** (14 mutations in the new code caught after two added tests; run live on a throwaway simulator). Independently reviewed: one real bug (`--save` replaced a symlinked profile named by a bare file name) and several test gaps, all fixed. +- **M5e** `clone`, `repair-clone`: **Done** (independent review, 35 tests, 32 of 41 mutants caught at first and the observable survivors fixed; live runs on throwaway simulators in an isolated set: clone of a booted and of a shut-down source, repair of a deliberately broken clone, an unrebasable link refused and the clone deleted; source boot state restored each time). Review fixes: a clone UDID that equals the source or any existing simulator is rejected before anything can be deleted (the Go code would have run `simctl delete` on it); the open-file audit also flags any path naming the source UDID, so a symlinked CoreSimulator directory cannot hide a leak; rewrite roots must look like `//data`; files vanishing mid-walk and ENOTDIR counterparts no longer fail a good clone. Other differences from Go, all deliberate: the new UDID is read from stdout only; stricter symlink containment shared with `disk-clean`; progress lines on stderr (quiet under `--json`). Known and shared with Go: Ctrl-C during `simctl clone` itself can leave an orphan clone, because no UDID exists yet to delete. Unobservable survivors: redundant source-UDID check, `st_dev` in the hard-link test (one filesystem), overlapping UDID-component and resolved-path checks. +- **M5d** `profile` wizard: **Done** (16 tests, mutation-checked, driven through a real pty). Differences from Go, all deliberate: the file is created exclusively (`O_EXCL|O_NOFOLLOW`) so it never replaces a file, even one created during the wizard; a kept daemon is dropped when *any* kept feature covers it and is listed once (Go dropped it only within the same feature); the header typo `simslim.Features` is fixed; name and description are read byte-by-byte so no typed-ahead key is lost. Not independently reviewed: it writes one new file and touches no simulator. +- **M5c** `size`, `disk-categories`, `disk-plan`, `disk-clean`: **Done** (reviewed independently; live run on throwaway simulators; 39 disk tests, every deletion-safety mutant caught except two unreachable defence-in-depth checks). The review found a hole the Go code shares: a symlink *inside* the data directory (for example `var -> Media`) could redirect a fixed cleanup path such as `var/log` into protected user data. The Swift port now requires the real path to equal the lexical path under the real root. The Go tree is not fixed. Other differences from Go, all deliberate: `disk-clean` refuses a Booting or Shutting Down simulator; directories are listed with `readdir` (Foundation hides `._*` files); a child that vanishes mid-clean is not an error. +- **M5b** `top`: **Done** (pure model with 28 tests, key parser, raw-mode runner; checked in a pseudo-terminal: drill-down, Esc, `q`, Ctrl-C, SIGINT and SIGTERM all restore the terminal; 19 mutations, 4 survivors then covered). `deviceDiskUsage` is shared with the future `size` command. +- **M5a** `rename`, `erase`, `delete`: **Done** (reviewed independently; no route for an alias or flag to reach the destructive simctl calls; live run on a throwaway simulator). One deliberate divergence from Go: erase and delete refuse a simulator that is Booting or Shutting Down, where Go runs them. Names print with Go's `%q` rules and trim with Go's space set. Remaining for the app cutover: `size`, `disk-categories`, `disk-plan`, `disk-clean`, `clone`. +- **M4** `watch`: **Done** (kqueue device-set watcher, pre-boot store seeding, per-device after-boot slim with cancellation, `--json` events; 40 tests, 19 mutations caught or hung). Not run live: `watch` always scans the user's default device set, so a live run would slim their real simulators; run it on a Mac where that is intended. Cancellation stops the next command, not one already running (Go kills it). +- **M5** Integration tests on a throwaway simulator, independent review of the mutating core, and parity run against the Go tool. diff --git a/features.go b/features.go deleted file mode 100644 index 5df33ec..0000000 --- a/features.go +++ /dev/null @@ -1,101 +0,0 @@ -package simslim - -import "fmt" - -// Feature is a user-facing capability backed by specific launchd daemons. -// Every label must also be managed by a Category (enforced in features_test.go), -// including required services that earlier versions could have turned off. -type Feature struct { - ID string `json:"id"` - Name string `json:"name"` - Labels []string `json:"labels"` -} - -// Features maps commonly required capabilities to the daemons they need running. -var Features = []Feature{ - {ID: "push", Name: "Push notifications", Labels: []string{"com.apple.apsd"}}, - // In-app purchase needs the store daemons plus AMS, which runs the - // payment sheet task, plus Wallet (passd) which hosts the sheet UI and - // Finance (financed) which passd requires — products load without them - // but purchases fail at sheet presentation. - {ID: "storekit", Name: "StoreKit / in-app purchase", Labels: []string{ - "com.apple.storekitd", - "com.apple.itunesstored", - "com.apple.amsaccountsd", - "com.apple.amsengagementd", - "com.apple.amsondevicestoraged", - "com.apple.passd", - "com.apple.financed", - }}, - {ID: "app-store", Name: "App Store", Labels: []string{"com.apple.appstored", "com.apple.itunesstored"}}, - {ID: "universal-links", Name: "Universal links / associated domains", Labels: []string{"com.apple.swcd"}}, - {ID: "spotlight", Name: "Spotlight & Settings search", Labels: []string{"com.apple.searchd", "com.apple.searchtoold"}}, - // Files and the document picker load Recents through a Spotlight query - // that searchd serves; without it the tab shows "Content Unavailable". - {ID: "files-recents", Name: "Files & document picker Recents", Labels: []string{"com.apple.searchd"}}, - {ID: "siri", Name: "Siri & speech", Labels: []string{"com.apple.assistantd", "com.apple.corespeechd"}}, - {ID: "icloud", Name: "iCloud sync", Labels: []string{"com.apple.cloudd"}}, - {ID: "keychain-sync", Name: "iCloud Keychain", Labels: []string{"com.apple.akd"}}, - {ID: "contacts", Name: "Contacts", Labels: []string{"com.apple.contactsd"}}, - {ID: "calendar", Name: "Calendar", Labels: []string{"com.apple.calaccessd"}}, - {ID: "reminders", Name: "Reminders", Labels: []string{"com.apple.remindd"}}, - {ID: "mail", Name: "Mail", Labels: []string{"com.apple.email.maild"}}, - {ID: "photos", Name: "Photos library & analysis", Labels: []string{"com.apple.assetsd", "com.apple.photoanalysisd"}}, - {ID: "health", Name: "HealthKit", Labels: []string{"com.apple.healthd"}}, - {ID: "homekit", Name: "HomeKit", Labels: []string{"com.apple.homed"}}, - {ID: "imessage", Name: "iMessage & FaceTime", Labels: []string{"com.apple.identityservicesd"}}, - // The stock Maps widget needs navd: without it the widget extension - // spins on its XPC connection and floods the unified log. - {ID: "widgets", Name: "Widgets & Live Activities", Labels: []string{"com.apple.chronod", "com.apple.liveactivitiesd", "com.apple.navd"}}, - {ID: "wallet", Name: "Wallet & passes", Labels: []string{"com.apple.passd"}}, - {ID: "maps", Name: "Maps background services", Labels: []string{"com.apple.Maps.mapssyncd"}}, - {ID: "weather", Name: "Weather", Labels: []string{"com.apple.weatherd"}}, - {ID: "news", Name: "News", Labels: []string{"com.apple.newsd"}}, - {ID: "game-center", Name: "Game Center", Labels: []string{"com.apple.gamed"}}, - {ID: "find-my", Name: "Find My", Labels: []string{"com.apple.findmy.findmylocated"}}, - {ID: "mdm", Name: "Declarative device management", Labels: []string{"com.apple.remotemanagementd", "com.apple.RemoteManagementAgent"}}, - {ID: "app-clips", Name: "App Clips", Labels: []string{"com.apple.ClipServices.clipserviced"}}, - {ID: "screen-time", Name: "Screen Time", Labels: []string{"com.apple.ScreenTimeAgent"}}, -} - -func featureByID(id string) (Feature, bool) { - for _, f := range Features { - if f.ID == id { - return f, true - } - } - return Feature{}, false -} - -// resolveFeatures maps requested IDs to their Features, erroring on the first -// unknown one so a typo in --requires fails loudly instead of passing silently. -func ResolveFeatures(ids []string) ([]Feature, error) { - out := make([]Feature, 0, len(ids)) - for _, id := range ids { - f, ok := featureByID(id) - if !ok { - return nil, fmt.Errorf("unknown feature %q (see `simslim doctor --list`)", id) - } - out = append(out, f) - } - return out, nil -} - -// diagnoseFeatures reports, for each feature, which of its daemons the device -// currently has disabled. A feature is OK only when none of them are. -func DiagnoseFeatures(features []Feature, disabled map[string]bool) DoctorOutput { - statuses := make([]FeatureStatus, 0, len(features)) - allOK := true - for _, f := range features { - var down []string - for _, l := range f.Labels { - if disabled[l] { - down = append(down, l) - } - } - ok := len(down) == 0 - allOK = allOK && ok - statuses = append(statuses, FeatureStatus{ID: f.ID, Name: f.Name, OK: ok, Disabled: down}) - } - return DoctorOutput{OK: allOK, Features: statuses} -} diff --git a/features_test.go b/features_test.go deleted file mode 100644 index f37a97f..0000000 --- a/features_test.go +++ /dev/null @@ -1,148 +0,0 @@ -package simslim - -import ( - "reflect" - "testing" -) - -func TestFeatureLabelsAreManaged(t *testing.T) { - managed := managedSet() - for _, f := range Features { - if len(f.Labels) == 0 { - t.Errorf("feature %q has no labels", f.ID) - } - for _, l := range f.Labels { - if !managed[l] { - t.Errorf("feature %q names unmanaged daemon %q", f.ID, l) - } - } - } -} - -func TestFeatureIDsAreUniqueAndNamed(t *testing.T) { - seen := map[string]bool{} - for _, f := range Features { - if f.ID == "" { - t.Error("a feature has an empty ID") - } - if f.Name == "" { - t.Errorf("feature %q has no name", f.ID) - } - if seen[f.ID] { - t.Errorf("duplicate feature ID %q", f.ID) - } - seen[f.ID] = true - } -} - -func TestResolveFeatures(t *testing.T) { - got, err := ResolveFeatures([]string{"push", "storekit"}) - if err != nil { - t.Fatalf("ResolveFeatures() error = %v", err) - } - if len(got) != 2 || got[0].ID != "push" || got[1].ID != "storekit" { - t.Errorf("resolveFeatures = %v, want [push storekit]", got) - } - if _, err := ResolveFeatures([]string{"push", "nope"}); err == nil { - t.Error("ResolveFeatures(unknown) error = nil, want error") - } -} - -func TestGameCenterDiagnosesLegacyDisabledGamed(t *testing.T) { - features, err := ResolveFeatures([]string{"game-center"}) - if err != nil { - t.Fatalf("ResolveFeatures(game-center) error = %v", err) - } - if !DiagnoseFeatures(features, map[string]bool{}).OK { - t.Error("game-center should be healthy with gamed enabled") - } - report := DiagnoseFeatures(features, map[string]bool{"com.apple.gamed": true}) - if report.OK || len(report.Features) != 1 || !reflect.DeepEqual(report.Features[0].Disabled, []string{"com.apple.gamed"}) { - t.Errorf("doctor must still report legacy disabled gamed: %+v", report) - } -} - -func TestWidgetsDiagnoseDisabledNavd(t *testing.T) { - features, err := ResolveFeatures([]string{"widgets"}) - if err != nil { - t.Fatalf("ResolveFeatures(widgets) error = %v", err) - } - if !DiagnoseFeatures(features, map[string]bool{}).OK { - t.Error("widgets should be healthy with navd enabled") - } - report := DiagnoseFeatures(features, map[string]bool{"com.apple.navd": true}) - if report.OK || len(report.Features) != 1 || !reflect.DeepEqual(report.Features[0].Disabled, []string{"com.apple.navd"}) { - t.Errorf("doctor must report widgets kept without navd: %+v", report) - } -} - -func TestFilesRecentsDiagnoseDisabledSearchd(t *testing.T) { - features, err := ResolveFeatures([]string{"files-recents"}) - if err != nil { - t.Fatalf("ResolveFeatures(files-recents) error = %v", err) - } - if !DiagnoseFeatures(features, map[string]bool{"com.apple.searchtoold": true}).OK { - t.Error("files-recents should be healthy with searchd enabled") - } - report := DiagnoseFeatures(features, map[string]bool{"com.apple.searchd": true}) - if report.OK || len(report.Features) != 1 || !reflect.DeepEqual(report.Features[0].Disabled, []string{"com.apple.searchd"}) { - t.Errorf("doctor must report Files Recents without searchd: %+v", report) - } -} - -func TestSlimProfileReportsMDMAndAppClipsUntilExcepted(t *testing.T) { - features, err := ResolveFeatures([]string{"mdm", "app-clips"}) - if err != nil { - t.Fatalf("ResolveFeatures(mdm, app-clips) error = %v", err) - } - if report := DiagnoseFeatures(features, (Profile{}).Desired()); report.OK { - t.Errorf("a full slim profile must break MDM and App Clips: %+v", report) - } - kept := Profile{ExceptCategories: map[string]bool{"mdm": true, "other": true}} - if report := DiagnoseFeatures(features, kept.Desired()); !report.OK { - t.Errorf("--except mdm,other must keep MDM and App Clips: %+v", report) - } -} - -func TestDiagnoseFeatures(t *testing.T) { - features, err := ResolveFeatures([]string{"push", "storekit", "universal-links"}) - if err != nil { - t.Fatalf("ResolveFeatures() error = %v", err) - } - - t.Run("all healthy on a stock device", func(t *testing.T) { - report := DiagnoseFeatures(features, map[string]bool{}) - if !report.OK { - t.Errorf("OK = false, want true for %v", report.Features) - } - }) - - t.Run("a disabled daemon breaks its feature", func(t *testing.T) { - disabled := map[string]bool{"com.apple.storekitd": true} - report := DiagnoseFeatures(features, disabled) - if report.OK { - t.Error("OK = true, want false when storekitd is disabled") - } - byID := map[string]FeatureStatus{} - for _, f := range report.Features { - byID[f.ID] = f - } - if byID["storekit"].OK { - t.Error("storekit reported OK despite storekitd disabled") - } - if !reflect.DeepEqual(byID["storekit"].Disabled, []string{"com.apple.storekitd"}) { - t.Errorf("storekit.Disabled = %v, want [com.apple.storekitd]", byID["storekit"].Disabled) - } - if !byID["push"].OK || !byID["universal-links"].OK { - t.Error("unrelated features should stay OK") - } - }) - - t.Run("any disabled backing daemon breaks a multi-daemon feature", func(t *testing.T) { - spotlight, _ := ResolveFeatures([]string{"spotlight"}) - report := DiagnoseFeatures(spotlight, map[string]bool{"com.apple.searchtoold": true}) - if report.OK { - t.Error("spotlight reported OK with searchtoold disabled") - } - }) -} diff --git a/fleet.go b/fleet.go deleted file mode 100644 index a5cc0eb..0000000 --- a/fleet.go +++ /dev/null @@ -1,79 +0,0 @@ -package simslim - -import ( - "context" - "sort" - "sync" -) - -// FleetSnapshot gathers the live resource view of every booted simulator: its -// slim status and memory come from one shared process snapshot; disk usage is -// optional because it shells out to `du` per device and is comparatively slow. -func FleetSnapshot(ctx context.Context, withDisk bool) (TopOutput, error) { - devices, err := ListDevices(ctx) - if err != nil { - return TopOutput{}, err - } - - var booted []Device - for _, d := range devices { - if d.State == "Booted" { - booted = append(booted, d) - } - } - - udids := make([]string, len(booted)) - for i, d := range booted { - udids[i] = d.UDID - } - memory, memErr := MeasureMany(ctx, udids) - - sims := make([]TopSim, len(booted)) - var wg sync.WaitGroup - for i, d := range booted { - wg.Add(1) - go func(i int, d Device) { - defer wg.Done() - sim := TopSim{Device: d} - if st, _, err := ReadStatusForDevice(ctx, d); err == nil { - disabled := st.ManagedDisabled - sim.ManagedDisabled = &disabled - sim.ManagedTotal = st.ManagedTotal - } else { - sim.StatusError = err.Error() - } - if withDisk { - if du, err := DeviceDiskUsage(ctx, d.UDID); err == nil { - bytes := du.Bytes - sim.DiskBytes = &bytes - } - } - sims[i] = sim - }(i, d) - } - wg.Wait() - - var out TopOutput - for _, sim := range sims { - if m, ok := memory[sim.UDID]; ok { - measurement := m - sim.Memory = &measurement - out.TotalBytes += m.Bytes - } else if e, ok := memErr[sim.UDID]; ok { - sim.MemoryError = e - } - out.Sims = append(out.Sims, sim) - } - - sort.Slice(out.Sims, func(i, j int) bool { - return topBytes(out.Sims[i]) > topBytes(out.Sims[j]) - }) - return out, nil -} - -func topBytes(s TopSim) int64 { - if s.Memory == nil { - return -1 - } - return s.Memory.Bytes -} diff --git a/go.mod b/go.mod deleted file mode 100644 index e91304a..0000000 --- a/go.mod +++ /dev/null @@ -1,29 +0,0 @@ -module github.com/mobai-app/simslim - -go 1.26 - -require ( - github.com/charmbracelet/bubbletea v1.3.10 - github.com/charmbracelet/lipgloss v1.1.0 - github.com/mattn/go-isatty v0.0.20 - github.com/urfave/cli/v3 v3.10.1 -) - -require ( - github.com/aymanbagabas/go-osc52/v2 v2.0.1 // indirect - github.com/charmbracelet/colorprofile v0.2.3-0.20250311203215-f60798e515dc // indirect - github.com/charmbracelet/x/ansi v0.10.1 // indirect - github.com/charmbracelet/x/cellbuf v0.0.13-0.20250311204145-2c3ea96c31dd // indirect - github.com/charmbracelet/x/term v0.2.1 // indirect - github.com/erikgeiser/coninput v0.0.0-20211004153227-1c3628e74d0f // indirect - github.com/lucasb-eyer/go-colorful v1.2.0 // indirect - github.com/mattn/go-localereader v0.0.1 // indirect - github.com/mattn/go-runewidth v0.0.16 // indirect - github.com/muesli/ansi v0.0.0-20230316100256-276c6243b2f6 // indirect - github.com/muesli/cancelreader v0.2.2 // indirect - github.com/muesli/termenv v0.16.0 // indirect - github.com/rivo/uniseg v0.4.7 // indirect - github.com/xo/terminfo v0.0.0-20220910002029-abceb7e1c41e // indirect - golang.org/x/sys v0.36.0 // indirect - golang.org/x/text v0.3.8 // indirect -) diff --git a/go.sum b/go.sum deleted file mode 100644 index 09217c7..0000000 --- a/go.sum +++ /dev/null @@ -1,53 +0,0 @@ -github.com/aymanbagabas/go-osc52/v2 v2.0.1 h1:HwpRHbFMcZLEVr42D4p7XBqjyuxQH5SMiErDT4WkJ2k= -github.com/aymanbagabas/go-osc52/v2 v2.0.1/go.mod h1:uYgXzlJ7ZpABp8OJ+exZzJJhRNQ2ASbcXHWsFqH8hp8= -github.com/charmbracelet/bubbletea v1.3.10 h1:otUDHWMMzQSB0Pkc87rm691KZ3SWa4KUlvF9nRvCICw= -github.com/charmbracelet/bubbletea v1.3.10/go.mod h1:ORQfo0fk8U+po9VaNvnV95UPWA1BitP1E0N6xJPlHr4= -github.com/charmbracelet/colorprofile v0.2.3-0.20250311203215-f60798e515dc h1:4pZI35227imm7yK2bGPcfpFEmuY1gc2YSTShr4iJBfs= -github.com/charmbracelet/colorprofile v0.2.3-0.20250311203215-f60798e515dc/go.mod h1:X4/0JoqgTIPSFcRA/P6INZzIuyqdFY5rm8tb41s9okk= -github.com/charmbracelet/lipgloss v1.1.0 h1:vYXsiLHVkK7fp74RkV7b2kq9+zDLoEU4MZoFqR/noCY= -github.com/charmbracelet/lipgloss v1.1.0/go.mod h1:/6Q8FR2o+kj8rz4Dq0zQc3vYf7X+B0binUUBwA0aL30= -github.com/charmbracelet/x/ansi v0.10.1 h1:rL3Koar5XvX0pHGfovN03f5cxLbCF2YvLeyz7D2jVDQ= -github.com/charmbracelet/x/ansi v0.10.1/go.mod h1:3RQDQ6lDnROptfpWuUVIUG64bD2g2BgntdxH0Ya5TeE= -github.com/charmbracelet/x/cellbuf v0.0.13-0.20250311204145-2c3ea96c31dd h1:vy0GVL4jeHEwG5YOXDmi86oYw2yuYUGqz6a8sLwg0X8= -github.com/charmbracelet/x/cellbuf v0.0.13-0.20250311204145-2c3ea96c31dd/go.mod h1:xe0nKWGd3eJgtqZRaN9RjMtK7xUYchjzPr7q6kcvCCs= -github.com/charmbracelet/x/term v0.2.1 h1:AQeHeLZ1OqSXhrAWpYUtZyX1T3zVxfpZuEQMIQaGIAQ= -github.com/charmbracelet/x/term v0.2.1/go.mod h1:oQ4enTYFV7QN4m0i9mzHrViD7TQKvNEEkHUMCmsxdUg= -github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c= -github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= -github.com/erikgeiser/coninput v0.0.0-20211004153227-1c3628e74d0f h1:Y/CXytFA4m6baUTXGLOoWe4PQhGxaX0KpnayAqC48p4= -github.com/erikgeiser/coninput v0.0.0-20211004153227-1c3628e74d0f/go.mod h1:vw97MGsxSvLiUE2X8qFplwetxpGLQrlU1Q9AUEIzCaM= -github.com/lucasb-eyer/go-colorful v1.2.0 h1:1nnpGOrhyZZuNyfu1QjKiUICQ74+3FNCN69Aj6K7nkY= -github.com/lucasb-eyer/go-colorful v1.2.0/go.mod h1:R4dSotOR9KMtayYi1e77YzuveK+i7ruzyGqttikkLy0= -github.com/mattn/go-isatty v0.0.20 h1:xfD0iDuEKnDkl03q4limB+vH+GxLEtL/jb4xVJSWWEY= -github.com/mattn/go-isatty v0.0.20/go.mod h1:W+V8PltTTMOvKvAeJH7IuucS94S2C6jfK/D7dTCTo3Y= -github.com/mattn/go-localereader v0.0.1 h1:ygSAOl7ZXTx4RdPYinUpg6W99U8jWvWi9Ye2JC/oIi4= -github.com/mattn/go-localereader v0.0.1/go.mod h1:8fBrzywKY7BI3czFoHkuzRoWE9C+EiG4R1k4Cjx5p88= -github.com/mattn/go-runewidth v0.0.16 h1:E5ScNMtiwvlvB5paMFdw9p4kSQzbXFikJ5SQO6TULQc= -github.com/mattn/go-runewidth v0.0.16/go.mod h1:Jdepj2loyihRzMpdS35Xk/zdY8IAYHsh153qUoGf23w= -github.com/muesli/ansi v0.0.0-20230316100256-276c6243b2f6 h1:ZK8zHtRHOkbHy6Mmr5D264iyp3TiX5OmNcI5cIARiQI= -github.com/muesli/ansi v0.0.0-20230316100256-276c6243b2f6/go.mod h1:CJlz5H+gyd6CUWT45Oy4q24RdLyn7Md9Vj2/ldJBSIo= -github.com/muesli/cancelreader v0.2.2 h1:3I4Kt4BQjOR54NavqnDogx/MIoWBFa0StPA8ELUXHmA= -github.com/muesli/cancelreader v0.2.2/go.mod h1:3XuTXfFS2VjM+HTLZY9Ak0l6eUKfijIfMUZ4EgX0QYo= -github.com/muesli/termenv v0.16.0 h1:S5AlUN9dENB57rsbnkPyfdGuWIlkmzJjbFf0Tf5FWUc= -github.com/muesli/termenv v0.16.0/go.mod h1:ZRfOIKPFDYQoDFF4Olj7/QJbW60Ol/kL1pU3VfY/Cnk= -github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM= -github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= -github.com/rivo/uniseg v0.2.0/go.mod h1:J6wj4VEh+S6ZtnVlnTBMWIodfgj8LQOQFoIToxlJtxc= -github.com/rivo/uniseg v0.4.7 h1:WUdvkW8uEhrYfLC4ZzdpI2ztxP1I582+49Oc5Mq64VQ= -github.com/rivo/uniseg v0.4.7/go.mod h1:FN3SvrM+Zdj16jyLfmOkMNblXMcoc8DfTHruCPUcx88= -github.com/stretchr/testify v1.11.1 h1:7s2iGBzp5EwR7/aIZr8ao5+dra3wiQyKjjFuvgVKu7U= -github.com/stretchr/testify v1.11.1/go.mod h1:wZwfW3scLgRK+23gO65QZefKpKQRnfz6sD981Nm4B6U= -github.com/urfave/cli/v3 v3.10.1 h1:7Kx9H50hrHbRbyxgO1KP6/BcbiGRz0uYh5YyQ30JEEY= -github.com/urfave/cli/v3 v3.10.1/go.mod h1:ysVLtOEmg2tOy6PknnYVhDoouyC/6N42TMeoMzskhso= -github.com/xo/terminfo v0.0.0-20220910002029-abceb7e1c41e h1:JVG44RsyaB9T2KIHavMF/ppJZNG9ZpyihvCd0w101no= -github.com/xo/terminfo v0.0.0-20220910002029-abceb7e1c41e/go.mod h1:RbqR21r5mrJuqunuUZ/Dhy/avygyECGrLceyNeo4LiM= -golang.org/x/exp v0.0.0-20220909182711-5c715a9e8561 h1:MDc5xs78ZrZr3HMQugiXOAkSZtfTpbJLDr/lwfgO53E= -golang.org/x/exp v0.0.0-20220909182711-5c715a9e8561/go.mod h1:cyybsKvd6eL0RnXn6p/Grxp8F5bW7iYuBgsNCOHpMYE= -golang.org/x/sys v0.0.0-20210809222454-d867a43fc93e/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= -golang.org/x/sys v0.6.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= -golang.org/x/sys v0.36.0 h1:KVRy2GtZBrk1cBYA7MKu5bEZFxQk4NIDV6RLVcC8o0k= -golang.org/x/sys v0.36.0/go.mod h1:OgkHotnGiDImocRcuBABYBEXf8A9a87e/uXjp9XT3ks= -golang.org/x/text v0.3.8 h1:nAL+RVCQ9uMn3vJZbV+MRnydTJFPf8qqY42YiA6MrqY= -golang.org/x/text v0.3.8/go.mod h1:E6s5w1FMmriuDzIBO73fBruAKo1PCIq6d2Q6DHfQ8WQ= -gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA= -gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= diff --git a/gui/Info.plist b/gui/Info.plist index aefdd55..c0a4274 100644 --- a/gui/Info.plist +++ b/gui/Info.plist @@ -9,7 +9,7 @@ CFBundleExecutable SimSlim CFBundleIdentifier - app.mobai.simslim + io.github.akhrameev.simslim CFBundleIconFile SimSlim.icns CFBundleInfoDictionaryVersion @@ -29,7 +29,7 @@ NSHighResolutionCapable NSHumanReadableCopyright - Copyright © Interlap. MIT licensed. + Copyright © Interlap; © 2026 Pavel Akhrameev (Swift port). MIT licensed. NSPrincipalClass NSApplication diff --git a/launchd_batch.go b/launchd_batch.go deleted file mode 100644 index 67f904c..0000000 --- a/launchd_batch.go +++ /dev/null @@ -1,100 +0,0 @@ -package simslim - -import ( - "context" - "encoding/json" - "fmt" - "os" - "os/exec" - "path/filepath" - "strings" -) - -// launchdJobDirs are the RuntimeRoot directories holding the job plists that -// launchd_sim bootstraps into the simulator's system domain. -var launchdJobDirs = []string{"System/Library/LaunchDaemons", "System/Library/LaunchAgents"} - -// unloadChunk bounds how many plist paths go into one `launchctl unload`, so -// the argument list stays far below ARG_MAX however long the profile grows. -const unloadChunk = 64 - -func parseRuntimeRoot(out []byte, runtimeID string) (string, error) { - var parsed struct { - Runtimes []struct { - Identifier string `json:"identifier"` - RuntimeRoot string `json:"runtimeRoot"` - } `json:"runtimes"` - } - if err := json.Unmarshal(out, &parsed); err != nil { - return "", fmt.Errorf("parse simctl list runtimes: %w", err) - } - for _, r := range parsed.Runtimes { - if r.Identifier == runtimeID && r.RuntimeRoot != "" { - return r.RuntimeRoot, nil - } - } - return "", fmt.Errorf("runtime %s has no runtimeRoot", runtimeID) -} - -// launchdJobPlists maps each label to the job plist that defines exactly that -// label. A plist is only used when its own Label key matches, so a renamed or -// shared file can never unload a daemon outside the allowlist; labels without -// a matching plist are left for the per-label path. -func launchdJobPlists(ctx context.Context, root string, labels []string, plistLabel func(context.Context, string) (string, error)) map[string]string { - paths := make(map[string]string, len(labels)) - for _, label := range labels { - if ctx.Err() != nil { - break - } - for _, dir := range launchdJobDirs { - path := filepath.Join(root, dir, label+".plist") - if _, err := os.Stat(path); err != nil { - continue - } - if got, err := plistLabel(ctx, path); err == nil && got == label { - paths[label] = path - break - } - } - } - return paths -} - -// readPlistLabel reads a job plist's Label with the host's plutil, which -// handles both XML and binary plists. -func readPlistLabel(ctx context.Context, path string) (string, error) { - out, err := exec.CommandContext(ctx, "plutil", "-extract", "Label", "raw", "-o", "-", path).Output() - if err != nil { - return "", err - } - return strings.TrimSpace(string(out)), nil -} - -// parseLaunchctlList reads `launchctl list` rows: "PIDStatusLabel", -// with "-" as the PID of a loaded job that is not running. -func parseLaunchctlList(output string) map[string]bool { - loaded := map[string]bool{} - for _, line := range strings.Split(output, "\n") { - fields := strings.Fields(line) - if len(fields) != 3 || fields[2] == "Label" { - continue - } - loaded[fields[2]] = true - } - return loaded -} - -// stillToStop keeps the labels the batch did not finish: no disable override -// yet, or still loaded. A few jobs stay listed even with their override in -// place (on a slim visionOS 27.0 simulator, for example siri.context.service -// and TrustedPeersHelper), so they always take the per-label bootout; the old -// path booted out every label, so this is never more work than before. -func stillToStop(labels []string, disabled, loaded map[string]bool) []string { - var rest []string - for _, l := range labels { - if !disabled[l] || loaded[l] { - rest = append(rest, l) - } - } - return rest -} diff --git a/launchd_batch_test.go b/launchd_batch_test.go deleted file mode 100644 index 6322c67..0000000 --- a/launchd_batch_test.go +++ /dev/null @@ -1,371 +0,0 @@ -package simslim - -import ( - "context" - "os" - "os/exec" - "path/filepath" - "reflect" - "sort" - "strings" - "testing" - "time" -) - -func TestParseRuntimeRoot(t *testing.T) { - out := []byte(`{"runtimes":[ - {"identifier":"com.apple.CoreSimulator.SimRuntime.iOS-26-5","runtimeRoot":"/r/iOS"}, - {"identifier":"com.apple.CoreSimulator.SimRuntime.tvOS-26-0","runtimeRoot":"/r/tvOS"}]}`) - got, err := parseRuntimeRoot(out, "com.apple.CoreSimulator.SimRuntime.tvOS-26-0") - if err != nil || got != "/r/tvOS" { - t.Errorf("parseRuntimeRoot = %q, %v; want /r/tvOS", got, err) - } - if _, err := parseRuntimeRoot(out, "com.apple.CoreSimulator.SimRuntime.watchOS-26-0"); err == nil { - t.Error("an unknown runtime must not resolve") - } -} - -func TestParseLaunchctlList(t *testing.T) { - got := parseLaunchctlList("PID\tStatus\tLabel\n123\t0\tcom.apple.a\n-\t0\tcom.apple.b\n\ngarbage\n") - want := map[string]bool{"com.apple.a": true, "com.apple.b": true} - if !reflect.DeepEqual(got, want) { - t.Errorf("parseLaunchctlList = %v, want %v", got, want) - } -} - -func TestStillToStop(t *testing.T) { - labels := []string{"a", "b", "c", "d"} - disabled := map[string]bool{"a": true, "b": true, "c": true} - loaded := map[string]bool{"b": true} - if got := stillToStop(labels, disabled, loaded); !reflect.DeepEqual(got, []string{"b", "d"}) { - t.Errorf("stillToStop = %v, want [b d]", got) - } -} - -// writeJobPlist writes a minimal launchd job plist whose Label key is label. -func writeJobPlist(t *testing.T, path, label string) { - t.Helper() - if err := os.MkdirAll(filepath.Dir(path), 0o755); err != nil { - t.Fatal(err) - } - body := ` - -Label` + label + ` -` - if err := os.WriteFile(path, []byte(body), 0o644); err != nil { - t.Fatal(err) - } -} - -// A plist is only used when its own Label matches: a file named after one -// label but defining another would otherwise unload an unmanaged daemon. -func TestLaunchdJobPlistsMatchesTheLabelInside(t *testing.T) { - root := t.TempDir() - writeJobPlist(t, filepath.Join(root, "System/Library/LaunchDaemons/com.apple.a.plist"), "com.apple.a") - writeJobPlist(t, filepath.Join(root, "System/Library/LaunchAgents/com.apple.b.plist"), "com.apple.b") - writeJobPlist(t, filepath.Join(root, "System/Library/LaunchDaemons/com.apple.c.plist"), "com.apple.unmanaged") - got := launchdJobPlists(context.Background(), root, []string{"com.apple.a", "com.apple.b", "com.apple.c", "com.apple.missing"}, readPlistLabel) - want := map[string]string{ - "com.apple.a": filepath.Join(root, "System/Library/LaunchDaemons/com.apple.a.plist"), - "com.apple.b": filepath.Join(root, "System/Library/LaunchAgents/com.apple.b.plist"), - } - if !reflect.DeepEqual(got, want) { - t.Errorf("launchdJobPlists = %v, want %v", got, want) - } -} - -// fakeBatchXcrun models a booted simulator's launchd with one file per label: -// $FAKE_DIS holds disable overrides, $FAKE_LOADED the loaded jobs. It answers -// `launchctl unload -w ` the way launchd does: override set, job -// gone. Labels listed in $FAKE_STUCK get the override but stay loaded, and -// FAKE_SLOW_UNLOAD makes every unload outlast its spawn timeout. `load -w` -// lifts each override and loads the job, `enable` lifts one override, and -// `bootstrap` loads one job unless it is still disabled; labels listed in -// $FAKE_NOLOAD never load in this boot session. FAKE_STATE overrides the -// device state the listing reports. While $FAKE_TEARDOWN holds a positive -// count, each spawn uses one up and fails with launchd_sim's error 124, the -// way a simulator answers while its boot session starts or tears down. -// FAKE_SPAWN_ERROR makes every spawn fail with another error, and FAKE_HANG -// makes every spawn hang with a child process that keeps the output pipe open, -// the way simctl outlives a killed xcrun; FAKE_HANG_ONCE names a file whose -// presence makes only the next spawn hang that way. -const fakeBatchXcrun = `#!/bin/sh -printf '%s\n' "$*" >> "$FAKE_LOG" -case "$1 $2 $3" in - "simctl list runtimes") printf '{"runtimes":[{"identifier":"com.apple.CoreSimulator.SimRuntime.%s","runtimeRoot":"%s"}]}\n' "$FAKE_RUNTIME" "$FAKE_ROOT"; exit 0 ;; - "simctl list devices") printf '{"devices":{"com.apple.CoreSimulator.SimRuntime.%s":[{"udid":"%s","name":"Batch","state":"%s","isAvailable":true,"dataPath":"/tmp/batch"}]}}\n' "$FAKE_RUNTIME" "$FAKE_UDID" "${FAKE_STATE:-Booted}"; exit 0 ;; -esac -case "$1 $2" in - "simctl boot"|"simctl bootstatus") exit 0 ;; - "simctl spawn") - shift 3 - n=$(cat "$FAKE_TEARDOWN" 2>/dev/null || echo 0) - if [ "$n" -gt 0 ]; then - echo $((n - 1)) > "$FAKE_TEARDOWN" - echo "An error was encountered processing the command (domain=com.apple.CoreSimulator.LaunchdSimError, code=124): Domain is tearing down" >&2 - exit 124 - fi - [ -n "$FAKE_SPAWN_ERROR" ] && { echo "Invalid device state" >&2; exit 1; } - [ -n "$FAKE_HANG" ] && { sleep 10 & exec sleep 10; } - [ -n "$FAKE_HANG_ONCE" ] && [ -e "$FAKE_HANG_ONCE" ] && { rm -f "$FAKE_HANG_ONCE"; sleep 10 & exec sleep 10; } ;; - *) exit 99 ;; -esac -verb=$2 -case "$verb" in - print-disabled) for f in "$FAKE_DIS"/*; do [ -e "$f" ] && printf '\t"%s" => disabled\n' "${f##*/}"; done ;; - list) printf 'PID\tStatus\tLabel\n'; for f in "$FAKE_LOADED"/*; do [ -e "$f" ] && printf -- '-\t0\t%s\n' "${f##*/}"; done ;; - unload) - [ -n "$FAKE_SLOW_UNLOAD" ] && exec sleep 5 - shift 3 - for p in "$@"; do - l=${p##*/}; l=${l%.plist}; : > "$FAKE_DIS/$l" - grep -qx "$l" "$FAKE_STUCK" 2>/dev/null || rm -f "$FAKE_LOADED/$l" - done ;; - load) - shift 3 - for p in "$@"; do - l=${p##*/}; l=${l%.plist}; rm -f "$FAKE_DIS/$l" - grep -qx "$l" "$FAKE_NOLOAD" 2>/dev/null || : > "$FAKE_LOADED/$l" - done ;; - enable) l=${3#system/}; rm -f "$FAKE_DIS/$l" ;; - bootstrap) - l=${4##*/}; l=${l%.plist} - [ -e "$FAKE_DIS/$l" ] && exit 5 - grep -qx "$l" "$FAKE_NOLOAD" 2>/dev/null && exit 5 - : > "$FAKE_LOADED/$l" ;; - disable) l=${3#system/}; : > "$FAKE_DIS/$l" ;; - bootout) l=${3#system/}; rm -f "$FAKE_LOADED/$l" ;; - *) exit 99 ;; -esac -exit 0 -` - -// batchFake is a booted simulator whose launchd state lives in files, with a -// RuntimeRoot holding a job plist for every label except withoutPlist. -type batchFake struct { - udid, dis, loaded, stuck, noload, teardown, log string -} - -func newBatchFake(t *testing.T, runtime string, labels []string, withoutPlist string) batchFake { - t.Helper() - dir := t.TempDir() - f := batchFake{ - udid: "00000000-0000-0000-0000-0000000000B1", - dis: filepath.Join(dir, "dis"), - loaded: filepath.Join(dir, "loaded"), - stuck: filepath.Join(dir, "stuck"), - noload: filepath.Join(dir, "noload"), - teardown: filepath.Join(dir, "teardown"), - log: filepath.Join(dir, "calls.log"), - } - root := filepath.Join(dir, "RuntimeRoot") - for _, d := range []string{f.dis, f.loaded} { - if err := os.MkdirAll(d, 0o755); err != nil { - t.Fatal(err) - } - } - for _, l := range labels { - if err := os.WriteFile(filepath.Join(f.loaded, l), nil, 0o644); err != nil { - t.Fatal(err) - } - if l != withoutPlist { - writeJobPlist(t, filepath.Join(root, "System/Library/LaunchDaemons", l+".plist"), l) - } - } - xcrun := filepath.Join(dir, "xcrun") - if err := os.WriteFile(xcrun, []byte(fakeBatchXcrun), 0o755); err != nil { - t.Fatal(err) - } - // macOS vets a new executable on its first exec, which can take most of a - // second; run it once so a short SpawnTimeout times the fake, not that check. - warm := exec.Command(xcrun) - warm.Env = append(os.Environ(), "FAKE_LOG="+os.DevNull) - _ = warm.Run() - t.Setenv("PATH", dir+string(os.PathListSeparator)+os.Getenv("PATH")) - t.Setenv("FAKE_LOG", f.log) - t.Setenv("FAKE_DIS", f.dis) - t.Setenv("FAKE_LOADED", f.loaded) - t.Setenv("FAKE_STUCK", f.stuck) - t.Setenv("FAKE_NOLOAD", f.noload) - t.Setenv("FAKE_TEARDOWN", f.teardown) - t.Setenv("FAKE_ROOT", root) - t.Setenv("FAKE_RUNTIME", runtime) - t.Setenv("FAKE_UDID", f.udid) - return f -} - -// calls splits the logged xcrun calls into batch unloads and per-label spawns. -func (f batchFake) calls(t *testing.T) (unloads, perLabel []string) { - t.Helper() - log, err := os.ReadFile(f.log) - if err != nil { - t.Fatal(err) - } - for _, call := range strings.Split(strings.TrimSpace(string(log)), "\n") { - switch { - case strings.Contains(call, " launchctl unload "): - unloads = append(unloads, call) - case strings.Contains(call, " launchctl disable "), strings.Contains(call, " launchctl bootout "): - perLabel = append(perLabel, call) - } - } - return unloads, perLabel -} - -// assertStopped checks that every label ends with an override and unloaded. -func (f batchFake) assertStopped(t *testing.T, labels []string) { - t.Helper() - for _, l := range labels { - if _, err := os.Stat(filepath.Join(f.dis, l)); err != nil { - t.Errorf("%s has no disable override", l) - } - if _, err := os.Stat(filepath.Join(f.loaded, l)); err == nil { - t.Errorf("%s is still loaded", l) - } - } -} - -func sortedLabels(set map[string]bool) []string { - labels := make([]string, 0, len(set)) - for l := range set { - labels = append(labels, l) - } - sort.Strings(labels) - return labels -} - -func TestNoRebootStopsEveryDaemonWithOneBatchSpawn(t *testing.T) { - labels := sortedLabels(Profile{}.Desired()) - // Every job is loaded; all but one ship a plist, so that one must take the - // per-label path. - withoutPlist := labels[0] - f := newBatchFake(t, "iOS-26-5", labels, withoutPlist) - - if _, err := EnableSlimNoReboot(context.Background(), "default", f.udid, Profile{}, nil); err != nil { - t.Fatalf("EnableSlimNoReboot: %v", err) - } - unloads, perLabel := f.calls(t) - wantUnloads := (len(labels) - 1 + unloadChunk - 1) / unloadChunk - if len(unloads) != wantUnloads { - t.Errorf("%d unload spawns for %d plists, want %d", len(unloads), len(labels)-1, wantUnloads) - } - if len(perLabel) != 2 { - t.Errorf("per-label spawns = %v, want only the disable and bootout of %s", perLabel, withoutPlist) - } - f.assertStopped(t, labels) -} - -// A job that keeps its process after `unload -w` is disabled but still loaded; -// it must still get the per-label bootout. -func TestNoRebootBootsOutJobsTheBatchLeftLoaded(t *testing.T) { - labels := sortedLabels(Profile{}.Desired()) - stuck := labels[3] - f := newBatchFake(t, "iOS-26-5", labels, "") - if err := os.WriteFile(f.stuck, []byte(stuck+"\n"), 0o644); err != nil { - t.Fatal(err) - } - - if _, err := EnableSlimNoReboot(context.Background(), "default", f.udid, Profile{}, nil); err != nil { - t.Fatalf("EnableSlimNoReboot: %v", err) - } - _, perLabel := f.calls(t) - want := []string{ - "simctl spawn " + f.udid + " launchctl disable system/" + stuck, - "simctl spawn " + f.udid + " launchctl bootout system/" + stuck, - } - if !reflect.DeepEqual(perLabel, want) { - t.Errorf("per-label spawns = %v, want %v", perLabel, want) - } - f.assertStopped(t, labels) -} - -// Without a RuntimeRoot there are no plists to batch, so every label takes the -// per-label path and the slim still succeeds. -func TestNoRebootFallsBackWithoutRuntimeRoot(t *testing.T) { - labels := sortedLabels(Profile{}.Desired()) - f := newBatchFake(t, "iOS-26-5", labels, "") - t.Setenv("FAKE_ROOT", "") - - if _, err := EnableSlimNoReboot(context.Background(), "default", f.udid, Profile{}, nil); err != nil { - t.Fatalf("EnableSlimNoReboot: %v", err) - } - unloads, perLabel := f.calls(t) - if len(unloads) != 0 || len(perLabel) != 2*len(labels) { - t.Errorf("%d unload and %d per-label spawns, want 0 and %d", len(unloads), len(perLabel), 2*len(labels)) - } - f.assertStopped(t, labels) -} - -// A chunk that outlasts its spawn timeout ends the batch at once, so a slow -// host keeps its remaining budget for the per-label path. -func TestNoRebootStopsBatchingAfterASlowChunk(t *testing.T) { - labels := sortedLabels(Profile{}.Desired()) - f := newBatchFake(t, "iOS-26-5", labels, "") - t.Setenv("FAKE_SLOW_UNLOAD", "1") - previous := SpawnTimeout - SpawnTimeout = 300 * time.Millisecond - t.Cleanup(func() { SpawnTimeout = previous }) - - if _, err := EnableSlimNoReboot(context.Background(), "default", f.udid, Profile{}, nil); err != nil { - t.Fatalf("EnableSlimNoReboot: %v", err) - } - unloads, perLabel := f.calls(t) - if len(unloads) != 1 { - t.Errorf("%d unload spawns after the first one timed out, want 1", len(unloads)) - } - if len(perLabel) != 2*len(labels) { - t.Errorf("%d per-label spawns, want %d", len(perLabel), 2*len(labels)) - } - f.assertStopped(t, labels) -} - -// A second run on a device that is already slim has nothing to stop: it spawns -// no unload and no per-label transition, and says so instead of claiming a batch. -func TestNoRebootOnASlimDeviceStopsNothing(t *testing.T) { - labels := sortedLabels(Profile{}.Desired()) - f := newBatchFake(t, "iOS-26-5", labels, "") - if _, err := EnableSlimNoReboot(context.Background(), "default", f.udid, Profile{}, nil); err != nil { - t.Fatalf("first EnableSlimNoReboot: %v", err) - } - if err := os.Remove(f.log); err != nil { - t.Fatal(err) - } - - var lines []string - report := Reporter(func(s string) { lines = append(lines, s) }) - if _, err := EnableSlimNoReboot(context.Background(), "default", f.udid, Profile{}, report); err != nil { - t.Fatalf("second EnableSlimNoReboot: %v", err) - } - unloads, perLabel := f.calls(t) - if len(unloads) != 0 || len(perLabel) != 0 { - t.Errorf("%d unload and %d per-label spawns on a slim device, want none", len(unloads), len(perLabel)) - } - out := strings.Join(lines, "\n") - if strings.Contains(out, "stopped in one batch") || !strings.Contains(out, "already stopped") { - t.Errorf("report on a slim device = %q, want the already-stopped line", out) - } - f.assertStopped(t, labels) -} - -// The batch only unloads the device's own desired labels, so visionOS keeps -// mobileassetd (and with it the surroundings) running. -func TestNoRebootBatchKeepsVisionMobileAssetsRunning(t *testing.T) { - const label = "com.apple.mobileassetd" - f := newBatchFake(t, "xrOS-27-0", sortedLabels(Profile{}.Desired()), "") - - if _, err := EnableSlimNoReboot(context.Background(), "default", f.udid, Profile{}, nil); err != nil { - t.Fatalf("EnableSlimNoReboot: %v", err) - } - unloads, perLabel := f.calls(t) - for _, call := range append(unloads, perLabel...) { - if strings.Contains(call, label) { - t.Errorf("visionOS slim passed %s to launchctl", label) - } - } - if _, err := os.Stat(filepath.Join(f.loaded, label)); err != nil { - t.Errorf("%s is no longer loaded on visionOS", label) - } - if _, err := os.Stat(filepath.Join(f.dis, label)); err == nil { - t.Errorf("%s got a disable override on visionOS", label) - } -} diff --git a/live.go b/live.go deleted file mode 100644 index 4fa6d15..0000000 --- a/live.go +++ /dev/null @@ -1,372 +0,0 @@ -package simslim - -import ( - "context" - "fmt" - "slices" - "sort" - "strings" -) - -// EnableServices re-enables categories (IDs from `simslim profiles`) and -// individual managed daemons on a booted simulator, live, without a reboot: -// each disable override is lifted and each job loaded into the running boot -// session. It keeps no state of its own, like `on --no-reboot`: the next `on` -// or `watch` pass applies its profile again. With save, the change is also -// written to that profile file (see SaveServices), which is how it persists: -// on a booted simulator only once the live change succeeded; a simulator that -// is not booted only gets the file, and without save it is an error. -func EnableServices(ctx context.Context, udid string, ids []string, save string, report Reporter) (ServicesOutput, error) { - categories, labels, err := resolveServiceIDs(ids) - if err != nil { - return ServicesOutput{}, err - } - if len(categories)+len(labels) == 0 { - return ServicesOutput{}, fmt.Errorf("name at least one category ID or managed daemon to enable (see `simslim profiles`)") - } - if err := checkSave(save, categories, labels, true); err != nil { - return ServicesOutput{}, err - } - d, err := serviceTarget(ctx, udid, save) - if err != nil { - return ServicesOutput{}, err - } - out := ServicesOutput{Action: "enable", UDID: d.UDID, Live: d.State == "Booted", Labels: []string{}} - if out.Live { - out.Labels = sortedKeys(coveredLabels(categories, labels)) - report.report(fmt.Sprintf("Starting %d background services without a reboot...", len(out.Labels))) - if out.NotStarted, err = startServices(ctx, d, out.Labels, report); err != nil { - return out, unsaved(err, save) - } - } - return out, saveServices(&out, save, categories, labels, true) -} - -// DisableServices is the inverse of EnableServices: it stops categories and -// daemons on a booted simulator at once, each one booted out of the running -// boot session with its disable override set, no reboot. A daemon named on its -// own is always stopped, unless the platform needs it. A daemon a named -// category covers is also kept while another category that lists it is fully -// enabled right now (iCloud and the store share the AMS daemons). Both are -// reported in StillEnabled. With save, the categories and daemons are also -// removed from that profile file, once the live change succeeded. -func DisableServices(ctx context.Context, udid string, ids []string, save string, report Reporter) (ServicesOutput, error) { - categories, labels, err := resolveServiceIDs(ids) - if err != nil { - return ServicesOutput{}, err - } - if len(categories)+len(labels) == 0 { - return ServicesOutput{}, fmt.Errorf("name at least one category ID or managed daemon to disable (see `simslim profiles`)") - } - slimmable := SlimmableSet() - for _, l := range labels { - if !slimmable[l] { - return ServicesOutput{}, fmt.Errorf("%s is never disabled: simslim keeps it running for compatibility (see `simslim profiles`)", l) - } - } - if err := checkSave(save, categories, labels, false); err != nil { - return ServicesOutput{}, err - } - d, err := serviceTarget(ctx, udid, save) - if err != nil { - return ServicesOutput{}, err - } - out := ServicesOutput{Action: "disable", UDID: d.UDID, Live: d.State == "Booted", Labels: []string{}} - if out.Live { - if err := stopNamed(ctx, d, &out, categories, labels, report); err != nil { - return out, unsaved(err, save) - } - } - return out, saveServices(&out, save, categories, labels, false) -} - -// stopNamed stops what DisableServices was told to on a booted simulator, -// filling out.Labels with what it stops and out.StillEnabled with what it keeps. -func stopNamed(ctx context.Context, d Device, out *ServicesOutput, categories, labels []string, report Reporter) error { - disabled, err := readDisabled(ctx, d.Set, d.UDID) - if err != nil { - return err - } - slimmable := SlimmableSet() - covered := coveredLabels(categories, labels) - allowed := desiredForDevice(d, covered) - kept := enabledNeighbours(categories, labels, disabled) - for _, l := range sortedKeys(covered) { - if allowed[l] && slimmable[l] && !kept[l] { - out.Labels = append(out.Labels, l) - } else { - out.StillEnabled = append(out.StillEnabled, l) - } - } - if len(out.Labels) == 0 { - return nil - } - report.report(fmt.Sprintf("Stopping %d background services without a reboot...", len(out.Labels))) - return stopServices(ctx, d, out.Labels, report) -} - -// enabledNeighbours returns the labels the disabling categories cover that -// another category, one not being disabled and with every label enabled right -// now, also lists. Only the live state says which features are on, so that is -// what decides: stopping the store keeps the AMS daemons iCloud shares while -// iCloud is fully running. A label named on its own is never kept: naming it -// is asking for exactly that daemon to stop. -func enabledNeighbours(disabling, named []string, disabled map[string]bool) map[string]bool { - covered := coveredLabels(disabling, nil) - for _, l := range named { - delete(covered, l) - } - kept := map[string]bool{} - for _, c := range Categories { - if slices.Contains(disabling, c.ID) { - continue - } - enabled, shares := true, false - for _, l := range c.Labels { - enabled = enabled && !disabled[l] - shares = shares || covered[l] - } - if !enabled || !shares { - continue - } - for _, l := range c.Labels { - if covered[l] { - kept[l] = true - } - } - } - return kept -} - -// checkSave validates the profile file --save names before anything changes, -// so a bad file fails the command up front. -func checkSave(save string, categories, labels []string, enable bool) error { - if save == "" { - return nil - } - _, _, err := updatedProfile(save, categories, labels, enable) - return err -} - -// saveServices writes the change to the profile file --save names, if any, -// once the simulator has been changed. -func saveServices(out *ServicesOutput, save string, categories, labels []string, enable bool) error { - if save == "" { - return nil - } - if err := SaveServices(save, categories, labels, enable); err != nil { - if out.Live { - return fmt.Errorf("the simulator was changed, but profile %s was not: %w", save, err) - } - return err - } - out.Saved = save - return nil -} - -// unsaved notes on a failed live change that --save left the profile alone. -func unsaved(err error, save string) error { - if save == "" { - return err - } - return fmt.Errorf("%w (profile %s not changed)", err, save) -} - -// serviceTarget resolves the exact simulator `enable` and `disable` act on, so -// a simctl alias such as "all" can never fan out across devices. Only a booted -// simulator can change live; with a profile to save, any simulator is fine, -// since only the file changes. -func serviceTarget(ctx context.Context, udid, save string) (Device, error) { - d, err := FindDevice(ctx, udid, "") - if err != nil { - return Device{}, err - } - if d.State != "Booted" && save == "" { - return Device{}, fmt.Errorf("simulator %s is not booted (it is %s): enable and disable change a running simulator only; pass --save to record the change, then apply it with `simslim on %s --profile `", d.UDID, d.State, d.UDID) - } - return d, nil -} - -// resolveServiceIDs sorts the IDs `enable` and `disable` accept into category -// IDs and individual managed labels, rejecting anything else. -func resolveServiceIDs(ids []string) (categories, labels []string, err error) { - managed := managedSet() - seenCategory, seenLabel := map[string]bool{}, map[string]bool{} - for _, id := range ids { - switch { - case seenCategory[id] || seenLabel[id]: - case isCategory(id): - seenCategory[id] = true - categories = append(categories, id) - case managed[id]: - seenLabel[id] = true - labels = append(labels, id) - default: - return nil, nil, fmt.Errorf("unknown category or managed daemon %q (see `simslim profiles`)", id) - } - } - sort.Strings(categories) - sort.Strings(labels) - return categories, labels, nil -} - -func isCategory(id string) bool { - _, ok := CategoryByID(id) - return ok -} - -// coveredLabels is every managed label the categories and labels name. -func coveredLabels(categories, labels []string) map[string]bool { - covered := map[string]bool{} - for _, id := range categories { - if c, ok := CategoryByID(id); ok { - for _, l := range c.Labels { - covered[l] = true - } - } - } - managed := managedSet() - for _, l := range labels { - if managed[l] { - covered[l] = true - } - } - return covered -} - -// startServices lifts the disable override of each label and loads its job into -// the running boot session, so the daemons are back without a reboot. One -// `launchctl load -w` per chunk handles every label whose job plist is found; -// what is still disabled afterwards gets a per-label `launchctl enable`, and -// what is still not loaded a per-label bootstrap. A label without a plist (an -// XPC service, for example) only needs its override lifted: launchd starts it -// on demand. Labels launchd re-enabled but would not load in this boot session -// are returned; they start at the next boot. A label left disabled is an error. -func startServices(ctx context.Context, d Device, labels []string, report Reporter) (notStarted []string, err error) { - set, udid := d.Set, d.UDID - disabled, loaded, err := serviceState(ctx, set, udid) - if err != nil { - return nil, err - } - var candidates []string - for _, l := range labels { - if disabled[l] || !loaded[l] { - candidates = append(candidates, l) - } - } - plists, haveRoot := map[string]string{}, false - if d.RuntimeID != "" && len(candidates) > 0 { - if root, err := runtimeRoot(ctx, d.RuntimeID); err == nil { - plists, haveRoot = launchdJobPlists(ctx, root, candidates, readPlistLabel), true - } - } - // Without the RuntimeRoot nothing tells a missing plist from an unknown - // one, so every unloaded label counts as one launchd should load. - loadable := func(l string) bool { return plists[l] != "" || !haveRoot } - var pending []string - for _, l := range candidates { - if disabled[l] || loadable(l) { - pending = append(pending, l) - } - } - if len(pending) == 0 { - report.report(fmt.Sprintf(" all %d services were already running", len(labels))) - return nil, nil - } - var paths []string - for _, l := range pending { - if p := plists[l]; p != "" { - paths = append(paths, p) - } - } - if len(paths) > 0 { - loadJobs(ctx, set, udid, paths) - if disabled, loaded, err = serviceState(ctx, set, udid); err != nil { - return nil, err - } - report.report(fmt.Sprintf(" %d/%d services started in one batch", len(pending)-len(stillToStart(pending, disabled, loaded, loadable)), len(pending))) - } - var toEnable []string - unloaded := map[string]string{} - for _, l := range pending { - if disabled[l] { - toEnable = append(toEnable, l) - } - if p := plists[l]; p != "" && !loaded[l] { - unloaded[l] = p - } - } - if len(toEnable) > 0 { - if err := applyDelta(ctx, set, udid, nil, toEnable, "disable", report); err != nil { - return nil, err - } - } - if len(unloaded) > 0 { - bootstrapJobs(ctx, set, udid, unloaded) - } - if len(toEnable)+len(unloaded) > 0 { - if disabled, loaded, err = serviceState(ctx, set, udid); err != nil { - return nil, err - } - } - var still []string - for _, l := range pending { - switch { - case disabled[l]: - still = append(still, l) - case !loaded[l] && loadable(l): - notStarted = append(notStarted, l) - } - } - if len(still) > 0 { - return notStarted, fmt.Errorf("%d of %d services are still disabled: %s", len(still), len(pending), strings.Join(still, ", ")) - } - return notStarted, nil -} - -// stillToStart keeps the labels that are still disabled, or still not loaded -// although launchd could load them. -func stillToStart(labels []string, disabled, loaded map[string]bool, loadable func(string) bool) []string { - var rest []string - for _, l := range labels { - if disabled[l] || !loaded[l] && loadable(l) { - rest = append(rest, l) - } - } - return rest -} - -// serviceState reads the disable overrides and the loaded jobs together. -func serviceState(ctx context.Context, set, udid string) (disabled, loaded map[string]bool, err error) { - if disabled, err = readDisabled(ctx, set, udid); err != nil { - return nil, nil, err - } - if loaded, err = loadedLabels(ctx, set, udid); err != nil { - return nil, nil, err - } - return disabled, loaded, nil -} - -// stopServices disables each label and boots its job out of the running boot -// session: one `launchctl unload -w` per chunk first, then a per-label disable -// and bootout for whatever the batch missed. Every override is read back. -func stopServices(ctx context.Context, d Device, labels []string, report Reporter) error { - remaining := unloadInBatch(ctx, d.Set, d.UDID, d.RuntimeID, labels, readPlistLabel, report) - if err := applyDelta(ctx, d.Set, d.UDID, remaining, nil, liveDisable, report); err != nil { - return err - } - after, err := readDisabled(ctx, d.Set, d.UDID) - if err != nil { - return err - } - missing := 0 - for _, l := range labels { - if !after[l] { - missing++ - } - } - if missing > 0 { - return fmt.Errorf("%d of %d disable overrides did not take", missing, len(labels)) - } - return nil -} diff --git a/live_test.go b/live_test.go deleted file mode 100644 index 08d33e2..0000000 --- a/live_test.go +++ /dev/null @@ -1,430 +0,0 @@ -package simslim - -import ( - "context" - "os" - "path/filepath" - "reflect" - "strings" - "testing" - "time" -) - -// useTestCategories swaps in a two-category catalog: cloud and media share -// com.apple.shared, and media has a compatibility service. -func useTestCategories(t *testing.T) { - t.Helper() - saved := Categories - Categories = []Category{ - {ID: "cloud", Name: "Cloud", ApproxMemoryMB: 1, Labels: []string{"com.apple.cloudd", "com.apple.lazy", "com.apple.shared", "com.apple.xpc"}}, - {ID: "media", Name: "Media", ApproxMemoryMB: 1, Labels: []string{"com.apple.mediad", "com.apple.shared"}, - AlwaysEnabled: []AlwaysEnabledService{{Label: "com.apple.required", Reason: "needed"}}}, - } - t.Cleanup(func() { Categories = saved }) -} - -// cloudLabels are the test catalog's cloud category (see useTestCategories). -var cloudLabels = []string{"com.apple.cloudd", "com.apple.lazy", "com.apple.shared", "com.apple.xpc"} - -// slimmed leaves labels the way a slim boot does: disabled and not loaded. -func (f batchFake) slimmed(t *testing.T, labels ...string) { - t.Helper() - for _, l := range labels { - if err := os.WriteFile(filepath.Join(f.dis, l), nil, 0o644); err != nil { - t.Fatal(err) - } - if err := os.Remove(filepath.Join(f.loaded, l)); err != nil && !os.IsNotExist(err) { - t.Fatal(err) - } - } -} - -// spawns returns the logged `launchctl ` spawns. -func (f batchFake) spawns(t *testing.T, verb string) []string { - t.Helper() - var out []string - for _, call := range xcrunCalls(t, f.log) { - if strings.Contains(call, " launchctl "+verb+" ") { - out = append(out, call) - } - } - return out -} - -// assertEnabled checks that no label has a disable override, and that each -// label in loaded is also loaded. -func (f batchFake) assertEnabled(t *testing.T, labels []string, loaded ...string) { - t.Helper() - for _, l := range labels { - if _, err := os.Stat(filepath.Join(f.dis, l)); err == nil { - t.Errorf("%s still has a disable override", l) - } - } - for _, l := range loaded { - if _, err := os.Stat(filepath.Join(f.loaded, l)); err != nil { - t.Errorf("%s is not loaded", l) - } - } -} - -// assertNoSpawn fails if a command did more than look the simulator up. -func (f batchFake) assertNoSpawn(t *testing.T, what string) { - t.Helper() - if _, err := os.Stat(f.log); os.IsNotExist(err) { - return // not even a lookup - } - for _, call := range xcrunCalls(t, f.log) { - if call != "simctl list devices -j" { - t.Errorf("%s ran %q", what, call) - } - } -} - -// enable on a booted simulator lifts every override and loads the jobs with one -// `launchctl load -w`, without a reboot. A label without a job plist only needs -// its override lifted; one launchd will not load in this boot session is -// bootstrapped once and reported, not failed. -func TestEnableServicesStartsDaemonsWithoutAReboot(t *testing.T) { - useTestCategories(t) - labels := sortedLabels(SlimmableSet()) - f := newBatchFake(t, "iOS-26-5", labels, "com.apple.xpc") - f.slimmed(t, labels...) - if err := os.WriteFile(f.noload, []byte("com.apple.lazy\n"), 0o644); err != nil { - t.Fatal(err) - } - - out, err := EnableServices(context.Background(), f.udid, []string{"cloud"}, "", nil) - if err != nil { - t.Fatalf("EnableServices: %v", err) - } - if !out.Live || !reflect.DeepEqual(out.Labels, cloudLabels) || !reflect.DeepEqual(out.NotStarted, []string{"com.apple.lazy"}) { - t.Errorf("EnableServices = %+v, want live, labels %v, and lazy not started", out, cloudLabels) - } - if out.Saved != "" { - t.Errorf("EnableServices without --save saved %q", out.Saved) - } - if loads := f.spawns(t, "load"); len(loads) != 1 || strings.Count(loads[0], ".plist") != 3 { - t.Errorf("load spawns = %v, want one batch of the three plists", loads) - } - if enables := f.spawns(t, "enable"); !reflect.DeepEqual(enables, []string{"simctl spawn " + f.udid + " launchctl enable system/com.apple.xpc"}) { - t.Errorf("per-label enables = %v, want only the plist-less com.apple.xpc", enables) - } - if boots := f.spawns(t, "bootstrap"); len(boots) != 1 || !strings.HasSuffix(boots[0], "/com.apple.lazy.plist") { - t.Errorf("bootstraps = %v, want one retry of com.apple.lazy", boots) - } - for _, call := range xcrunCalls(t, f.log) { - if strings.Contains(call, "simctl shutdown") || strings.Contains(call, " launchctl unload ") || strings.Contains(call, " launchctl disable ") { - t.Errorf("enable ran %q", call) - } - } - f.assertEnabled(t, cloudLabels, "com.apple.cloudd", "com.apple.shared") - f.assertStopped(t, []string{"com.apple.mediad"}) -} - -// disable stops a category at once, except the daemons another category that -// is fully enabled right now still needs: media keeps com.apple.shared running. -func TestDisableServicesKeepsWhatAnEnabledCategoryShares(t *testing.T) { - useTestCategories(t) - labels := sortedLabels(SlimmableSet()) - f := newBatchFake(t, "iOS-26-5", labels, "com.apple.xpc") - - out, err := DisableServices(context.Background(), f.udid, []string{"cloud"}, "", nil) - if err != nil { - t.Fatalf("DisableServices: %v", err) - } - stopped := []string{"com.apple.cloudd", "com.apple.lazy", "com.apple.xpc"} - if !out.Live || !reflect.DeepEqual(out.Labels, stopped) || !reflect.DeepEqual(out.StillEnabled, []string{"com.apple.shared"}) { - t.Errorf("DisableServices = %+v, want %v stopped and com.apple.shared kept", out, stopped) - } - unloads, perLabel := f.calls(t) - if len(unloads) != 1 || len(perLabel) != 2 { - t.Errorf("%d unload and %d per-label spawns, want one batch plus the disable and bootout of com.apple.xpc", len(unloads), len(perLabel)) - } - f.assertStopped(t, stopped) - f.assertEnabled(t, []string{"com.apple.shared", "com.apple.mediad"}, "com.apple.shared", "com.apple.mediad") -} - -// A category that is already partly slimmed protects nothing: with mediad -// disabled, stopping cloud stops com.apple.shared too. -func TestDisableServicesStopsWhatNoEnabledCategoryNeeds(t *testing.T) { - useTestCategories(t) - labels := sortedLabels(SlimmableSet()) - f := newBatchFake(t, "iOS-26-5", labels, "") - f.slimmed(t, "com.apple.mediad") - - out, err := DisableServices(context.Background(), f.udid, []string{"cloud"}, "", nil) - if err != nil { - t.Fatalf("DisableServices: %v", err) - } - if !reflect.DeepEqual(out.Labels, cloudLabels) || len(out.StillEnabled) != 0 { - t.Errorf("DisableServices = %+v, want every cloud label stopped", out) - } - f.assertStopped(t, cloudLabels) -} - -// Without --save, a simulator that is not booted is refused: there is nothing -// to change live and no state to record. -func TestServicesRefuseASimulatorThatIsNotBooted(t *testing.T) { - useTestCategories(t) - for _, state := range []string{"Shutdown", "Shutting Down"} { - f := newBatchFake(t, "iOS-26-5", nil, "") - t.Setenv("FAKE_STATE", state) - _, err := EnableServices(context.Background(), f.udid, []string{"cloud"}, "", nil) - if err == nil || !strings.Contains(err.Error(), "is not booted") || !strings.Contains(err.Error(), "--profile") { - t.Errorf("EnableServices while %s = %v, want a not-booted error suggesting on --profile", state, err) - } - _, err = DisableServices(context.Background(), f.udid, []string{"cloud"}, "", nil) - if err == nil || !strings.Contains(err.Error(), "is not booted") { - t.Errorf("DisableServices while %s = %v, want a not-booted error", state, err) - } - f.assertNoSpawn(t, "a refused command") - } -} - -// With --save, a shutdown simulator only gets the profile written; nothing is -// applied and nothing is spawned. -func TestServicesSaveOnAShutdownSimulator(t *testing.T) { - useTestCategories(t) - f := newBatchFake(t, "iOS-26-5", nil, "") - t.Setenv("FAKE_STATE", "Shutdown") - path := filepath.Join(t.TempDir(), "dev.json") - - out, err := EnableServices(context.Background(), f.udid, []string{"cloud", "com.apple.mediad"}, path, nil) - if err != nil { - t.Fatalf("EnableServices --save: %v", err) - } - if out.Live || out.Saved != path || len(out.Labels) != 0 { - t.Errorf("EnableServices --save = %+v, want not live, nothing applied, saved to %s", out, path) - } - assertProfileFile(t, path, `{ - "except": [ - "cloud" - ], - "keep": [ - "com.apple.mediad" - ] -} -`) - out, err = DisableServices(context.Background(), f.udid, []string{"cloud"}, path, nil) - if err != nil || out.Live || out.Saved != path { - t.Fatalf("DisableServices --save = (%+v, %v), want saved, not live", out, err) - } - assertProfileFile(t, path, `{ - "keep": [ - "com.apple.mediad" - ] -} -`) - f.assertNoSpawn(t, "--save on a shutdown simulator") -} - -// With --save on a booted simulator, the change is applied live and saved. -func TestEnableServicesSavesAndAppliesLive(t *testing.T) { - useTestCategories(t) - labels := sortedLabels(SlimmableSet()) - f := newBatchFake(t, "iOS-26-5", labels, "") - f.slimmed(t, labels...) - path := filepath.Join(t.TempDir(), "ci.json") - - out, err := EnableServices(context.Background(), f.udid, []string{"media"}, path, nil) - if err != nil { - t.Fatalf("EnableServices --save: %v", err) - } - if !out.Live || out.Saved != path || !reflect.DeepEqual(out.Labels, []string{"com.apple.mediad", "com.apple.shared"}) { - t.Errorf("EnableServices --save = %+v, want media started live and saved", out) - } - f.assertEnabled(t, []string{"com.apple.mediad", "com.apple.shared"}, "com.apple.mediad", "com.apple.shared") - if p, err := LoadSlimProfile(path); err != nil || !p.ExceptCategories["media"] { - t.Errorf("saved profile = (%+v, %v), want media excepted", p, err) - } -} - -// An invalid profile file fails the command before anything changes. -func TestServicesSaveRejectsAnInvalidProfileFirst(t *testing.T) { - useTestCategories(t) - labels := sortedLabels(SlimmableSet()) - f := newBatchFake(t, "iOS-26-5", labels, "") - f.slimmed(t, labels...) - path := filepath.Join(t.TempDir(), "bad.json") - if err := os.WriteFile(path, []byte(`{"except": ["nope"]}`), 0o644); err != nil { - t.Fatal(err) - } - _, err := EnableServices(context.Background(), f.udid, []string{"cloud"}, path, nil) - if err == nil || !strings.Contains(err.Error(), `unknown category "nope"`) { - t.Errorf("EnableServices with a bad profile = %v, want a validation error", err) - } - f.assertNoSpawn(t, "a refused --save") -} - -// Argument mistakes fail before any simulator is looked up. -func TestServicesRejectBadArguments(t *testing.T) { - useTestCategories(t) - t.Setenv("PATH", t.TempDir()) // no xcrun: a lookup would fail with another error - ctx := context.Background() - const udid = "00000000-0000-0000-0000-0000000000C3" - for _, tc := range []struct { - name string - run func() error - want string - }{ - {"enable nothing", func() error { _, err := EnableServices(ctx, udid, nil, "", nil); return err }, "name at least one category ID or managed daemon to enable"}, - {"enable unknown", func() error { _, err := EnableServices(ctx, udid, []string{"bogus"}, "", nil); return err }, `unknown category or managed daemon "bogus"`}, - {"disable nothing", func() error { _, err := DisableServices(ctx, udid, nil, "", nil); return err }, "name at least one category ID or managed daemon to disable"}, - {"disable required", func() error { - _, err := DisableServices(ctx, udid, []string{"com.apple.required"}, "", nil) - return err - }, "com.apple.required is never disabled"}, - } { - if err := tc.run(); err == nil || !strings.Contains(err.Error(), tc.want) { - t.Errorf("%s: err = %v, want %q", tc.name, err, tc.want) - } - } -} - -// Right after a boot launchd_sim answers 124 ("Domain is tearing down") for a -// few seconds. enable retries its reads instead of failing, and reports the -// error only once the retries run out. -func TestEnableServicesWaitsForLaunchdToSettle(t *testing.T) { - useTestCategories(t) - delays := launchdRetryDelays - launchdRetryDelays = []time.Duration{time.Millisecond, time.Millisecond, time.Millisecond, time.Millisecond} - t.Cleanup(func() { launchdRetryDelays = delays }) - labels := sortedLabels(SlimmableSet()) - f := newBatchFake(t, "iOS-26-5", labels, "") - f.slimmed(t, labels...) - if err := os.WriteFile(f.teardown, []byte("3\n"), 0o644); err != nil { - t.Fatal(err) - } - - if _, err := EnableServices(context.Background(), f.udid, []string{"cloud"}, "", nil); err != nil { - t.Fatalf("EnableServices while launchd settles: %v", err) - } - f.assertEnabled(t, cloudLabels, "com.apple.cloudd", "com.apple.shared") - - if err := os.WriteFile(f.teardown, []byte("1000\n"), 0o644); err != nil { - t.Fatal(err) - } - _, err := EnableServices(context.Background(), f.udid, []string{"media"}, "", nil) - if err == nil || !strings.Contains(err.Error(), "tearing down") { - t.Errorf("EnableServices with launchd never ready = %v, want the 124 error", err) - } -} - -// A daemon named on its own is stopped even while every category that lists -// it is fully enabled: only a named category's daemons are kept for a neighbour. -func TestDisableServicesStopsANamedDaemon(t *testing.T) { - useTestCategories(t) - labels := sortedLabels(SlimmableSet()) - f := newBatchFake(t, "iOS-26-5", labels, "") - - for _, label := range []string{"com.apple.mediad", "com.apple.shared"} { - out, err := DisableServices(context.Background(), f.udid, []string{label}, "", nil) - if err != nil { - t.Fatalf("DisableServices %s: %v", label, err) - } - if !reflect.DeepEqual(out.Labels, []string{label}) || len(out.StillEnabled) != 0 { - t.Errorf("DisableServices %s = %+v, want it stopped and nothing kept", label, out) - } - f.assertStopped(t, []string{label}) - } - f.assertEnabled(t, []string{"com.apple.cloudd"}, "com.apple.cloudd") -} - -// With --save, a live change that fails leaves the profile file untouched and -// says so. -func TestServicesSaveOnlyAfterTheLiveChange(t *testing.T) { - useTestCategories(t) - delays := launchdRetryDelays - launchdRetryDelays = []time.Duration{time.Millisecond} - t.Cleanup(func() { launchdRetryDelays = delays }) - labels := sortedLabels(SlimmableSet()) - f := newBatchFake(t, "iOS-26-5", labels, "") - f.slimmed(t, labels...) - if err := os.WriteFile(f.teardown, []byte("1000\n"), 0o644); err != nil { - t.Fatal(err) - } - path := filepath.Join(t.TempDir(), "ci.json") - - out, err := EnableServices(context.Background(), f.udid, []string{"media"}, path, nil) - if err == nil || !strings.Contains(err.Error(), "not changed") { - t.Errorf("EnableServices --save with a failing simulator = %v, want an error saying the profile was not changed", err) - } - if out.Saved != "" { - t.Errorf("EnableServices --save reported %q saved after a failure", out.Saved) - } - if _, err := os.Stat(path); !os.IsNotExist(err) { - t.Errorf("profile written after a failed live change: %v", err) - } - _, err = DisableServices(context.Background(), f.udid, []string{"media"}, path, nil) - if err == nil || !strings.Contains(err.Error(), "not changed") { - t.Errorf("DisableServices --save with a failing simulator = %v, want an error saying the profile was not changed", err) - } - if _, err := os.Stat(path); !os.IsNotExist(err) { - t.Errorf("profile written after a failed live change: %v", err) - } -} - -// Only launchd_sim's error 124 is retried; any other failure of a read is -// returned at once, as before. -func TestReadLaunchdRetriesOnlyTheTransientError(t *testing.T) { - f := newBatchFake(t, "iOS-26-5", nil, "") - t.Setenv("FAKE_SPAWN_ERROR", "1") - _, err := readDisabled(context.Background(), "default", f.udid) - if err == nil || !strings.Contains(err.Error(), "Invalid device state") { - t.Fatalf("readDisabled = %v, want the spawn error", err) - } - if calls := xcrunCalls(t, f.log); len(calls) != 1 { - t.Errorf("readDisabled spawned %d times on a non-transient error, want once: %v", len(calls), calls) - } -} - -// A read that runs out of time is retried: on a heavily loaded host one -// `launchctl list` can take longer than SpawnTimeout and the next one succeed. -func TestReadLaunchdRetriesATimedOutRead(t *testing.T) { - f := newBatchFake(t, "iOS-26-5", nil, "") - once := filepath.Join(t.TempDir(), "hang-once") - if err := os.WriteFile(once, nil, 0o644); err != nil { - t.Fatal(err) - } - t.Setenv("FAKE_HANG_ONCE", once) - savedTimeout, savedWait, savedDelays := SpawnTimeout, spawnWaitDelay, launchdRetryDelays - SpawnTimeout, spawnWaitDelay, launchdRetryDelays = 200*time.Millisecond, 100*time.Millisecond, []time.Duration{time.Millisecond} - t.Cleanup(func() { SpawnTimeout, spawnWaitDelay, launchdRetryDelays = savedTimeout, savedWait, savedDelays }) - - if _, err := readDisabled(context.Background(), "default", f.udid); err != nil { - t.Fatalf("readDisabled after one timed-out attempt = %v, want it retried", err) - } - if calls := xcrunCalls(t, f.log); len(calls) != 2 { - t.Errorf("readDisabled spawned %d times, want 2 (one timeout, one retry): %v", len(calls), calls) - } -} - -// A spawn that times out while a child process still holds its output pipe -// returns instead of waiting for that child forever, both for a read and for -// a per-label transition. -func TestLaunchdSpawnsDoNotHangOnAHeldPipe(t *testing.T) { - f := newBatchFake(t, "iOS-26-5", []string{"com.apple.cloudd"}, "") - t.Setenv("FAKE_HANG", "1") - savedTimeout, savedWait, savedDelays := SpawnTimeout, spawnWaitDelay, launchdRetryDelays - SpawnTimeout, spawnWaitDelay, launchdRetryDelays = 200*time.Millisecond, 100*time.Millisecond, []time.Duration{time.Millisecond} - t.Cleanup(func() { SpawnTimeout, spawnWaitDelay, launchdRetryDelays = savedTimeout, savedWait, savedDelays }) - - done := make(chan error, 2) - go func() { - _, err := readDisabled(context.Background(), "default", f.udid) - done <- err - }() - go func() { - done <- applyDelta(context.Background(), "default", f.udid, []string{"com.apple.cloudd"}, nil, liveDisable, nil) - }() - for range 2 { - select { - case err := <-done: - if err == nil { - t.Error("a hung spawn succeeded, want a timeout error") - } - case <-time.After(10 * time.Second): - t.Fatal("a hung spawn never returned") - } - } -} diff --git a/measure.go b/measure.go deleted file mode 100644 index 1ff4816..0000000 --- a/measure.go +++ /dev/null @@ -1,242 +0,0 @@ -package simslim - -import ( - "context" - "fmt" - "os/exec" - "regexp" - "sort" - "strconv" - "strings" -) - -// Measurement is a device's real memory cost. -type Measurement struct { - Processes int `json:"processes"` - Bytes int64 `json:"bytes"` // summed phys_footprint (compressed + dirty), the number that caps how many sims fit - CPU float64 `json:"cpu"` // summed %cpu across the tree (ps's decaying average; can exceed 100 on multicore) -} - -// Process is one process in a simulator's launchd tree, for the top drill-down. -type Process struct { - PID int `json:"pid"` - Command string `json:"command"` - Bytes int64 `json:"bytes"` - CPU float64 `json:"cpu"` -} - -// measure sums the phys_footprint of every process in the device's launchd tree. -// phys_footprint (the same value Activity Monitor's "Memory" column reports) -// counts compressed and swapped pages, so it stays accurate under memory -// pressure where resident size would read misleadingly low. -func Measure(ctx context.Context, udid string) (Measurement, error) { - root, err := simLaunchdPID(ctx, udid) - if err != nil { - return Measurement{}, err - } - snap, err := processSnapshot(ctx) - if err != nil { - return Measurement{}, err - } - footprint, err := footprintByPID(ctx) - if err != nil { - return Measurement{}, err - } - - return measureTree(root, snap, footprint), nil -} - -// MeasureProcesses returns every process in the device's launchd tree with its -// own footprint and cpu, sorted by memory descending — the top drill-down view. -func MeasureProcesses(ctx context.Context, udid string) ([]Process, error) { - root, err := simLaunchdPID(ctx, udid) - if err != nil { - return nil, err - } - snap, err := processSnapshot(ctx) - if err != nil { - return nil, err - } - footprint, err := footprintByPID(ctx) - if err != nil { - return nil, err - } - - procs := make([]Process, 0) - for pid := range treePIDs(root, snap.children) { - procs = append(procs, Process{PID: pid, Command: snap.comm[pid], Bytes: footprint[pid], CPU: snap.cpu[pid]}) - } - sort.Slice(procs, func(i, j int) bool { - if procs[i].Bytes != procs[j].Bytes { - return procs[i].Bytes > procs[j].Bytes - } - return procs[i].PID < procs[j].PID - }) - return procs, nil -} - -// measureMany takes one process and footprint snapshot for every requested -// simulator. This keeps the GUI's RAM column current without running the -// relatively expensive `top` command once per booted device. -func MeasureMany(ctx context.Context, udids []string) (map[string]Measurement, map[string]string) { - measurements := make(map[string]Measurement, len(udids)) - errorsByUDID := make(map[string]string) - roots := make(map[string]int, len(udids)) - for _, udid := range udids { - root, err := simLaunchdPID(ctx, udid) - if err != nil { - errorsByUDID[udid] = err.Error() - continue - } - roots[udid] = root - } - if len(roots) == 0 { - return measurements, errorsByUDID - } - - snap, err := processSnapshot(ctx) - if err != nil { - for udid := range roots { - errorsByUDID[udid] = err.Error() - } - return measurements, errorsByUDID - } - footprint, err := footprintByPID(ctx) - if err != nil { - for udid := range roots { - errorsByUDID[udid] = err.Error() - } - return measurements, errorsByUDID - } - - for udid, root := range roots { - measurements[udid] = measureTree(root, snap, footprint) - } - return measurements, errorsByUDID -} - -// treePIDs collects every pid reachable from root through the child map. -func treePIDs(root int, children map[int][]int) map[int]bool { - seen := map[int]bool{} - stack := []int{root} - for len(stack) > 0 { - pid := stack[len(stack)-1] - stack = stack[:len(stack)-1] - if seen[pid] { - continue - } - seen[pid] = true - stack = append(stack, children[pid]...) - } - return seen -} - -func measureTree(root int, snap psSnapshot, footprint map[int]int64) Measurement { - var m Measurement - for pid := range treePIDs(root, snap.children) { - m.Processes++ - m.Bytes += footprint[pid] - m.CPU += snap.cpu[pid] - } - return m -} - -func simLaunchdPID(ctx context.Context, udid string) (int, error) { - out, err := exec.CommandContext(ctx, "pgrep", "-f", udid+"/data/var/run/launchd_bootstrap").Output() - if err != nil { - return 0, fmt.Errorf("simulator %s does not appear to be booted", udid) - } - fields := strings.Fields(string(out)) - if len(fields) == 0 { - return 0, fmt.Errorf("simulator %s does not appear to be booted", udid) - } - return strconv.Atoi(fields[0]) -} - -// psSnapshot is one `ps` sweep of every process: parent links, cpu, and name. -type psSnapshot struct { - children map[int][]int - cpu map[int]float64 - comm map[int]string -} - -func processSnapshot(ctx context.Context) (psSnapshot, error) { - // comm is the full executable path (untruncated, unlike ucomm); we basename - // it so the drill-down shows real daemon names like backboardd or SpringBoard. - out, err := exec.CommandContext(ctx, "ps", "-axo", "pid,ppid,%cpu,comm").Output() - if err != nil { - return psSnapshot{}, err - } - return parsePS(string(out)), nil -} - -func parsePS(out string) psSnapshot { - snap := psSnapshot{children: map[int][]int{}, cpu: map[int]float64{}, comm: map[int]string{}} - for _, line := range strings.Split(out, "\n") { - f := strings.Fields(line) - if len(f) < 4 { - continue - } - pid, err1 := strconv.Atoi(f[0]) - ppid, err2 := strconv.Atoi(f[1]) - if err1 != nil || err2 != nil { - continue - } - snap.children[ppid] = append(snap.children[ppid], pid) - if cpu, err := strconv.ParseFloat(f[2], 64); err == nil { - snap.cpu[pid] = cpu - } - snap.comm[pid] = commName(strings.Join(f[3:], " ")) // join defends against spaces in the path - } - return snap -} - -// commName reduces a full executable path to its basename. -func commName(path string) string { - if i := strings.LastIndexByte(path, '/'); i >= 0 { - return path[i+1:] - } - return path -} - -var topMemLine = regexp.MustCompile(`^\s*(\d+)\s+([0-9.]+[KMGB+]?)`) - -func footprintByPID(ctx context.Context) (map[int]int64, error) { - out, err := exec.CommandContext(ctx, "top", "-l", "1", "-stats", "pid,mem").Output() - if err != nil { - return nil, err - } - mem := map[int]int64{} - for _, line := range strings.Split(string(out), "\n") { - g := topMemLine.FindStringSubmatch(line) - if g == nil { - continue - } - pid, _ := strconv.Atoi(g[1]) - mem[pid] = parseBytes(g[2]) - } - return mem, nil -} - -func parseBytes(s string) int64 { - s = strings.TrimSuffix(strings.TrimSpace(s), "+") - if s == "" { - return 0 - } - mult := int64(1) - switch s[len(s)-1] { - case 'K': - mult, s = 1<<10, s[:len(s)-1] - case 'M': - mult, s = 1<<20, s[:len(s)-1] - case 'G': - mult, s = 1<<30, s[:len(s)-1] - case 'B': - s = s[:len(s)-1] - } - v, err := strconv.ParseFloat(s, 64) - if err != nil { - return 0 - } - return int64(v * float64(mult)) -} diff --git a/measure_test.go b/measure_test.go deleted file mode 100644 index 0dd9e5c..0000000 --- a/measure_test.go +++ /dev/null @@ -1,65 +0,0 @@ -package simslim - -import "testing" - -func TestMeasureTree(t *testing.T) { - snap := psSnapshot{ - children: map[int][]int{ - 10: {11, 12}, - 11: {13}, - 13: {10}, // A cycle must not double-count the root. - }, - cpu: map[int]float64{10: 1.5, 11: 0.5, 12: 2, 13: 0}, - } - footprint := map[int]int64{10: 100, 11: 20, 12: 30, 13: 4} - - got := measureTree(10, snap, footprint) - if got.Processes != 4 { - t.Errorf("Processes = %d, want 4", got.Processes) - } - if got.Bytes != 154 { - t.Errorf("Bytes = %d, want 154", got.Bytes) - } - if got.CPU != 4 { - t.Errorf("CPU = %v, want 4", got.CPU) - } -} - -func TestParsePS(t *testing.T) { - out := " PID PPID %CPU COMM\n" + - " 10 1 1.5 launchd_sim\n" + - " 11 10 12.0 /usr/libexec/assistantd\n" + - " 12 10 0.0 /System/Library/CoreServices/SpringBoard.app/SpringBoard\n" + - " bad line that should be skipped\n" - - snap := parsePS(out) - if got := snap.children[10]; len(got) != 2 { - t.Fatalf("children[10] = %v, want 2 entries", got) - } - if snap.comm[11] != "assistantd" { // basenamed from the full path - t.Errorf("comm[11] = %q, want assistantd", snap.comm[11]) - } - if snap.comm[12] != "SpringBoard" { - t.Errorf("comm[12] = %q, want SpringBoard", snap.comm[12]) - } - if snap.cpu[11] != 12 { - t.Errorf("cpu[11] = %v, want 12", snap.cpu[11]) - } - if _, ok := snap.comm[1]; ok { - t.Errorf("header row was parsed as a process") - } -} - -func TestParseBytes(t *testing.T) { - tests := map[string]int64{ - "512B": 512, - "8K": 8 << 10, - "823M": 823 << 20, - "1.5G+": 3 << 29, - } - for input, want := range tests { - if got := parseBytes(input); got != want { - t.Errorf("parseBytes(%q) = %d, want %d", input, got, want) - } - } -} diff --git a/output.go b/output.go deleted file mode 100644 index 2ca2b1b..0000000 --- a/output.go +++ /dev/null @@ -1,95 +0,0 @@ -package simslim - -// DeviceSummary is the stable, machine-readable representation used by the -// macOS app and other integrations. managedDisabled is omitted for shutdown -// simulators because launchd state can only be read while a simulator is booted. -type DeviceSummary struct { - Device - ManagedDisabled *int `json:"managedDisabled,omitempty"` - ManagedTotal int `json:"managedTotal"` - StatusError string `json:"statusError,omitempty"` - Memory *Measurement `json:"memory,omitempty"` - MemoryError string `json:"memoryError,omitempty"` -} - -type StatusOutput struct { - Status - Verdict string `json:"verdict"` - Dropped []DroppedCategory `json:"dropped,omitempty"` // only when `status --dropped` is requested -} - -// ServicesOutput is returned by `enable` and `disable`: the managed daemons the -// command changed in the running boot session, and the profile file it saved. -type ServicesOutput struct { - Action string `json:"action"` // "enable" or "disable" - UDID string `json:"udid"` - Live bool `json:"live"` // false: the simulator is not booted, only the profile was saved - Labels []string `json:"labels"` // daemons enabled, or stopped by disable - NotStarted []string `json:"notStarted,omitempty"` // enable: re-enabled, but launchd starts them only at the next boot - StillEnabled []string `json:"stillEnabled,omitempty"` // disable: kept running for another fully enabled category or the platform - Saved string `json:"saved,omitempty"` // the profile file --save created or updated -} - -// DroppedCategory lists the managed launchd labels a category has disabled on a -// simulator, alongside the feature that stops working as a result. -type DroppedCategory struct { - ID string `json:"id"` - Name string `json:"name"` - Downside string `json:"downside"` - Labels []string `json:"labels"` -} - -// SimulatorMutationOutput is returned by simulator-management commands so the -// GUI can refresh and, for clone, select the newly created device. -type SimulatorMutationOutput struct { - Action string `json:"action"` - UDID string `json:"udid"` - Name string `json:"name,omitempty"` - SourceUDID string `json:"sourceUdid,omitempty"` -} - -// DoctorOutput reports whether each required feature survives the device's -// current slimming. OK is false when any required feature has a disabled daemon. -type DoctorOutput struct { - UDID string `json:"udid,omitempty"` - OK bool `json:"ok"` - Features []FeatureStatus `json:"features"` -} - -// FeatureStatus is one feature's verdict: the daemons it needs that are down. -type FeatureStatus struct { - ID string `json:"id"` - Name string `json:"name"` - OK bool `json:"ok"` - Disabled []string `json:"disabled,omitempty"` -} - -type DiskMeasurement struct { - Bytes int64 `json:"bytes"` -} - -// TopSim is one booted simulator's live resource snapshot for `simslim top`. -type TopSim struct { - Device - ManagedDisabled *int `json:"managedDisabled,omitempty"` - ManagedTotal int `json:"managedTotal"` - StatusError string `json:"statusError,omitempty"` - Memory *Measurement `json:"memory,omitempty"` - MemoryError string `json:"memoryError,omitempty"` - DiskBytes *int64 `json:"diskBytes,omitempty"` -} - -// TopOutput is the fleet view: every booted simulator plus the summed footprint -// that decides how many more fit. -type TopOutput struct { - Sims []TopSim `json:"sims"` - TotalBytes int64 `json:"totalBytes"` -} - -// TopProcesses is one simulator's per-daemon breakdown, the top drill-down. -type TopProcesses struct { - UDID string `json:"udid"` - Name string `json:"name,omitempty"` - Processes []Process `json:"processes"` - TotalBytes int64 `json:"totalBytes"` -} diff --git a/packaging/homebrew/simslim.rb.in b/packaging/homebrew/simslim.rb.in deleted file mode 100644 index cda4a3f..0000000 --- a/packaging/homebrew/simslim.rb.in +++ /dev/null @@ -1,21 +0,0 @@ -class Simslim < Formula - desc "Run more iOS, tvOS, watchOS, and visionOS simulators on one Mac by disabling unneeded background daemons" - homepage "https://github.com/mobai-app/simslim" - url "@SOURCE_URL@" - sha256 "@SOURCE_SHA256@" - license "MIT" - - depends_on "go" => :build - depends_on arch: :arm64 - depends_on :macos - - def install - # std_go_args passes no package path, so the CLI must be named explicitly: - # the repo root is the importable simslim library, not package main. - system "go", "build", *std_go_args(ldflags: "-X main.version=#{version}"), "./cmd/simslim" - end - - test do - assert_match version.to_s, shell_output("#{bin}/simslim --version") - end -end diff --git a/platform_test.go b/platform_test.go deleted file mode 100644 index 0932275..0000000 --- a/platform_test.go +++ /dev/null @@ -1,301 +0,0 @@ -package simslim - -import ( - "context" - "encoding/json" - "os" - "path/filepath" - "strings" - "testing" -) - -func TestParseRuntime(t *testing.T) { - for _, tt := range []struct{ runtime, platform, version string }{ - {"com.apple.CoreSimulator.SimRuntime.iOS-26-5", "iOS", "26.5"}, - {"com.apple.CoreSimulator.SimRuntime.tvOS-18-5", "tvOS", "18.5"}, - {"com.apple.CoreSimulator.SimRuntime.watchOS-11-5-1", "watchOS", "11.5.1"}, - {"com.apple.CoreSimulator.SimRuntime.watchOS-26-0", "watchOS", "26.0"}, - {"com.apple.CoreSimulator.SimRuntime.xrOS-26-0", "visionOS", "26.0"}, - {"com.apple.CoreSimulator.SimRuntime.xrOS-2-5", "visionOS", "2.5"}, - {"com.apple.CoreSimulator.SimRuntime.visionOS-26-0", "", "?"}, - {"com.apple.CoreSimulator.SimRuntime.not-iOS-26-0", "", "?"}, - {"com.apple.CoreSimulator.SimRuntime.iOS-", "", "?"}, - {"iOS-26-5", "", "?"}, - {"", "", "?"}, - } { - t.Run(tt.runtime, func(t *testing.T) { - platform, version := parseRuntime(tt.runtime) - if platform != tt.platform || version != tt.version { - t.Fatalf("parseRuntime(%q) = (%q, %q), want (%q, %q)", tt.runtime, platform, version, tt.platform, tt.version) - } - }) - } -} - -func TestListAndFindDevicesAcrossPlatformsAndSets(t *testing.T) { - ResetDeviceSets() - t.Cleanup(ResetDeviceSets) - RegisterDeviceSet("/custom/devices") - dir := t.TempDir() - script := `#!/bin/sh -case "$*" in - "simctl list devices -j") - printf '%s\n' '{"devices":{ - "com.apple.CoreSimulator.SimRuntime.iOS-26-5":[{"udid":"PHONE","name":"Phone","state":"Shutdown","isAvailable":true}], - "com.apple.CoreSimulator.SimRuntime.tvOS-26-0":[{"udid":"TV","name":"Living room","state":"Booted","isAvailable":true,"dataPath":"/tmp/tv/data"},{"udid":"UNAVAILABLE","isAvailable":false}], - "com.apple.CoreSimulator.SimRuntime.xrOS-26-0":[{"udid":"VISION","isAvailable":true}] - }}' ;; - "simctl --set testing list devices -j") - printf '%s\n' '{"devices":{"com.apple.CoreSimulator.SimRuntime.watchOS-11-5":[{"udid":"WATCH","name":"Renamed device","state":"Booted","isAvailable":true,"dataPath":"/tmp/watch/data"}]}}' ;; - "simctl --set /custom/devices list devices -j") - printf '%s\n' '{"devices":{"com.apple.CoreSimulator.SimRuntime.tvOS-18-5":[{"udid":"CUSTOM","name":"Custom TV","state":"Shutdown","isAvailable":true}]}}' ;; - *) exit 99 ;; -esac -` - if err := os.WriteFile(filepath.Join(dir, "xcrun"), []byte(script), 0o755); err != nil { - t.Fatal(err) - } - t.Setenv("PATH", dir+string(os.PathListSeparator)+os.Getenv("PATH")) - devices, err := ListDevices(context.Background()) - if err != nil || len(devices) != 5 { - t.Fatalf("ListDevices = (%v, %v), want 5 supported, available devices", devices, err) - } - want := map[string]Device{ - "PHONE": {Platform: "iOS", OSVersion: "26.5", Set: "default"}, - "VISION": {Platform: "visionOS", OSVersion: "26.0", Set: "default"}, - "TV": {Platform: "tvOS", OSVersion: "26.0", Set: "default", DataPath: "/tmp/tv/data"}, - "WATCH": {Platform: "watchOS", OSVersion: "11.5", Set: "testing", DataPath: "/tmp/watch/data"}, - "CUSTOM": {Platform: "tvOS", OSVersion: "18.5", Set: "/custom/devices"}, - } - for _, d := range devices { - w, ok := want[d.UDID] - if !ok || d.Platform != w.Platform || d.OSVersion != w.OSVersion || d.Set != w.Set || d.DataPath != w.DataPath { - t.Errorf("unexpected device: %+v", d) - } - found, err := FindDevice(context.Background(), d.UDID, d.Set) - if err != nil || found != d { - t.Errorf("FindDevice(%q, %q) = (%+v, %v), want %+v", d.UDID, d.Set, found, err, d) - } - encoded, err := json.Marshal(DeviceSummary{Device: d}) - if err != nil || !strings.Contains(string(encoded), `"platform":"`+w.Platform+`"`) { - t.Errorf("device summary lost platform: %s (%v)", encoded, err) - } - } -} - -func TestDeviceSupportsPersistentOverrides(t *testing.T) { - for _, tt := range []struct { - platform, version string - want bool - }{ - {"", "18.5", true}, // backward-compatible Device literals - {"iOS", "18.4", false}, {"iOS", "18.5", true}, - {"tvOS", "18.4", false}, {"tvOS", "18.5", true}, - {"watchOS", "10.5", false}, {"watchOS", "11.4", false}, - {"watchOS", "11.5", true}, {"watchOS", "11.5.1", true}, - {"watchOS", "26.0", true}, {"tvOS", "26.0", true}, - {"watchOS", "?", false}, {"watchOS", "11", false}, - {"watchOS", "26.-1", false}, {"xrOS", "26.0", false}, - {"visionOS", "2.4", false}, {"visionOS", "2.5", true}, - {"visionOS", "26.0", true}, {"visionOS", "27.0", true}, - } { - d := Device{Platform: tt.platform, OSVersion: tt.version} - t.Run(d.RuntimeName(), func(t *testing.T) { - if got := d.SupportsPersistentOverrides(); got != tt.want { - t.Errorf("SupportsPersistentOverrides = %t, want %t", got, tt.want) - } - }) - } -} - -func TestSlimAndRestoreAppleTVAndWatch(t *testing.T) { - for _, runtime := range []string{"tvOS-18-5", "watchOS-11-5", "tvOS-26-0", "watchOS-26-5", "xrOS-2-5", "xrOS-27-0"} { - t.Run(runtime, func(t *testing.T) { - const udid = "00000000-0000-0000-0000-0000000000F1" - useTempStoreRoot(t) - fakeSimctl(t, udid, runtime, "Shutdown") - ctx := context.Background() - changed, err := EnableSlim(ctx, "default", udid, Profile{}, nil) - if err != nil || !changed { - t.Fatalf("EnableSlim = (%t, %v)", changed, err) - } - st, _, err := ReadStatus(ctx, udid) - if err != nil || !st.Persistent || st.ManagedDisabled != st.ManagedTotal { - t.Fatalf("ReadStatus = (%+v, %v), want persistent full slim", st, err) - } - changed, err = EnableSlim(ctx, "default", udid, Profile{}, nil) - if err != nil || changed { - t.Fatalf("second EnableSlim = (%t, %v), want idempotent", changed, err) - } - if _, err := DisableSlim(ctx, "default", udid, nil); err != nil { - t.Fatal(err) - } - st, _, err = ReadStatus(ctx, udid) - if err != nil || st.ManagedDisabled != 0 { - t.Fatalf("status after off = (%+v, %v), want stock", st, err) - } - }) - } -} - -func TestOlderAppleTVAndWatchRequireNoReboot(t *testing.T) { - for _, runtime := range []string{"tvOS-18-3", "watchOS-10-5", "watchOS-11-4"} { - t.Run(runtime, func(t *testing.T) { - const udid = "00000000-0000-0000-0000-0000000000F2" - useTempStoreRoot(t) - logPath := fakeSimctl(t, udid, runtime, "Shutdown") - ctx := context.Background() - changed, err := EnableSlim(ctx, "default", udid, Profile{}, nil) - platform, version := parseRuntime("com.apple.CoreSimulator.SimRuntime." + runtime) - if err == nil || changed || !strings.Contains(err.Error(), platform+" "+version) || !strings.Contains(err.Error(), "--no-reboot") { - t.Fatalf("EnableSlim = (%t, %v), want platform-specific rejection", changed, err) - } - if calls := xcrunCalls(t, logPath); len(calls) != 1 || calls[0] != "simctl list devices -j" { - t.Fatalf("rejected device was mutated: %v", calls) - } - changed, err = EnableSlimNoReboot(ctx, "default", udid, Profile{}, nil) - if err != nil || !changed { - t.Fatalf("EnableSlimNoReboot = (%t, %v)", changed, err) - } - if calls := strings.Join(xcrunCalls(t, logPath), "\n"); strings.Contains(calls, "simctl shutdown") { - t.Fatal("no-reboot slimming shut the device down") - } - st, _, err := ReadStatus(ctx, udid) - if err != nil || st.Persistent || st.ManagedDisabled != st.ManagedTotal { - t.Fatalf("ReadStatus = (%+v, %v), want session-only full slim", st, err) - } - if _, err := DisableSlim(ctx, "default", udid, nil); err != nil { - t.Fatalf("DisableSlim must still work on older runtimes: %v", err) - } - }) - } -} - -func TestNewPlatformsRejectLostOverrides(t *testing.T) { - for _, runtime := range []string{"tvOS-26-0", "watchOS-26-5"} { - t.Run(runtime, func(t *testing.T) { - const udid = "00000000-0000-0000-0000-0000000000F3" - useTempStoreRoot(t) - logPath := fakeSimctl(t, udid, runtime, "Shutdown") - t.Setenv("SIMSLIM_TEST_IGNORE_STORE", "1") - // Model a runtime that accepts disables but forgets them on reboot. - xcrunPath := filepath.Join(filepath.Dir(logPath), "xcrun") - script := strings.Replace(fakeXcrunScript, "printf Shutdown", "rm -f \"$SIMSLIM_TEST_LIVE\"/*\n printf Shutdown", 1) - if err := os.WriteFile(xcrunPath, []byte(script), 0o755); err != nil { - t.Fatal(err) - } - labels := twoSlimmableLabels(t) - _, err := ensure(context.Background(), "default", udid, map[string]bool{labels[0]: true}, nil) - if err == nil || !strings.Contains(err.Error(), "did not survive the reboot") { - t.Fatalf("ensure = %v, want persistence verification failure", err) - } - }) - } -} - -func TestRepairCloneRejectsDifferentPlatformsAtSameVersion(t *testing.T) { - useTempStoreRoot(t) - logPath := fakeSimctl(t, testSourceUDID, "iOS-26-5", "Shutdown") - dir := t.TempDir() - devices := map[string]any{"devices": map[string]any{ - "com.apple.CoreSimulator.SimRuntime.iOS-26-5": []map[string]any{ - {"udid": testSourceUDID, "state": "Booted", "isAvailable": true, "dataPath": dir}, - }, - "com.apple.CoreSimulator.SimRuntime.watchOS-26-5": []map[string]any{ - {"udid": testCloneUDID, "state": "Booted", "isAvailable": true, "dataPath": dir}, - }, - }} - encoded, err := json.Marshal(devices) - if err != nil { - t.Fatal(err) - } - t.Setenv("SIMSLIM_TEST_DEVICES", string(encoded)) - err = RepairClonedDevice(context.Background(), testSourceUDID, testCloneUDID) - if err == nil || !strings.Contains(err.Error(), "source and clone runtimes differ (iOS 26.5 and watchOS 26.5)") { - t.Fatalf("RepairClonedDevice = %v, want platform mismatch", err) - } - for _, call := range xcrunCalls(t, logPath) { - if call != "simctl list devices -j" { - t.Errorf("cross-platform repair mutated a simulator: %s", call) - } - } -} - -func TestWatchProfileKeepsHomedEnabled(t *testing.T) { - p := Profile{Keep: map[string]bool{"com.apple.apsd": true}} - watch := Device{Platform: "watchOS", OSVersion: "26.5"} - for _, platform := range []string{"iOS", "tvOS", ""} { - if !p.DesiredForDevice(Device{Platform: platform})["com.apple.homed"] { - t.Errorf("homed unexpectedly excluded on %q", platform) - } - } - if desired := p.DesiredForDevice(watch); desired["com.apple.homed"] || desired["com.apple.apsd"] { - t.Fatalf("Watch profile disabled a required or kept label: %v", desired) - } - const udid = "00000000-0000-0000-0000-0000000000F4" - useTempStoreRoot(t) - logPath := fakeSimctl(t, udid, "watchOS-26-5", "Shutdown") - if err := writeDisabledStore(udid, []string{"com.apple.homed"}, nil); err != nil { - t.Fatal(err) - } - ctx := context.Background() - if _, err := EnableSlim(ctx, "default", udid, p, nil); err != nil { - t.Fatal(err) - } - st, disabled, err := ReadStatus(ctx, udid) - if err != nil || disabled["com.apple.homed"] || st.ManagedTotal != len(SlimmableSet())-1 || st.ManagedDisabled != st.ManagedTotal-1 { - t.Fatalf("Watch status = (%+v, %v), homed disabled = %t", st, err, disabled["com.apple.homed"]) - } - verified, err := VerifyProfile(ctx, udid, p) - if err != nil || !verified.OK { - t.Fatalf("Watch profile verification = (%+v, %v)", verified, err) - } - if _, err := EnableSlimNoReboot(ctx, "default", udid, p, nil); err != nil { - t.Fatal(err) - } - for _, call := range xcrunCalls(t, logPath) { - if strings.Contains(call, "launchctl disable system/com.apple.homed") || strings.Contains(call, "launchctl bootout system/com.apple.homed") { - t.Fatalf("Watch slimming tried to disable required service: %s", call) - } - } -} - -func TestVisionProfileKeepsMobileAssetsEnabled(t *testing.T) { - const label = "com.apple.mobileassetd" - vision := Device{Platform: "visionOS", OSVersion: "27.0"} - for _, platform := range []string{"iOS", "tvOS", "watchOS", ""} { - if !(Profile{}).DesiredForDevice(Device{Platform: platform})[label] { - t.Errorf("mobileassetd unexpectedly excluded on %q", platform) - } - } - if (Profile{}).DesiredForDevice(vision)[label] { - t.Fatal("Vision profile disables mobileassetd, which serves the surroundings") - } - // A device slimmed before this exception existed gets mobileassetd back. - const udid = "00000000-0000-0000-0000-0000000000F5" - useTempStoreRoot(t) - logPath := fakeSimctl(t, udid, "xrOS-27-0", "Shutdown") - if err := writeDisabledStore(udid, []string{label}, nil); err != nil { - t.Fatal(err) - } - ctx := context.Background() - if _, err := EnableSlim(ctx, "default", udid, Profile{}, nil); err != nil { - t.Fatal(err) - } - st, disabled, err := ReadStatus(ctx, udid) - if err != nil || disabled[label] || st.ManagedTotal != len(SlimmableSet())-1 || st.ManagedDisabled != st.ManagedTotal { - t.Fatalf("Vision status = (%+v, %v), mobileassetd disabled = %t", st, err, disabled[label]) - } - verified, err := VerifyProfile(ctx, udid, Profile{}) - if err != nil || !verified.OK { - t.Fatalf("Vision profile verification = (%+v, %v)", verified, err) - } - if _, err := EnableSlimNoReboot(ctx, "default", udid, Profile{}, nil); err != nil { - t.Fatal(err) - } - for _, call := range xcrunCalls(t, logPath) { - if strings.Contains(call, "launchctl disable system/"+label) || strings.Contains(call, "launchctl bootout system/"+label) { - t.Fatalf("Vision slimming tried to disable mobileassetd: %s", call) - } - } -} diff --git a/profile_file.go b/profile_file.go deleted file mode 100644 index 49d6f14..0000000 --- a/profile_file.go +++ /dev/null @@ -1,143 +0,0 @@ -package simslim - -import ( - "bytes" - "encoding/json" - "errors" - "fmt" - "io" - "os" - "strings" -) - -// SlimProfile is the on-disk profile applied with `simslim on --profile `. -// Except and Keep mirror the `--except` and `--keep` flags. -type SlimProfile struct { - Name string `json:"name,omitempty"` - Description string `json:"description,omitempty"` - Except []string `json:"except,omitempty"` - Keep []string `json:"keep,omitempty"` -} - -// loadSlimProfile reads a profile file and resolves it to a validated Profile. -func LoadSlimProfile(path string) (Profile, error) { - data, err := os.ReadFile(path) - if err != nil { - return Profile{}, fmt.Errorf("read profile %s: %w", path, err) - } - dec := json.NewDecoder(bytes.NewReader(data)) - dec.DisallowUnknownFields() - var sp SlimProfile - if err := dec.Decode(&sp); err != nil { - return Profile{}, parseProfileError(path, err) - } - return sp.resolve(path) -} - -// parseProfileError explains a profile file that does not decode; an empty -// file would otherwise only say "EOF". -func parseProfileError(path string, err error) error { - if errors.Is(err, io.EOF) { - return fmt.Errorf("profile %s is empty; write {} for the default profile", path) - } - return fmt.Errorf("parse profile %s: %w", path, err) -} - -// resolve turns a parsed SlimProfile into the validated Profile it selects. -func (sp SlimProfile) resolve(path string) (Profile, error) { - p := Profile{ExceptCategories: map[string]bool{}, Keep: map[string]bool{}} - for _, id := range sp.Except { - if id = strings.TrimSpace(id); id == "" { - continue - } - if _, ok := CategoryByID(id); !ok { - return Profile{}, fmt.Errorf("profile %s: unknown category %q (see `simslim profiles`)", path, id) - } - p.ExceptCategories[id] = true - } - // Accept keep entries for required services too: profiles written as - // workarounds before a service became AlwaysEnabled must remain valid. - managed := managedSet() - for _, label := range sp.Keep { - if label = strings.TrimSpace(label); label == "" { - continue - } - if !managed[label] { - return Profile{}, fmt.Errorf("profile %s: %q is not a managed daemon (see `simslim profiles`)", path, label) - } - p.Keep[label] = true - } - return p, nil -} - -// SplitList parses the comma-separated list syntax shared by the --except, -// --keep, --requires and --categories flags, dropping blank entries. -func SplitList(s string) []string { - var out []string - for _, p := range strings.Split(s, ",") { - if p = strings.TrimSpace(p); p != "" { - out = append(out, p) - } - } - return out -} - -// buildProfile selects the slim profile for an `on` invocation. A --profile -// file is the single source of truth, so it cannot be combined with -// --except/--keep. -func BuildProfile(profilePath, except, keep string) (Profile, error) { - if profilePath != "" { - if except != "" || keep != "" { - return Profile{}, fmt.Errorf("--profile cannot be combined with --except or --keep") - } - return LoadSlimProfile(profilePath) - } - p := Profile{ExceptCategories: map[string]bool{}, Keep: map[string]bool{}} - for _, id := range SplitList(except) { - if _, ok := CategoryByID(id); !ok { - return Profile{}, fmt.Errorf("unknown category %q (see `simslim profiles`)", id) - } - p.ExceptCategories[id] = true - } - for _, l := range SplitList(keep) { - p.Keep[l] = true - } - return p, nil -} - -// marshalProfile renders a profile as indented JSON with a trailing newline. -func MarshalProfile(sp SlimProfile) ([]byte, error) { - data, err := json.MarshalIndent(sp, "", " ") - if err != nil { - return nil, err - } - return append(data, '\n'), nil -} - -// profileFileName derives a JSON filename from a profile name, for when the -// command targets a directory. Non-filename runs collapse to a hyphen; an empty -// name falls back to profile.json. -func ProfileFileName(name string) string { - var b strings.Builder - prevDash := false - for _, r := range strings.ToLower(strings.TrimSpace(name)) { - switch { - case r >= 'a' && r <= 'z', r >= '0' && r <= '9', r == '_', r == '.': - b.WriteRune(r) - prevDash = false - default: - if !prevDash { - b.WriteByte('-') - prevDash = true - } - } - } - slug := strings.Trim(b.String(), "-.") - if slug == "" { - return "profile.json" - } - if strings.HasSuffix(slug, ".json") { - return slug - } - return slug + ".json" -} diff --git a/profile_file_test.go b/profile_file_test.go deleted file mode 100644 index 8cfcd00..0000000 --- a/profile_file_test.go +++ /dev/null @@ -1,145 +0,0 @@ -package simslim - -import ( - "os" - "path/filepath" - "reflect" - "testing" -) - -// writeProfile writes contents to a temp file and returns its path. -func writeProfile(t *testing.T, contents string) string { - t.Helper() - path := filepath.Join(t.TempDir(), "profile.json") - if err := os.WriteFile(path, []byte(contents), 0o600); err != nil { - t.Fatalf("write profile: %v", err) - } - return path -} - -func TestLoadSlimProfile(t *testing.T) { - path := writeProfile(t, `{ - "name": "ci", - "description": "UI test runs", - "except": ["search", "store"], - "keep": ["com.apple.apsd"] - }`) - p, err := LoadSlimProfile(path) - if err != nil { - t.Fatalf("LoadSlimProfile() error = %v", err) - } - wantExcept := map[string]bool{"search": true, "store": true} - if !reflect.DeepEqual(p.ExceptCategories, wantExcept) { - t.Errorf("ExceptCategories = %v, want %v", p.ExceptCategories, wantExcept) - } - wantKeep := map[string]bool{"com.apple.apsd": true} - if !reflect.DeepEqual(p.Keep, wantKeep) { - t.Errorf("Keep = %v, want %v", p.Keep, wantKeep) - } -} - -func TestLoadSlimProfileMinimal(t *testing.T) { - // name/description are optional and empty arrays yield an empty selection. - p, err := LoadSlimProfile(writeProfile(t, `{}`)) - if err != nil { - t.Fatalf("LoadSlimProfile() error = %v", err) - } - if len(p.ExceptCategories) != 0 || len(p.Keep) != 0 { - t.Errorf("empty profile selected %v / %v, want empty", p.ExceptCategories, p.Keep) - } -} - -func TestLoadSlimProfileKeepsRequiredEnabledLabels(t *testing.T) { - // Keep existing workaround profiles valid after a service becomes required. - p, err := LoadSlimProfile(writeProfile(t, `{"keep": ["com.apple.gamed", "com.apple.sharingd"]}`)) - if err != nil { - t.Fatalf("LoadSlimProfile() error = %v", err) - } - for _, label := range []string{"com.apple.gamed", "com.apple.sharingd"} { - if !p.Keep[label] || p.Desired()[label] { - t.Errorf("profile must keep required service %q enabled", label) - } - } -} - -func TestLoadSlimProfileRejects(t *testing.T) { - tests := []struct { - name string - contents string - }{ - {name: "unknown category", contents: `{"except": ["nope"]}`}, - {name: "unknown keep label", contents: `{"keep": ["com.apple.does-not-exist"]}`}, - {name: "unknown field", contents: `{"disable": ["search"]}`}, - {name: "malformed json", contents: `{"except": [`}, - } - for _, tt := range tests { - t.Run(tt.name, func(t *testing.T) { - if _, err := LoadSlimProfile(writeProfile(t, tt.contents)); err == nil { - t.Errorf("LoadSlimProfile(%q) error = nil, want error", tt.contents) - } - }) - } -} - -func TestLoadSlimProfileMissingFile(t *testing.T) { - if _, err := LoadSlimProfile(filepath.Join(t.TempDir(), "absent.json")); err == nil { - t.Error("LoadSlimProfile(absent) error = nil, want error") - } -} - -func TestBuildProfile(t *testing.T) { - t.Run("flags build the profile", func(t *testing.T) { - p, err := BuildProfile("", "search", "com.apple.apsd") - if err != nil { - t.Fatalf("BuildProfile() error = %v", err) - } - if !p.ExceptCategories["search"] || !p.Keep["com.apple.apsd"] { - t.Errorf("buildProfile flags = %v / %v", p.ExceptCategories, p.Keep) - } - }) - t.Run("unknown category flag errors", func(t *testing.T) { - if _, err := BuildProfile("", "nope", ""); err == nil { - t.Error("BuildProfile(unknown category) error = nil, want error") - } - }) - t.Run("profile file resolves", func(t *testing.T) { - path := writeProfile(t, `{"except": ["search"]}`) - p, err := BuildProfile(path, "", "") - if err != nil { - t.Fatalf("BuildProfile(file) error = %v", err) - } - if !p.ExceptCategories["search"] { - t.Errorf("BuildProfile(file) except = %v", p.ExceptCategories) - } - }) - t.Run("profile with except flag errors", func(t *testing.T) { - if _, err := BuildProfile("some.json", "search", ""); err == nil { - t.Error("BuildProfile(profile+except) error = nil, want error") - } - }) - t.Run("profile with keep flag errors", func(t *testing.T) { - if _, err := BuildProfile("some.json", "", "com.apple.apsd"); err == nil { - t.Error("BuildProfile(profile+keep) error = nil, want error") - } - }) -} - -func TestProfileFileName(t *testing.T) { - tests := []struct { - name string - want string - }{ - {name: "ci", want: "ci.json"}, - {name: "UI Test Runs", want: "ui-test-runs.json"}, - {name: "", want: "profile.json"}, - {name: " ", want: "profile.json"}, - {name: "prod.json", want: "prod.json"}, - {name: "a/b:c", want: "a-b-c.json"}, - {name: "--weird--", want: "weird.json"}, - } - for _, tt := range tests { - if got := ProfileFileName(tt.name); got != tt.want { - t.Errorf("ProfileFileName(%q) = %q, want %q", tt.name, got, tt.want) - } - } -} diff --git a/profile_save.go b/profile_save.go deleted file mode 100644 index 25be27c..0000000 --- a/profile_save.go +++ /dev/null @@ -1,129 +0,0 @@ -package simslim - -import ( - "bytes" - "encoding/json" - "errors" - "fmt" - "io/fs" - "os" - "path/filepath" - "slices" -) - -// SaveServices records an `enable` or `disable` in a profile file, the one -// place that describes a slim simulator, so `on`, `watch`, and `verify` with -// that profile agree with it. Enabling adds each category to "except" and each -// daemon to "keep"; disabling removes them. Entries keep their order, new ones -// go at the end, and nothing is listed twice: a daemon an excepted category -// already keeps is not added to "keep". A missing file starts from the default -// profile, the one `on` applies without --profile. An unchanged profile is not -// rewritten; a changed one is replaced atomically. -func SaveServices(path string, categories, labels []string, enable bool) error { - data, changed, err := updatedProfile(path, categories, labels, enable) - if err != nil || !changed { - return err - } - return writeFileAtomic(path, data) -} - -// updatedProfile reads the profile at path and returns it with the change -// applied, and whether that changed anything. It writes nothing. -func updatedProfile(path string, categories, labels []string, enable bool) (data []byte, changed bool, err error) { - sp, exists, err := readSlimProfile(path) - if err != nil { - return nil, false, err - } - before := slices.Clone(sp.Except) - beforeKeep := slices.Clone(sp.Keep) - if enable { - for _, id := range categories { - if !slices.Contains(sp.Except, id) { - sp.Except = append(sp.Except, id) - } - } - excepted := coveredLabels(sp.Except, nil) - for _, l := range labels { - if !excepted[l] && !slices.Contains(sp.Keep, l) { - sp.Keep = append(sp.Keep, l) - } - } - } else { - sp.Except = slices.DeleteFunc(sp.Except, func(id string) bool { return slices.Contains(categories, id) }) - sp.Keep = slices.DeleteFunc(sp.Keep, func(l string) bool { return slices.Contains(labels, l) }) - // Removing a daemon from "keep" is not enough while a category the - // profile still excepts lists it. - for _, l := range labels { - for _, id := range sp.Except { - if coveredLabels([]string{id}, nil)[l] { - return nil, false, fmt.Errorf("profile %s keeps %s enabled through category %q; disable that category instead, or edit the file", path, l, id) - } - } - } - } - if exists && slices.Equal(before, sp.Except) && slices.Equal(beforeKeep, sp.Keep) { - return nil, false, nil - } - data, err = MarshalProfile(sp) - if err != nil { - return nil, false, err - } - return data, true, nil -} - -// readSlimProfile reads and validates a profile file, keeping its entries as -// written. A missing file is the default profile. -func readSlimProfile(path string) (sp SlimProfile, exists bool, err error) { - data, err := os.ReadFile(path) - if errors.Is(err, fs.ErrNotExist) { - return SlimProfile{}, false, nil - } - if err != nil { - return SlimProfile{}, false, fmt.Errorf("read profile %s: %w", path, err) - } - dec := json.NewDecoder(bytes.NewReader(data)) - dec.DisallowUnknownFields() - if err := dec.Decode(&sp); err != nil { - return SlimProfile{}, false, parseProfileError(path, err) - } - if _, err := sp.resolve(path); err != nil { - return SlimProfile{}, false, err - } - return sp, true, nil -} - -// writeFileAtomic replaces path with data through a temporary file in the same -// directory, so a concurrent reader sees the old file or the new one, never -// half of it. A symlink is followed, and an existing file keeps its mode. -func writeFileAtomic(path string, data []byte) error { - mode := fs.FileMode(0o644) - if resolved, err := filepath.EvalSymlinks(path); err == nil { - path = resolved - if info, err := os.Stat(path); err == nil { - mode = info.Mode().Perm() - } - } - temp, err := os.CreateTemp(filepath.Dir(path), "."+filepath.Base(path)+".*") - if err != nil { - return fmt.Errorf("write profile %s: %w", path, err) - } - defer os.Remove(temp.Name()) - if _, err := temp.Write(data); err != nil { - temp.Close() - return fmt.Errorf("write profile %s: %w", path, err) - } - if err := temp.Sync(); err != nil { - temp.Close() - return fmt.Errorf("write profile %s: %w", path, err) - } - if err := temp.Close(); err != nil { - return fmt.Errorf("write profile %s: %w", path, err) - } - if err := os.Chmod(temp.Name(), mode); err != nil { - return fmt.Errorf("write profile %s: %w", path, err) - } - if err := os.Rename(temp.Name(), path); err != nil { - return fmt.Errorf("write profile %s: %w", path, err) - } - return nil -} diff --git a/profile_save_test.go b/profile_save_test.go deleted file mode 100644 index 652c9b3..0000000 --- a/profile_save_test.go +++ /dev/null @@ -1,154 +0,0 @@ -package simslim - -import ( - "os" - "path/filepath" - "strings" - "testing" -) - -// assertProfileFile compares a saved profile byte for byte. -func assertProfileFile(t *testing.T, path, want string) { - t.Helper() - data, err := os.ReadFile(path) - if err != nil { - t.Fatalf("read %s: %v", path, err) - } - if string(data) != want { - t.Errorf("%s =\n%s\nwant\n%s", filepath.Base(path), data, want) - } -} - -// A missing file starts from the default profile, the one `on` applies -// without --profile, which excepts and keeps nothing. -func TestSaveServicesCreatesTheProfile(t *testing.T) { - useTestCategories(t) - path := filepath.Join(t.TempDir(), "dev.json") - if err := SaveServices(path, []string{"cloud"}, []string{"com.apple.mediad"}, true); err != nil { - t.Fatalf("SaveServices: %v", err) - } - assertProfileFile(t, path, "{\n \"except\": [\n \"cloud\"\n ],\n \"keep\": [\n \"com.apple.mediad\"\n ]\n}\n") - info, err := os.Stat(path) - if err != nil || info.Mode().Perm() != 0o644 { - t.Errorf("profile mode = %v (%v), want 0644", info.Mode().Perm(), err) - } - if entries, _ := os.ReadDir(filepath.Dir(path)); len(entries) != 1 { - t.Errorf("directory holds %d entries, want only the profile (no temporary file left)", len(entries)) - } - - path = filepath.Join(t.TempDir(), "empty.json") - if err := SaveServices(path, []string{"cloud"}, nil, false); err != nil { - t.Fatalf("SaveServices disable on a missing file: %v", err) - } - assertProfileFile(t, path, "{}\n") -} - -// Adding keeps the existing entries, their order, and the other fields; new -// entries go at the end, and nothing is listed twice. -func TestSaveServicesAddsWithoutDuplicates(t *testing.T) { - useTestCategories(t) - path := filepath.Join(t.TempDir(), "ci.json") - if err := os.WriteFile(path, []byte(`{"name":"ci","description":"CI runs","except":["media"],"keep":["com.apple.xpc"]}`), 0o600); err != nil { - t.Fatal(err) - } - // media is already excepted, com.apple.shared already kept by media, and - // com.apple.xpc already in keep: only com.apple.lazy is new. - if err := SaveServices(path, []string{"media"}, []string{"com.apple.shared", "com.apple.xpc", "com.apple.lazy"}, true); err != nil { - t.Fatalf("SaveServices: %v", err) - } - if err := SaveServices(path, []string{"cloud"}, nil, true); err != nil { - t.Fatalf("SaveServices: %v", err) - } - want := `{ - "name": "ci", - "description": "CI runs", - "except": [ - "media", - "cloud" - ], - "keep": [ - "com.apple.xpc", - "com.apple.lazy" - ] -} -` - assertProfileFile(t, path, want) - if info, _ := os.Stat(path); info.Mode().Perm() != 0o600 { - t.Errorf("profile mode = %v, want the original 0600", info.Mode().Perm()) - } - if _, err := LoadSlimProfile(path); err != nil { - t.Errorf("saved profile does not load: %v", err) - } -} - -// Removing drops only what is named and keeps the rest in order. -func TestSaveServicesRemoves(t *testing.T) { - useTestCategories(t) - path := filepath.Join(t.TempDir(), "dev.json") - if err := os.WriteFile(path, []byte(`{"except":["media","cloud"],"keep":["com.apple.mediad","com.apple.xpc"]}`), 0o644); err != nil { - t.Fatal(err) - } - if err := SaveServices(path, []string{"media"}, []string{"com.apple.mediad"}, false); err != nil { - t.Fatalf("SaveServices: %v", err) - } - assertProfileFile(t, path, "{\n \"except\": [\n \"cloud\"\n ],\n \"keep\": [\n \"com.apple.xpc\"\n ]\n}\n") - - // A daemon a still-excepted category keeps cannot be removed through keep. - err := SaveServices(path, nil, []string{"com.apple.cloudd"}, false) - if err == nil || !strings.Contains(err.Error(), `through category "cloud"`) { - t.Errorf("removing a daemon cloud keeps = %v, want an error naming cloud", err) - } -} - -// Saving the same change twice leaves the file untouched the second time. -func TestSaveServicesIsIdempotent(t *testing.T) { - useTestCategories(t) - path := filepath.Join(t.TempDir(), "dev.json") - const original = `{"except": ["cloud"]}` // hand-formatted: a rewrite would reformat it - if err := os.WriteFile(path, []byte(original), 0o644); err != nil { - t.Fatal(err) - } - for _, enable := range []bool{true, true} { - if err := SaveServices(path, []string{"cloud"}, []string{"com.apple.lazy"}, enable); err != nil { - t.Fatalf("SaveServices: %v", err) - } - } - assertProfileFile(t, path, original) - if err := SaveServices(path, []string{"media"}, nil, false); err != nil { - t.Fatalf("SaveServices: %v", err) - } - assertProfileFile(t, path, original) -} - -// A profile that would not load is refused, not rewritten. -func TestSaveServicesRejectsAnInvalidProfile(t *testing.T) { - useTestCategories(t) - for name, contents := range map[string]string{ - "unknown field": `{"exceptt": ["cloud"]}`, - "unknown category": `{"except": ["nope"]}`, - "not JSON": `{"except": [`, - } { - path := filepath.Join(t.TempDir(), "bad.json") - if err := os.WriteFile(path, []byte(contents), 0o644); err != nil { - t.Fatal(err) - } - if err := SaveServices(path, []string{"cloud"}, nil, true); err == nil { - t.Errorf("%s: SaveServices accepted %s", name, contents) - } - assertProfileFile(t, path, contents) - } -} - -// An empty profile file is refused with an error that says so, not "EOF". -func TestEmptyProfileIsExplained(t *testing.T) { - path := filepath.Join(t.TempDir(), "empty.json") - if err := os.WriteFile(path, nil, 0o644); err != nil { - t.Fatal(err) - } - if _, err := LoadSlimProfile(path); err == nil || !strings.Contains(err.Error(), "is empty") { - t.Errorf("LoadSlimProfile of an empty file = %v, want an is-empty error", err) - } - if err := SaveServices(path, []string{"siri"}, nil, true); err == nil || !strings.Contains(err.Error(), "is empty") { - t.Errorf("SaveServices on an empty file = %v, want an is-empty error", err) - } -} diff --git a/profiles.go b/profiles.go deleted file mode 100644 index 9f9ac7e..0000000 --- a/profiles.go +++ /dev/null @@ -1,492 +0,0 @@ -package simslim - -import "sort" - -// Category groups launchd daemon labels that a slim boot disables together. -type Category struct { - ID string `json:"id"` - Name string `json:"name"` - Description string `json:"description"` - Downside string `json:"downside"` - ApproxMemoryMB int `json:"approxMemoryMB"` - Labels []string `json:"labels"` - ServiceDescriptions map[string]string `json:"serviceDescriptions"` - AlwaysEnabled []AlwaysEnabledService `json:"alwaysEnabled,omitempty"` -} - -// AlwaysEnabledService is shown alongside a category for transparency but is -// never included in a slim profile. Earlier versions may have disabled it, so -// it remains in the mutation allowlist solely to repair that legacy state. -type AlwaysEnabledService struct { - Label string `json:"label"` - Reason string `json:"reason"` -} - -// Categories is the complete allowlist of daemons a profile may disable. -// Categories may overlap: a label lives in every category whose feature needs -// it, and an excepted category keeps all its labels enabled even when a -// slimmed category also lists them. -// ApproxMemoryMB values are rounded median increases in phys_footprint when -// only that category is kept on versus a fully slim iOS 26.5 clean boot. The -// estimates vary by runtime and workload and are not additive. -var Categories = []Category{ - { - ID: "widgets", - Name: "Widgets & Wallpaper", - Description: "Home and lock screen posters, widgets, and Live Activities.", - Downside: "Home and Lock Screen widgets, wallpaper posters, and Live Activities stop updating.", - ApproxMemoryMB: 675, - Labels: []string{ - "com.apple.PosterBoard", - "com.apple.chronod", - "com.apple.liveactivitiesd", - // chronod runs the stock Maps widget, which retries its navd - // connection in a tight loop while navd is down and floods the - // unified log; shared with the connectivity category. - "com.apple.navd", - }, - }, - { - ID: "siri", - Name: "Siri & Intelligence", - Description: "Siri, Apple Intelligence, speech, and on-device ML model services.", - Downside: "Siri, speech features, and Apple Intelligence services are unavailable.", - ApproxMemoryMB: 265, - Labels: []string{ - "com.apple.assistant_cdmd", - "com.apple.assistant_service", - "com.apple.siriactionsd", - "com.apple.siriinferenced", - "com.apple.siriknowledged", - "com.apple.sirittsd", - "com.apple.siri.context.service", - "com.apple.siri.acousticsignature", - "com.apple.corespeechd", - "com.apple.voiced", - "com.apple.voicebankingd", - "com.apple.speechmodeltrainingd", - "com.apple.intelligenceplatformd", - "com.apple.intelligencecontextd", - "com.apple.intelligenceflowd", - "com.apple.intelligencetasksd", - "com.apple.generativeexperiencesd", - "com.apple.knowledgeconstructiond", - "com.apple.naturallanguaged", - "com.apple.textunderstandingd", - "com.apple.modelcatalogd", - "com.apple.modelmanagerd", - "com.apple.mlhostd", - "com.apple.mlruntimed", - "com.apple.suggestd", - "com.apple.parsecd", - "com.apple.parsec-fbf", - "com.apple.proactiveeventtrackerd", - }, - AlwaysEnabled: []AlwaysEnabledService{ - { - Label: "com.apple.assistantd", - Reason: "Hosts the dictation service; without it the system Spotlight app leaks memory.", - }, - }, - }, - { - ID: "search", - Name: "Spotlight & Search", - Description: "On-device Spotlight and in-Settings search services.", - Downside: "Spotlight and Settings search return no results, and Recents in Files and the document picker fails to load.", - ApproxMemoryMB: 50, - Labels: []string{ - "com.apple.searchd", - "com.apple.searchtoold", - "com.apple.spotlightknowledged", - "com.apple.spotlightknowledged.updater", - "com.apple.corespotlightservice", - }, - }, - { - ID: "icloud", - Name: "iCloud & Apple Account", - Description: "iCloud sync, Apple Account, keychain, and backup services.", - Downside: "iCloud sync, Apple Account, Keychain, and backup workflows will not work.", - ApproxMemoryMB: 100, - Labels: []string{ - "com.apple.appleaccountd", - "com.apple.appleaccounttransparencyd", - "com.apple.appleidsetupd", - "com.apple.akd", - "com.apple.amsaccountsd", - "com.apple.amsengagementd", - "com.apple.amsondevicestoraged", - "com.apple.cloudd", - "com.apple.cloudphotod", - "com.apple.ckdiscretionaryd", - "com.apple.cloudsettingssyncagent", - "com.apple.bird", - "com.apple.syncdefaultsd", - "com.apple.cdpd", - "com.apple.sosd", - "com.apple.SecureBackupDaemon", - "com.apple.TrustedPeersHelper", - "com.apple.protectedcloudstorage.protectedcloudkeysyncing", - "com.apple.icloudmailagent", - "com.apple.icloudsubscriptionoptimizerd", - "com.apple.communicationtrustd", - }, - }, - { - ID: "store", - Name: "App Store, Push & Media", - Description: "App Store, push notification, StoreKit, and media services.", - Downside: "Remote push notifications and StoreKit or App Store testing will not work.", - ApproxMemoryMB: 80, - Labels: []string{ - "com.apple.appstored", - "com.apple.appstorecomponentsd", - "com.apple.apsd", - "com.apple.itunescloudd", - "com.apple.itunesstored", - "com.apple.storekitd", - // Apple Media Services renders the in-app purchase payment - // sheet; these three are shared with the icloud category. - "com.apple.amsaccountsd", - "com.apple.amsengagementd", - "com.apple.amsondevicestoraged", - // Wallet hosts the payment authorization sheet and needs the - // Finance datastore; both shared with the other category. - "com.apple.passd", - "com.apple.financed", - "com.apple.videosubscriptionsd", - "com.apple.assetsubscriptiond", - "com.apple.musicd", - }, - }, - { - ID: "pim", - Name: "Mail, Calendar & Contacts", - Description: "Mail, Calendar, Contacts, Reminders, and related sync services.", - Downside: "Contacts, Calendar, Reminders, and Mail-backed pickers or sync may fail.", - ApproxMemoryMB: 80, - Labels: []string{ - "com.apple.email.maild", - "com.apple.exchangesyncd", - "com.apple.dataaccess.dataaccessd", - "com.apple.calaccessd", - "com.apple.remindd", - "com.apple.contactsd", - "com.apple.contacts.postersyncd", - "com.apple.peopled", - }, - }, - { - ID: "web", - Name: "Safari Sync & Web Services", - Description: "Safari sync, web push, privacy, and universal-link services.", - Downside: "Universal links and Safari sync or background web services will not work.", - ApproxMemoryMB: 50, - Labels: []string{ - "com.apple.SafariBookmarksSyncAgent", - "com.apple.Safari.History", - "com.apple.Safari.passwordbreachd", - "com.apple.Safari.SafeBrowsing.Service", - "com.apple.safarifetcherd", - "com.apple.WebBookmarks.webbookmarksd", - "com.apple.webkit.adattributiond", - "com.apple.webkit.webpushd", - "com.apple.webprivacyd", - "com.apple.swcd", - }, - }, - { - ID: "family", - Name: "Family & Screen Time", - Description: "Family Sharing, Screen Time, and usage tracking.", - Downside: "Family Sharing, Screen Time, and usage tracking stop working.", - ApproxMemoryMB: 65, - Labels: []string{ - "com.apple.familycircled", - "com.apple.FamilyControlsAgent", - "com.apple.familynotification", - "com.apple.askpermissiond", - "com.apple.asktod", - "com.apple.ScreenTimeAgent", - "com.apple.ScreenTimeSettingsAgent", - "com.apple.UsageTrackingAgent", - }, - }, - { - ID: "health", - Name: "Health, Home & Fitness", - Description: "HealthKit, HomeKit, and Fitness services.", - Downside: "HealthKit, HomeKit, and Fitness integrations will not work.", - ApproxMemoryMB: 135, - Labels: []string{ - "com.apple.healthd", - "com.apple.healthappd", - "com.apple.healthcontentd", - "com.apple.healtheventsd", - "com.apple.healthrecordsd", - "com.apple.finhealthd", - "com.apple.homed", - "com.apple.homeeventsd", - "com.apple.fitcore", - "com.apple.fitcore.session", - "com.apple.fitnesscoachingd", - "com.apple.fitnessintelligenced", - "com.apple.activityawardsd", - "com.apple.activitysharingd", - }, - }, - { - ID: "photos", - Name: "Photos & Media Analysis", - Description: "Photos library, photo analysis, and media analysis services.", - Downside: "Photo picker, Photos-library workflows, and media analysis may fail.", - ApproxMemoryMB: 60, - Labels: []string{ - "com.apple.photoanalysisd", - "com.apple.photosface", - "com.apple.mediaanalysisd", - "com.apple.mediaanalysisd.service", - "com.apple.mediastream.mstreamd", - "com.apple.medialibraryd", - "com.apple.assetsd", - "com.apple.assetsd.nebulad", - }, - }, - { - ID: "apps", - Name: "News, Weather, Maps & Games", - Description: "News, Weather, Maps, Tips, and game services.", - Downside: "News, Weather, Maps background data, and game-controller services are unavailable.", - ApproxMemoryMB: 90, - Labels: []string{ - "com.apple.newsd", - "com.apple.weatherd", - "com.apple.Maps.mapssyncd", - "com.apple.Maps.mapspushd", - "com.apple.Maps.geocorrectiond", - "com.apple.maps.destinationd", - "com.apple.MapKit.SnapshotService", - "com.apple.jetpackassetd", - "com.apple.tipsd", - "com.apple.gamesaved", - "com.apple.GameController.gamecontrollerd", - }, - AlwaysEnabled: []AlwaysEnabledService{ - { - Label: "com.apple.gamed", - Reason: "Required for timely XCUITest app launches (DTServiceHub / GameKit).", - }, - }, - }, - { - ID: "messaging", - Name: "Messaging & FaceTime", - Description: "iMessage, FaceTime, call, and identity services.", - Downside: "iMessage, FaceTime, and related identity services will not work.", - ApproxMemoryMB: 60, - Labels: []string{ - "com.apple.identityservicesd", - "com.apple.ids_simd", - "com.apple.imautomatichistorydeletionagent", - "com.apple.imcore.imtransferagent", - "com.apple.imdpersistence.IMDPersistenceAgent", - "com.apple.facetimemessagestored", - "com.apple.telephonyutilities.callservicesd", - }, - }, - { - ID: "connectivity", - Name: "Sharing & Device Connectivity", - Description: "AirDrop, Continuity, CarPlay, Watch, and Find My services.", - Downside: "AirDrop, Continuity, CarPlay, Watch, and Find My connectivity will not work.", - ApproxMemoryMB: 65, - Labels: []string{ - "com.apple.rapportd", - "com.apple.companiond", - "com.apple.carkitd", - "com.apple.wcd", - "com.apple.tvremoted", - "com.apple.avatarsd", - "com.apple.stickersd", - "com.apple.sociallayerd", - "com.apple.announced", - "com.apple.navd", - "com.apple.findmy.findmylocated", - }, - AlwaysEnabled: []AlwaysEnabledService{ - { - Label: "com.apple.sharingd", - Reason: "Required for system share sheets.", - }, - }, - }, - { - ID: "telemetry", - Name: "Ads, Diagnostics & Telemetry", - Description: "DeviceCheck, ad privacy, analytics, diagnostics, and feedback services.", - Downside: "DeviceCheck plus analytics, diagnostics, and feedback services are unavailable.", - ApproxMemoryMB: 105, - Labels: []string{ - "com.apple.ap.adprivacyd", - "com.apple.ap.promotedcontentd", - "com.apple.diagnosticextensionsd", - "com.apple.feedbackd", - "com.apple.rtcreportingd", - "com.apple.securityuploadd", - "com.apple.geoanalyticsd", - "com.apple.triald", - "com.apple.followupd", - "com.apple.purplebuddy.budd", - "com.apple.devicecheckd", - }, - }, - { - ID: "mdm", - Name: "Device Management", - Description: "Declarative device management and managed asset services.", - Downside: "Declarative device management, and MDM or configuration-profile workflows that use it, will not work.", - ApproxMemoryMB: 10, - Labels: []string{ - "com.apple.remotemanagementd", - "com.apple.RemoteManagementAgent", - "com.apple.managedassetsd", - }, - }, - { - ID: "other", - Name: "Other Background Services", - Description: "Wallet, App Clips, business services, assets, and miscellaneous background daemons.", - Downside: "Wallet, App Clips, accessibility asset downloads, merchant, business, and miscellaneous background services are unavailable.", - ApproxMemoryMB: 225, - Labels: []string{ - "com.apple.financed", - "com.apple.passd", - "com.apple.merchantd", - "com.apple.coreidvd", - "com.apple.businessservicesd", - "com.apple.deviceaccessd", - "com.apple.replicatord", - "com.apple.linkd", - "com.apple.ind", - "com.apple.storagedatad", - "com.apple.StatusKitAgent", - "com.apple.countryd", - "com.apple.mobileassetd", - "com.apple.managedconfiguration.passcodenagd", - "com.apple.accessibility.axassetsd", - "com.apple.ClipServices.clipserviced", - }, - }, -} - -func CategoryByID(id string) (Category, bool) { - for _, c := range Categories { - if c.ID == id { - return c, true - } - } - return Category{}, false -} - -// slimmableSet is every label a service profile may disable. -func SlimmableSet() map[string]bool { - set := make(map[string]bool) - for _, c := range Categories { - for _, l := range c.Labels { - set[l] = true - } - } - return set -} - -// managedSet is the complete mutation allowlist. Most labels are slimmable; -// required labels may only transition back to enabled for compatibility. -func managedSet() map[string]bool { - set := SlimmableSet() - for _, category := range Categories { - for _, service := range category.AlwaysEnabled { - set[service.Label] = true - } - } - return set -} - -// Profile selects which managed daemons a slim boot should disable. -type Profile struct { - ExceptCategories map[string]bool // category IDs to leave fully enabled - Keep map[string]bool // individual labels to leave enabled -} - -// desired returns the labels this profile wants disabled. Categories may share -// labels, so a label stays enabled when any excepted category lists it. -func (p Profile) Desired() map[string]bool { - set := SlimmableSet() - for _, c := range Categories { - if !p.ExceptCategories[c.ID] { - continue - } - for _, l := range c.Labels { - delete(set, l) - } - } - for l := range p.Keep { - delete(set, l) - } - return set -} - -// DesiredForDevice applies platform-specific service requirements to a profile. -// Desired remains the platform-independent catalog for profile editors. -func (p Profile) DesiredForDevice(d Device) map[string]bool { - return desiredForDevice(d, p.Desired()) -} - -func desiredForDevice(d Device, desired map[string]bool) map[string]bool { - set := make(map[string]bool, len(desired)) - for label, disabled := range desired { - // watchOS 26.5 re-enables homed after startup, even when launchd - // initially honours the override. Keep it enabled rather than report - // a full slim that drifts as soon as the Watch finishes starting up. - if d.PlatformName() == "watchOS" && label == "com.apple.homed" { - continue - } - // visionOS serves the simulated surroundings as mobile assets. - // Without mobileassetd the device boots into a black space: the - // Home View icons float in the dark, and apps still launch. - if d.PlatformName() == "visionOS" && label == "com.apple.mobileassetd" { - continue - } - set[label] = disabled - } - return set -} - -// delta returns the launchctl transitions to move from current to desired, -// scoped to managed labels. Labels outside managed are never touched: a -// non-managed desired label is ignored, and a non-managed label that is already -// disabled is left disabled. Empty results mean the device is already correct. -func delta(current, desired, managed map[string]bool) (toDisable, toEnable []string) { - dis := map[string]bool{} - for l := range desired { - if managed[l] && !current[l] { - dis[l] = true - } - } - en := map[string]bool{} - for l := range current { - if managed[l] && !desired[l] { - en[l] = true - } - } - return keys(dis), keys(en) -} - -func keys(set map[string]bool) []string { - out := make([]string, 0, len(set)) - for k := range set { - out = append(out, k) - } - sort.Strings(out) - return out -} diff --git a/profiles_test.go b/profiles_test.go deleted file mode 100644 index 5379bcd..0000000 --- a/profiles_test.go +++ /dev/null @@ -1,317 +0,0 @@ -package simslim - -import ( - "reflect" - "strings" - "testing" -) - -// forbiddenLabels deadlock or wedge a simulator when disabled and must never be -// managed. nanoregistryd wedges CoreSimulator so every simctl operation hangs; -// sleepd makes SpringBoard retry-storm itself to death; the rest were observed -// to break boot. They are deliberately absent from Categories. -var forbiddenLabels = []string{ - "com.apple.nanoregistryd", - "com.apple.nanoregistrylaunchd", - "com.apple.nanoprefsyncd.2", - "com.apple.nanotimekitcompaniond", - "com.apple.nanobackupd", - "com.apple.sleepd", - "com.apple.appprotectiond", - "com.apple.ManagedSettingsAgent", - "com.apple.managedconfiguration.profiled", - "com.apple.mobiletimerd", - "com.apple.routined", - "com.apple.biomed", - "com.apple.biomesyncd", - "com.apple.dmd", - "com.apple.donotdisturbd", -} - -func TestManagedExcludesForbidden(t *testing.T) { - managed := managedSet() - for _, l := range forbiddenLabels { - if managed[l] { - t.Errorf("forbidden daemon %q is in a category; it must never be managed", l) - } - } -} - -// These are the launchd or bundle identifiers behind the live processes cited -// in issue #30. None is part of a full slim profile: required and unsafe -// services stay up, and system apps/extensions are not managed launchd labels. -func TestFullProfileDoesNotClaimUnmanagedProcesses(t *testing.T) { - desired := (Profile{}).Desired() - for _, label := range []string{ - "com.apple.routined", - "com.apple.sharingd", - "com.apple.locationd", - "com.apple.eventkitsyncd", - "com.apple.Spotlight", - "com.apple.MercuryPoster", - "com.apple.texttospeech.SiriAUSP", - } { - if desired[label] { - t.Errorf("full profile claims live process %q is disabled", label) - } - } -} - -// Labels may repeat across categories (a daemon can serve several features) -// but never within one category. -func TestNoDuplicateLabelsWithinCategory(t *testing.T) { - for _, c := range Categories { - seen := map[string]bool{} - for _, l := range c.Labels { - if seen[l] { - t.Errorf("label %q appears twice in category %q", l, c.ID) - } - seen[l] = true - } - } -} - -func TestDesiredKeepsSharedLabelsOfExceptedCategories(t *testing.T) { - owners := map[string][]string{} - for _, c := range Categories { - for _, l := range c.Labels { - owners[l] = append(owners[l], c.ID) - } - } - sharedSeen := false - for l, ids := range owners { - if len(ids) < 2 { - continue - } - sharedSeen = true - for _, id := range ids { - p := Profile{ExceptCategories: map[string]bool{id: true}, Keep: map[string]bool{}} - if p.Desired()[l] { - t.Errorf("--except %s should keep shared label %q enabled", id, l) - } - } - } - if !sharedSeen { - t.Error("expected at least one shared label (the AMS payment-sheet daemons)") - } -} - -func TestEveryServiceHasShortDescription(t *testing.T) { - known := map[string]bool{} - for _, category := range Categories { - if len(category.ServiceDescriptions) != len(category.Labels) { - t.Errorf("category %q has %d labels but %d service descriptions", category.ID, len(category.Labels), len(category.ServiceDescriptions)) - } - for _, label := range category.Labels { - known[label] = true - description, ok := category.ServiceDescriptions[label] - if !ok || strings.TrimSpace(description) == "" { - t.Errorf("service %q has no user-facing description", label) - } - if strings.ContainsAny(description, "\r\n") { - t.Errorf("service %q description must stay on one logical line", label) - } - if len(description) > 90 { - t.Errorf("service %q description is too long (%d characters)", label, len(description)) - } - } - } - for label := range serviceDescriptionByLabel { - if !known[label] { - t.Errorf("description exists for unmanaged service %q", label) - } - } -} - -func TestRequiredEnabledLabelsAreNeverSlimmed(t *testing.T) { - slimmable := SlimmableSet() - managed := managedSet() - profile := Profile{ExceptCategories: map[string]bool{}, Keep: map[string]bool{}} - desired := profile.Desired() - for _, category := range Categories { - for _, service := range category.AlwaysEnabled { - if slimmable[service.Label] || desired[service.Label] { - t.Errorf("required daemon %q is included in a slim profile", service.Label) - } - if !managed[service.Label] { - t.Errorf("required daemon %q is missing from the repair allowlist", service.Label) - } - if service.Reason == "" { - t.Errorf("required daemon %q has no user-facing reason", service.Label) - } - } - } -} - -func TestDeltaRepairsRequiredEnabledLabels(t *testing.T) { - current := map[string]bool{"com.apple.sharingd": true} - desired := Profile{ExceptCategories: map[string]bool{}, Keep: map[string]bool{}}.Desired() - toDisable, toEnable := delta(current, desired, managedSet()) - if len(toDisable) == 0 { - t.Fatal("full profile should still disable slimmable labels") - } - if !reflect.DeepEqual(toEnable, []string{"com.apple.sharingd"}) { - t.Errorf("toEnable = %v, want [com.apple.sharingd]", toEnable) - } -} - -func TestGamedStaysEnabledForXCTest(t *testing.T) { - const label = "com.apple.gamed" - desired := (Profile{}).Desired() - if SlimmableSet()[label] || desired[label] { - t.Error("gamed must stay enabled: disabling it delays XCUITest app launches") - } - apps, ok := CategoryByID("apps") - if !ok { - t.Fatal("apps category is missing") - } - found := false - for _, service := range apps.AlwaysEnabled { - if service.Label == label && strings.TrimSpace(service.Reason) != "" { - found = true - } - } - if !found { - t.Error("apps must explain why gamed stays enabled") - } - _, toEnable := delta(map[string]bool{label: true}, desired, managedSet()) - if !reflect.DeepEqual(toEnable, []string{label}) { - t.Errorf("legacy disabled gamed repair = %v, want [%s]", toEnable, label) - } - for _, other := range []string{"com.apple.gamesaved", "com.apple.GameController.gamecontrollerd"} { - if !desired[other] { - t.Errorf("unrelated game service %q should remain slimmable", other) - } - } -} - -func TestAssistantdStaysEnabledForSpotlight(t *testing.T) { - const label = "com.apple.assistantd" - desired := (Profile{}).Desired() - if SlimmableSet()[label] || desired[label] { - t.Error("assistantd must stay enabled: without its dictation service Spotlight leaks memory") - } - siri, ok := CategoryByID("siri") - if !ok { - t.Fatal("siri category is missing") - } - found := false - for _, service := range siri.AlwaysEnabled { - if service.Label == label && strings.TrimSpace(service.Reason) != "" { - found = true - } - } - if !found { - t.Error("siri must explain why assistantd stays enabled") - } - _, toEnable := delta(map[string]bool{label: true}, desired, managedSet()) - if !reflect.DeepEqual(toEnable, []string{label}) { - t.Errorf("legacy disabled assistantd repair = %v, want [%s]", toEnable, label) - } - for _, other := range []string{"com.apple.assistant_service", "com.apple.corespeechd", "com.apple.siriknowledged"} { - if !desired[other] { - t.Errorf("other Siri service %q should remain slimmable", other) - } - } -} - -func TestWidgetsKeepNavdForMapsWidget(t *testing.T) { - const label = "com.apple.navd" - widgets := Profile{ExceptCategories: map[string]bool{"widgets": true}, Keep: map[string]bool{}} - if widgets.Desired()[label] { - t.Error("--except widgets must keep navd enabled: the Maps widget spins without it") - } - if !(Profile{}).Desired()[label] { - t.Error("navd should remain slimmable when widgets are disabled") - } -} - -func TestCategoriesHaveUserImpactMetadata(t *testing.T) { - for _, c := range Categories { - if c.Downside == "" { - t.Errorf("category %q has no downside description", c.ID) - } - if c.ApproxMemoryMB <= 0 { - t.Errorf("category %q has invalid approximate memory %d MB", c.ID, c.ApproxMemoryMB) - } - } -} - -func TestCategoryByID(t *testing.T) { - for _, c := range Categories { - got, ok := CategoryByID(c.ID) - if !ok { - t.Errorf("CategoryByID(%q) not found", c.ID) - continue - } - if got.ID != c.ID { - t.Errorf("CategoryByID(%q) returned category %q", c.ID, got.ID) - } - } - if _, ok := CategoryByID("nope"); ok { - t.Error("CategoryByID(\"nope\") should not resolve an unknown ID") - } -} - -func TestDelta(t *testing.T) { - managed := map[string]bool{"a": true, "b": true, "c": true} - cases := []struct { - name string - current, desired map[string]bool - wantDisable []string - wantEnable []string - }{ - { - name: "enable all from stock", - current: map[string]bool{}, - desired: map[string]bool{"a": true, "b": true, "c": true}, - wantDisable: []string{"a", "b", "c"}, - }, - { - name: "restore all to stock", - current: map[string]bool{"a": true, "b": true, "c": true}, - desired: map[string]bool{}, - wantEnable: []string{"a", "b", "c"}, - }, - { - name: "already in desired state", - current: map[string]bool{"a": true, "b": true}, - desired: map[string]bool{"a": true, "b": true}, - }, - { - name: "profile edit adds and removes", - current: map[string]bool{"a": true, "b": true}, - desired: map[string]bool{"b": true, "c": true}, - wantDisable: []string{"c"}, - wantEnable: []string{"a"}, - }, - { - name: "unmanaged desired label is ignored", - current: map[string]bool{}, - desired: map[string]bool{"x": true}, - }, - { - name: "unmanaged disabled label is left alone", - current: map[string]bool{"x": true}, - desired: map[string]bool{}, - }, - } - for _, tc := range cases { - t.Run(tc.name, func(t *testing.T) { - gotDisable, gotEnable := delta(tc.current, tc.desired, managed) - if !equalSlices(gotDisable, tc.wantDisable) { - t.Errorf("toDisable = %v, want %v", gotDisable, tc.wantDisable) - } - if !equalSlices(gotEnable, tc.wantEnable) { - t.Errorf("toEnable = %v, want %v", gotEnable, tc.wantEnable) - } - }) - } -} - -func equalSlices(a, b []string) bool { - if len(a) == 0 && len(b) == 0 { - return true - } - return reflect.DeepEqual(a, b) -} diff --git a/scripts/build-app.sh b/scripts/build-app.sh index 5181416..f046065 100755 --- a/scripts/build-app.sh +++ b/scripts/build-app.sh @@ -6,7 +6,7 @@ BUILD_DIR="${BUILD_DIR:-$ROOT_DIR/build}" APP_PATH="$BUILD_DIR/SimSlim.app" ICON_SOURCE="$ROOT_DIR/gui/Assets/AppIcon.png" MACHINE_ARCH="$(uname -m)" -VERSION="${VERSION:-$(git -C "$ROOT_DIR" describe --tags --always --dirty)}" +VERSION="${VERSION:-$(git -C "$ROOT_DIR" describe --tags --match 'v*' --always --dirty)}" APP_VERSION="${VERSION#v}" APP_VERSION="${APP_VERSION%%-*}" BUILD_NUMBER="${BUILD_NUMBER:-1}" @@ -24,19 +24,13 @@ if [[ "$(uname -s)" != "Darwin" ]]; then exit 1 fi -if ! command -v go >/dev/null 2>&1; then - echo "Go is required. Install it with: brew install go" >&2 - exit 1 -fi - if [[ ! -f "$ICON_SOURCE" ]]; then echo "App icon source is missing: $ICON_SOURCE" >&2 exit 1 fi case "$MACHINE_ARCH" in - arm64) GO_ARCH="arm64" ;; - x86_64) GO_ARCH="amd64" ;; + arm64 | x86_64) ;; *) echo "Unsupported Mac architecture: $MACHINE_ARCH" >&2 exit 1 @@ -44,7 +38,16 @@ case "$MACHINE_ARCH" in esac STAGING_DIR="$(mktemp -d "${TMPDIR:-/tmp}/simslim-app.XXXXXX")" -trap 'rm -rf "$STAGING_DIR"' EXIT +VERSION_SWIFT="$ROOT_DIR/swift/Sources/SimSlimKit/Version.swift" +VERSION_BACKUP="$STAGING_DIR/Version.swift.orig" +cleanup() { + # Put the stamped version file back, even when the build fails. + if [[ -f "$VERSION_BACKUP" ]]; then + cp "$VERSION_BACKUP" "$VERSION_SWIFT" + fi + rm -rf "$STAGING_DIR" +} +trap cleanup EXIT STAGED_APP="$STAGING_DIR/SimSlim.app" mkdir -p "$STAGED_APP/Contents/MacOS" "$STAGED_APP/Contents/Resources" @@ -76,12 +79,25 @@ done iconutil -c icns "$ICONSET_DIR" -o "$STAGED_APP/Contents/Resources/SimSlim.icns" echo "Building bundled simslim CLI ($MACHINE_ARCH)…" -( - cd "$ROOT_DIR" - CGO_ENABLED=0 GOOS=darwin GOARCH="$GO_ARCH" \ - go build -trimpath -ldflags "-s -w -X main.version=$VERSION" \ - -o "$STAGED_APP/Contents/Resources/simslim" ./cmd/simslim -) +case "$VERSION" in + *[!A-Za-z0-9._+-]*) + echo "VERSION contains characters that are not safe to stamp: $VERSION" >&2 + exit 1 + ;; +esac +cp "$VERSION_SWIFT" "$VERSION_BACKUP" +sed -i '' -E "s|^public let simslimVersion = \".*\"$|public let simslimVersion = \"$VERSION\"|" "$VERSION_SWIFT" +if ! grep -q "simslimVersion = \"$VERSION\"" "$VERSION_SWIFT"; then + echo "Could not stamp the version into $VERSION_SWIFT" >&2 + exit 1 +fi +swift build -c release --package-path "$ROOT_DIR/swift" --arch "$MACHINE_ARCH" +BIN_DIR="$(swift build -c release --package-path "$ROOT_DIR/swift" --arch "$MACHINE_ARCH" --show-bin-path)" +cp "$BIN_DIR/simslim" "$STAGED_APP/Contents/Resources/simslim" +cp "$VERSION_BACKUP" "$VERSION_SWIFT" +rm -f "$VERSION_BACKUP" +strip -x "$STAGED_APP/Contents/Resources/simslim" 2>/dev/null || true +codesign --force --sign - "$STAGED_APP/Contents/Resources/simslim" >/dev/null echo "Building SwiftUI app ($MACHINE_ARCH)…" xcrun swiftc \ diff --git a/scripts/parity-normalize.py b/scripts/parity-normalize.py new file mode 100755 index 0000000..4ca443d --- /dev/null +++ b/scripts/parity-normalize.py @@ -0,0 +1,80 @@ +#!/usr/bin/env python3 +"""Normalizes one simslim output stream for the Go-vs-Swift parity check. + +stdin -> stdout. Volatile values (UDIDs, home directory, binary paths, durations, +and with --shape every number) are replaced so that two correct implementations +produce identical text. JSON is re-serialized with sorted keys; JSON lines +(watch --json) are normalized per line. A null array and an empty array are the +same here: the Go encoder prints null where Swift prints [] (a known, harmless +difference). Everything else must match exactly. +""" +import argparse +import json +import os +import re +import sys + +ap = argparse.ArgumentParser() +ap.add_argument("--dev", default="", help="UDID of the scratch device, shown as ") +ap.add_argument("--bin", action="append", default=[], help="binary path to mask") +ap.add_argument("--shape", action="store_true", help="mask every number (live measurements)") +ap.add_argument("--kinds", action="store_true", help="JSON lines: keep only the event names") +args = ap.parse_args() + +text = sys.stdin.read() +seen = {} + + +def uuid_sub(match): + value = match.group(0).upper() + if args.dev and value == args.dev.upper(): + return "" + seen.setdefault(value, "" % (len(seen) + 1)) + return seen[value] + + +def scrub(s): + s = re.sub(r"[0-9A-Fa-f]{8}-[0-9A-Fa-f]{4}-[0-9A-Fa-f]{4}-[0-9A-Fa-f]{4}-[0-9A-Fa-f]{12}", uuid_sub, s) + for path in args.bin: + s = s.replace(path, "") + s = s.replace(os.path.expanduser("~"), "~") + s = re.sub(r"\bsimslim (dev|v?\d[\w.\-+]*)\b", "simslim ", s) + s = re.sub(r"\b\d+(\.\d+)?(ms|µs|s|m|h)\b", "", s) + return s + + +def walk(value): + if value is None: + return [] + if isinstance(value, bool): + return value + if isinstance(value, (int, float)): + return "" if args.shape else value + if isinstance(value, str): + return scrub(value) + if isinstance(value, list): + return [walk(v) for v in value] + if isinstance(value, dict): + return {scrub(k): walk(v) for k, v in value.items()} + return value + + +def dump(value): + return json.dumps(value, sort_keys=True, indent=1, ensure_ascii=False) + + +try: + print(dump(walk(json.loads(text)))) +except ValueError: + lines = [l for l in text.splitlines() if l.strip()] + try: + events = [json.loads(l) for l in lines] + if lines and all(isinstance(e, dict) for e in events): + if args.kinds: + print("\n".join(str(e.get("event")) for e in events)) + else: + print("\n".join(dump(walk(e)) for e in events)) + sys.exit(0) + except ValueError: + pass + sys.stdout.write(scrub(text)) diff --git a/scripts/parity.sh b/scripts/parity.sh new file mode 100755 index 0000000..e80abf2 --- /dev/null +++ b/scripts/parity.sh @@ -0,0 +1,436 @@ +#!/bin/bash +# Go-vs-Swift parity check for simslim. Run it on a Mac that has Xcode, a simulator +# runtime, python3 and Go. It builds both CLIs, runs the same commands through each, +# and diffs the normalized stdout, stderr and exit code. Nothing is sent anywhere. +# +# The Go tree was removed from this repository; the Go side is built from the +# go-reference-final tag (the last commit that still had it), checked out into a +# sibling worktree at ../simslim-go-reference, created once and reused across runs. +# +# scripts/parity.sh read-only commands on the existing simulators +# scripts/parity.sh --mutating also run on/off/enable/disable/clone/... on a +# scratch simulator this script creates and deletes +# scripts/parity.sh --watch also compare `watch --json` events (slow, ~5 min). +# UNLIKE the rest, `watch` slims EVERY shut-down +# simulator you own, so it asks first (or pass --yes) +# +# Options: --udid UDID (repeatable; default: up to 3 simulators plus booted ones) +# --runtime ID --devicetype ID (scratch simulator; default: newest iOS >= 18.5) +# --keep-device (leave the scratch simulator), --out DIR +# Env: GO_BIN / SWIFT_BIN use prebuilt binaries instead of building. +# +# Apart from --watch, the only simulators it changes are the scratch ones it creates +# itself. Read-only runs never mutate anything. Exit status is 1 if any comparison differs. +# Known, expected differences are listed in docs/parity-check.md. + +set -u +cd "$(dirname "$0")/.." || exit 2 +ROOT="$PWD" + +MUTATING=0 +WATCH=0 +YES=0 +KEEP=0 +UDIDS=() +RUNTIME="" +DEVTYPE="" +OUT="" +while [ $# -gt 0 ]; do + case "$1" in + --mutating) MUTATING=1 ;; + --watch) WATCH=1 ;; + --keep-device) KEEP=1 ;; + --yes) YES=1 ;; + --udid) UDIDS+=("$2"); shift ;; + --runtime) RUNTIME="$2"; shift ;; + --devicetype) DEVTYPE="$2"; shift ;; + --out) OUT="$2"; shift ;; + -h | --help) sed -n 2,24p "$0"; exit 0 ;; + *) echo "parity: unknown option $1" >&2; exit 2 ;; + esac + shift +done + +[ "$(uname)" = Darwin ] || { echo "parity: macOS only" >&2; exit 2; } +OUT="${OUT:-$ROOT/build/parity/$(date +%Y%m%d-%H%M%S)}" +mkdir -p "$OUT" +OUT="$(cd "$OUT" && pwd)" # absolute: the Go build below runs from another directory +NORM="$ROOT/scripts/parity-normalize.py" + +# --- binaries --------------------------------------------------------------- +if [ -z "${GO_BIN:-}" ]; then + command -v go >/dev/null || { echo "parity: go not found (or set GO_BIN)" >&2; exit 2; } + GO_WORKTREE="$ROOT/../simslim-go-reference" + if [ ! -d "$GO_WORKTREE" ]; then + git worktree prune + git worktree add --detach "$GO_WORKTREE" go-reference-final >/dev/null || exit 2 + fi + want="$(git rev-parse 'go-reference-final^{commit}' 2>/dev/null)" || + { echo "parity: tag go-reference-final not found (git fetch --tags)" >&2; exit 2; } + [ "$(git -C "$GO_WORKTREE" rev-parse HEAD 2>/dev/null)" = "$want" ] || + { echo "parity: $GO_WORKTREE is not at go-reference-final; remove it (git worktree remove --force) and rerun" >&2; exit 2; } + GO_BIN="$OUT/simslim-go" + (cd "$GO_WORKTREE" && go build -o "$GO_BIN" ./cmd/simslim) || exit 2 +fi +if [ -z "${SWIFT_BIN:-}" ]; then + (cd swift && swift build -c release) >"$OUT/swift-build.log" 2>&1 || { cat "$OUT/swift-build.log"; exit 2; } + SWIFT_BIN="$ROOT/swift/.build/release/simslim" +fi +echo "go: $GO_BIN" +echo "swift: $SWIFT_BIN" +echo "out: $OUT" + +TOTAL=0 +DIFFS=0 +REPORT="$OUT/report.txt" +: >"$REPORT" +DEV="" + +bin_of() { if [ "$1" = go ]; then echo "$GO_BIN"; else echo "$SWIFT_BIN"; fi; } + +# normalize TOOL FILE [extra normalizer args...] -> stdout +normalize() { + local file="$1" + shift + python3 -I "$NORM" --dev "$DEV" --bin "$GO_BIN" --bin "$SWIFT_BIN" "$@" <"$file" +} + +# cap TOOL DIR NAME MODE args... : run one command, save normalized stdout/stderr/code. +# MODE is exact, or shape (live numbers masked). +cap() { + local tool="$1" dir="$2" name="$3" mode="$4" + shift 4 + mkdir -p "$dir" + local flags=() + [ "$mode" = shape ] && flags=(--shape) + "$(bin_of "$tool")" "$@" >"$dir/$name.raw.out" 2>"$dir/$name.raw.err" "$dir/$name.code" + normalize "$dir/$name.raw.out" ${flags[@]+"${flags[@]}"} >"$dir/$name.out" + normalize "$dir/$name.raw.err" >"$dir/$name.err" +} + +# compare DIRA DIRB LABEL NAME... : diff the saved artifacts of both tools. +compare_one() { + local label="$1" name="$2" ok=1 part + TOTAL=$((TOTAL + 1)) + for part in out err code; do + if ! diff -u "$OUT/go/$label/$name.$part" "$OUT/swift/$label/$name.$part" >"$OUT/diff.tmp" 2>&1; then + ok=0 + { + echo "=== DIFF $label/$name ($part): --- go +++ swift" + cat "$OUT/diff.tmp" + } >>"$REPORT" + fi + done + if [ $ok = 1 ]; then echo " ok $label/$name"; else echo " DIFF $label/$name"; DIFFS=$((DIFFS + 1)); fi +} + +# both LABEL NAME MODE args... : run on both tools right now and compare. +both() { + local label="$1" name="$2" mode="$3" + shift 3 + cap go "$OUT/go/$label" "$name" "$mode" "$@" + cap swift "$OUT/swift/$label" "$name" "$mode" "$@" + compare_one "$label" "$name" +} + +# --- phase 1: read-only ----------------------------------------------------- +echo "== read-only commands" +both static version exact version +both static help exact help +both static noargs exact +both static unknown exact bogus-command +both static profiles exact profiles +both static profiles-json exact profiles --json +for id in $("$SWIFT_BIN" profiles --json | python3 -I -c 'import json,sys;print(" ".join(c["id"] for c in json.load(sys.stdin)))'); do + both static "profiles-$id" exact profiles "$id" --json +done +both static profiles-bad exact profiles no-such-category +both static doctor-list exact doctor --list --json +both static disk-categories exact disk-categories --json +both static disk-categories-text exact disk-categories +both static list exact list +both static list-json exact list --json +both static list-booted exact list --booted --json +both static top-json shape top --json +# argument and safety errors; none of these may touch a simulator. +both errors on-noargs exact on +both errors on-all exact on all +both errors on-booted exact on booted +both errors erase-all exact erase all +both errors delete-all exact delete all +both errors disk-clean-all exact disk-clean all --categories caches --confirm +both errors status-bogus exact status NOT-A-UDID +both errors bad-boot-timeout exact --boot-timeout abc list +both errors huge-boot-timeout exact --boot-timeout 99999999999999999999s list +both errors on-bad-category exact on 00000000-0000-0000-0000-000000000000 --except nope +both errors verify-both exact verify 00000000-0000-0000-0000-000000000000 --profile x --except y + +if [ ${#UDIDS[@]} -eq 0 ]; then + while read -r u; do UDIDS+=("$u"); done < <("$SWIFT_BIN" list --json | python3 -I -c ' +import json, sys +sims = json.load(sys.stdin) +booted = [s["udid"] for s in sims if s["state"] == "Booted"] +rest = [s["udid"] for s in sims if s["state"] != "Booted"][:3] +print("\n".join(booted + rest))') +fi +for u in ${UDIDS[@]+"${UDIDS[@]}"}; do + DEV="$u" + l="device-${u%%-*}" + both "$l" status exact status "$u" --json + both "$l" status-dropped exact status "$u" --dropped --json + both "$l" verify exact verify "$u" --json + both "$l" verify-except exact verify "$u" --except search,store --json + both "$l" doctor exact doctor "$u" --requires push,storekit,universal-links --json + both "$l" measure shape measure "$u" --json + both "$l" size exact size "$u" --json + both "$l" disk-plan exact disk-plan "$u" --json + both "$l" disk-plan-text exact disk-plan "$u" +done +DEV="" + +# --- phase 2: mutating, on a scratch simulator -------------------------------- +STORE_ROOT=/private/var/tmp +is_udid() { [[ "$1" =~ ^[0-9A-Fa-f]{8}(-[0-9A-Fa-f]{4}){3}-[0-9A-Fa-f]{12}$ ]]; } +EXTRA=() +WATCH_PID="" +cleanup() { + local u + # A background `watch` keeps slimming every simulator, so never leave it running. + if [ -n "$WATCH_PID" ]; then + kill -INT "$WATCH_PID" 2>/dev/null + wait "$WATCH_PID" 2>/dev/null + WATCH_PID="" + fi + if [ "$KEEP" = 0 ]; then + for u in ${EXTRA[@]+"${EXTRA[@]}"} "$DEV"; do + if [ -n "$u" ] && is_udid "$u"; then + xcrun simctl shutdown "$u" >/dev/null 2>&1 + xcrun simctl delete "$u" >/dev/null 2>&1 + rm -rf "$STORE_ROOT/com.apple.CoreSimulator.SimDevice.$u" + fi + done + fi +} + +trap cleanup EXIT +trap 'exit 130' INT TERM + +# is_new_clone UDID BEFORE_JSON NAME: the UDID a CLI reports for a clone is deleted +# afterwards, so only accept one that did not exist before and is the clone we named. +is_new_clone() { + is_udid "$1" || return 1 + grep -qiF "$1" <<<"$2" && return 1 + xcrun simctl list devices -j | python3 -I -c ' +import json, sys +udid, name = sys.argv[1].upper(), sys.argv[2] +for devs in json.load(sys.stdin)["devices"].values(): + for d in devs: + if d["udid"].upper() == udid: + sys.exit(0 if d["name"] == name else 1) +sys.exit(1)' "$1" "$3" +} + +pick_runtime_and_type() { + xcrun simctl list runtimes -j | python3 -I -c ' +import json, sys +want = sys.argv[1:] +best = None +for r in json.load(sys.stdin)["runtimes"]: + if not r.get("isAvailable") or r.get("platform") != "iOS": + continue + v = tuple(int(x) for x in r["version"].split(".")[:2]) + if v < (18, 5) or (want[0] and r["identifier"] != want[0]): + continue + if best is None or v > best[0]: + best = (v, r) +if not best: + sys.exit("no available iOS runtime >= 18.5 (use --runtime)") +r = best[1] +types = [t["identifier"] for t in r.get("supportedDeviceTypes", []) if t["name"].startswith("iPhone")] +print(r["identifier"], want[1] or types[-1])' "$RUNTIME" "$DEVTYPE" +} + +snapstore() { # snapstore TOOL NAME UDID : the host-side disabled.plist, as sorted disabled labels + local tool="$1" name="$2" u="$3" f json last="" prev="" miss=0 settled=0 i note="" + f="$STORE_ROOT/com.apple.CoreSimulator.SimDevice.$u/disabled.plist" + mkdir -p "$OUT/$tool/mutating" + # launchd_sim owns this file and rewrites it asynchronously around boot and live + # disable/enable calls (an undocumented CoreSimulator detail; see + # docs/parity-check.md), so a read right after a command returns can catch it + # mid-rewrite: truncated, missing, or parseable yet incomplete. Trust a read only + # after two identical ones in a row. A file that stays absent for ~1.5s counts as + # genuinely absent. If neither happens in ~4.5s, say so in the step's stderr so + # the comparison fails loudly instead of recording a coin-flip as a result. + json="" + for i in $(seq 1 30); do + if [ -f "$f" ]; then + json="$(plutil -convert json -o - "$f" 2>/dev/null)" + miss=0 + else + json="" + miss=$((miss + 1)) + fi + [ -n "$json" ] && last="$json" + if [ -n "$json" ] && [ "$json" = "$prev" ]; then settled=1; break; fi + if [ "$miss" -ge 10 ]; then settled=1; break; fi + prev="$json" + sleep 0.15 + done + if [ "$settled" = 1 ] && [ "$miss" -ge 10 ]; then json=""; else json="$last"; fi + [ "$settled" = 1 ] || note="store did not settle within 30 reads" + if [ -n "$json" ]; then printf '%s' "$json"; else echo '{}'; fi | + python3 -I -c ' +import json, sys +d = json.load(sys.stdin) +print(json.dumps({"disabled": sorted(k for k, v in d.items() if v is True), + "explicitly_enabled": sorted(k for k, v in d.items() if v is False)}, indent=1))' \ + >"$OUT/$tool/mutating/$name.store.raw.out" + printf '%s' "$note" >"$OUT/$tool/mutating/$name.store.raw.err" + echo 0 >"$OUT/$tool/mutating/$name.store.code" + normalize "$OUT/$tool/mutating/$name.store.raw.out" >"$OUT/$tool/mutating/$name.store.out" + normalize "$OUT/$tool/mutating/$name.store.raw.err" >"$OUT/$tool/mutating/$name.store.err" +} + +reset_device() { + xcrun simctl shutdown "$DEV" >/dev/null 2>&1 + xcrun simctl erase "$DEV" >/dev/null 2>&1 + rm -rf "$STORE_ROOT/com.apple.CoreSimulator.SimDevice.$DEV" +} + +mutating_steps() { # mutating_steps TOOL + local tool="$1" d="$OUT/$1/mutating" bt="--boot-timeout 20m" clone before + reset_device + snapstore "$tool" 00-stock "$DEV" + cap "$tool" "$d" 01-on exact $bt on "$DEV" + cap "$tool" "$d" 01-status exact status "$DEV" --json + cap "$tool" "$d" 01-verify exact verify "$DEV" --json + snapstore "$tool" 01-on "$DEV" + cap "$tool" "$d" 02-off exact $bt off "$DEV" + cap "$tool" "$d" 02-status exact status "$DEV" --json + snapstore "$tool" 02-off "$DEV" + cap "$tool" "$d" 03-on-except exact $bt on "$DEV" --except search,store + cap "$tool" "$d" 03-verify exact verify "$DEV" --except search,store --json + snapstore "$tool" 03-on-except "$DEV" + cap "$tool" "$d" 04-on-keep exact $bt on "$DEV" --keep com.apple.apsd + cap "$tool" "$d" 04-verify exact verify "$DEV" --keep com.apple.apsd --json + snapstore "$tool" 04-on-keep "$DEV" + printf '{ "name": "parity", "except": ["photos"], "keep": ["com.apple.apsd"] }\n' >"$OUT/profile.json" + cap "$tool" "$d" 05-on-profile exact $bt on "$DEV" --profile "$OUT/profile.json" + cap "$tool" "$d" 05-verify exact verify "$DEV" --profile "$OUT/profile.json" --json + snapstore "$tool" 05-on-profile "$DEV" + cap "$tool" "$d" 06-off exact $bt off "$DEV" + cap "$tool" "$d" 07-on-noreboot exact $bt on "$DEV" --no-reboot + cap "$tool" "$d" 07-status exact status "$DEV" --json + # No store snapshot yet: after live launchctl calls the host-side disabled.plist + # can lag the guest's real state for a long time. It is snapshotted after the + # shutdown below, when launchd_sim has had to flush what it persists. + cap "$tool" "$d" 08-enable exact enable "$DEV" icloud --json + cap "$tool" "$d" 08-status exact status "$DEV" --dropped --json + cap "$tool" "$d" 09-disable exact disable "$DEV" icloud --json + cap "$tool" "$d" 09-status exact status "$DEV" --dropped --json + cap "$tool" "$d" 10-disable-label exact disable "$DEV" com.apple.apsd --json + cap "$tool" "$d" 10-disable-unmanaged exact disable "$DEV" com.apple.backboardd --json + cap "$tool" "$d" 11-doctor exact doctor "$DEV" --requires push,storekit,universal-links --json + cap "$tool" "$d" 12-measure shape measure "$DEV" --json + cap "$tool" "$d" 13-shutdown exact shutdown "$DEV" --json + snapstore "$tool" 13-shutdown "$DEV" + cap "$tool" "$d" 13-disable-notbooted exact disable "$DEV" icloud --json + cap "$tool" "$d" 14-size shape size "$DEV" --json + cap "$tool" "$d" 14-disk-plan shape disk-plan "$DEV" --json + cap "$tool" "$d" 15-rename exact rename "$DEV" "parity-renamed" --json + # clone: the clone's UDID differs per run; both runs normalize it to . + cap "$tool" "$d" 16-on-before-clone exact $bt on "$DEV" + cap "$tool" "$d" 16-shutdown exact shutdown "$DEV" --json + before="$(xcrun simctl list devices -j)" + cap "$tool" "$d" 17-clone exact $bt clone "$DEV" parity-clone --json + clone="$(python3 -I -c 'import json,sys;print(json.load(sys.stdin).get("udid",""))' <"$d/17-clone.raw.out" 2>/dev/null)" + if is_new_clone "$clone" "$before" parity-clone; then + EXTRA+=("$clone") + snapstore "$tool" 17-clone "$clone" + cap "$tool" "$d" 18-repair-clone exact repair-clone "$DEV" "$clone" --json + cap "$tool" "$d" 19-delete-clone exact delete "$clone" --json + elif [ -n "$clone" ]; then + echo "parity: refusing to track clone UDID '$clone' (not new, or not named parity-clone); nothing deleted" >&2 + fi + cap "$tool" "$d" 20-erase exact erase "$DEV" --json + snapstore "$tool" 20-erase "$DEV" +} + +if [ "$MUTATING" = 1 ]; then + echo "== mutating commands on a scratch simulator" + read -r RUNTIME DEVTYPE < <(pick_runtime_and_type) + [ -n "$DEVTYPE" ] || { echo "parity: no usable runtime" >&2; exit 2; } + DEV="$(xcrun simctl create "simslim-parity-$$" "$DEVTYPE" "$RUNTIME")" || exit 2 + is_udid "$DEV" || { echo "parity: simctl create returned '$DEV'" >&2; exit 2; } + echo "scratch simulator: $DEV ($RUNTIME)" + mutating_steps go + mutating_steps swift + for f in "$OUT"/go/mutating/*.code; do + n="$(basename "$f" .code)" + compare_one mutating "$n" + done + # Identical failures compare equal, so list the steps that failed in either tool: + # a step that fails everywhere usually means the script, not the tools, is wrong. + echo " non-zero exits (informational; 10-disable-unmanaged and 13-disable-notbooted are deliberate errors):" + for tool in go swift; do + for f in "$OUT/$tool"/mutating/*.code; do + [ -e "$f" ] || continue + [ "$(cat "$f")" != 0 ] && echo " $tool $(basename "$f" .code): $(head -c 100 "${f%.code}.err" | tr '\n' ' ')" + done + done +fi + +# --- phase 3: watch events -------------------------------------------------- +watch_run() { # watch_run TOOL : kinds of events for a simulator created and booted under watch + local tool="$1" d="$OUT/$1/watch" log w pid i + mkdir -p "$d" + log="$d/events.raw.out" + : >"$log" + "$(bin_of "$tool")" watch --json >"$log" 2>"$d/events.raw.err" &2; return 1; } + EXTRA+=("$w") + sleep 5 + xcrun simctl boot "$w" >/dev/null 2>&1 + for i in $(seq 1 48); do + grep -q '"event":"slimmed"' "$log" && break + sleep 5 + done + xcrun simctl shutdown "$w" >/dev/null 2>&1 + sleep 10 + kill -INT "$pid" 2>/dev/null + wait "$pid" 2>/dev/null + WATCH_PID="" + echo 0 >"$d/events.code" + DEV="$w" normalize "$log" --kinds >"$d/events.out" + : >"$d/events.err" + xcrun simctl delete "$w" >/dev/null 2>&1 +} + +if [ "$WATCH" = 1 ]; then + echo "== watch --json events (slow)" + if [ -z "$RUNTIME" ] || [ -z "$DEVTYPE" ]; then read -r RUNTIME DEVTYPE < <(pick_runtime_and_type); fi + [ -n "$DEVTYPE" ] || { echo "parity: no usable runtime" >&2; exit 2; } + # watch slims every shut-down simulator on start; --set restricts nothing, so this + # touches every simulator you own, not just the scratch ones. + if [ "$YES" != 1 ]; then + [ -t 0 ] || { echo "parity: --watch slims every shut-down simulator; pass --yes to allow it" >&2; exit 2; } + printf 'watch will slim EVERY shut-down simulator on this Mac (both CLIs). Type yes to continue: ' + read -r answer + [ "$answer" = yes ] || { echo "parity: aborted" >&2; exit 2; } + fi + watch_run go + watch_run swift + compare_one watch events +fi + +echo +echo "compared $TOTAL, differing $DIFFS" +if [ "$DIFFS" -gt 0 ]; then + echo "see $REPORT" + exit 1 +fi diff --git a/scripts/verify-deps.sh b/scripts/verify-deps.sh new file mode 100755 index 0000000..bdc00db --- /dev/null +++ b/scripts/verify-deps.sh @@ -0,0 +1,288 @@ +#!/bin/zsh +# Verifies that the Swift port uses no third-party code and no network. +# Read-only except for building into swift/.build. Run it by hand: +# +# make verify-deps # all checks +# scripts/verify-deps.sh --update-libs # rewrite swift/expected-libs.txt, then review the diff +# scripts/verify-deps.sh --no-binary # source-level checks only (no build) +# +# Exit status is non-zero if any check fails. +set -euo pipefail + +ROOT_DIR="$(cd "$(dirname "$0")/.." && pwd)" +SWIFT_DIR="$ROOT_DIR/swift" +GUI_DIR="$ROOT_DIR/gui" +SELF="scripts/verify-deps.sh" +EXPECTED_LIBS="$SWIFT_DIR/expected-libs.txt" + +UPDATE_LIBS=0 +CHECK_BINARY=1 +for arg in "$@"; do + case "$arg" in + --update-libs) UPDATE_LIBS=1 ;; + --no-binary) CHECK_BINARY=0 ;; + *) echo "unknown argument: $arg" >&2; exit 64 ;; + esac +done + +# Never name a zsh loop variable `path`: it is tied to PATH. +for tool in find grep awk sort diff otool nm strings swift; do + command -v "$tool" >/dev/null 2>&1 || { print -u2 -- "verify-deps: required tool not found: $tool"; exit 70 } +done + +# grep that treats "no match" (1) as empty output but any real error (>1) as fatal, +# so a broken search can never read as a clean result. +hits() { + local rc=0 + grep "$@" || rc=$? + if (( rc > 1 )); then + print -u2 -- "verify-deps: grep failed (status $rc): grep $*" + exit 70 + fi + return 0 +} + +FAILED=0 +fail() { print -u2 -- " FAIL: $*"; FAILED=1 } +ok() { print -- " ok: $*" } +section() { print -- "\n[$1]" } + +# Modules each tree may import. Everything here ships with Xcode. +ALLOWED_SOURCES=(Foundation Darwin Dispatch SimSlimKit SimSlimCLI) +ALLOWED_TESTS=(Foundation Darwin Dispatch SimSlimKit SimSlimCLI TestSupport XCTest Testing) +ALLOWED_GUI=(Foundation AppKit SwiftUI) + +# Prints ": " for each import in the given directory. +list_imports() { + local dir="$1" file + [[ -d "$dir" ]] || return 0 + find "$dir" -name '*.swift' -not -path '*/.build/*' | sort | while read -r file; do + awk -v f="${file#$ROOT_DIR/}" ' + /^[[:space:]]*(@[A-Za-z_]+(\([^)]*\))?[[:space:]]+)*((public|internal|package|private|fileprivate)[[:space:]]+)?import[[:space:]]/ { + n = split($0, w, /[[:space:]]+/) + for (i = 1; i <= n; i++) if (w[i] == "import") { j = i + 1; break } + if (w[j] ~ /^(struct|class|enum|protocol|typealias|func|var|let)$/) j++ + split(w[j], m, ".") + print f ": " m[1] + }' "$file" + done +} + +check_imports() { + local label="$1" dir="$2"; shift 2 + local -a allowed=("$@") + local line module bad=0 + while read -r line; do + [[ -n "$line" ]] || continue + module="${line##*: }" + if (( ${allowed[(Ie)$module]} == 0 )); then + fail "$label imports '$module' (${line%%:*}); allowed: ${allowed[*]}" + bad=1 + fi + done < <(list_imports "$dir") + (( bad )) || ok "$label imports only: ${allowed[*]}" +} + +# ------------------------------------------------------------------ canary +# Prove the searches can see the code: these patterns must match known lines. +section "0. Canary (the searches can see the code)" +[[ -n "$(hits -rn 'enum Executable' "$SWIFT_DIR/Sources")" ]] \ + && ok "found enum Executable in swift/Sources" || fail "canary: enum Executable not found" +[[ -n "$(hits -rn 'import Foundation' "$SWIFT_DIR/Sources")" ]] \ + && ok "found import Foundation in swift/Sources" || fail "canary: no imports found" +[[ -n "$(list_imports "$GUI_DIR")" ]] \ + && ok "list_imports sees the gui imports" || fail "canary: list_imports returned nothing for gui" +(( FAILED )) && { print -u2 -- "verify-deps: canary failed, aborting"; exit 70 } + +# ---------------------------------------------------------------- 1 packages +section "1. No packages, vendored code, or plugins" +PKG="$SWIFT_DIR/Package.swift" +if [[ ! -f "$PKG" ]]; then + fail "missing $PKG" +else + pkg_hits="$(hits -nE '\.package\(|\.binaryTarget|\.plugin|\.systemLibrary|unsafeFlags|cSettings|cxxSettings|linkerSettings|path:[[:space:]]*"(\.\.|/)' "$PKG")" + if [[ -n "$pkg_hits" ]]; then + print -u2 -- "$pkg_hits" + fail "Package.swift declares a package, binary target, plugin, or system library" + else + ok "Package.swift declares no packages, binary targets, or plugins" + fi +fi +# Only Swift may be compiled: a C/ObjC/C++ target would escape every Swift-only check. +foreign="$(find "$SWIFT_DIR" -path "$SWIFT_DIR/.build" -prune -o -type f \ + \( -name '*.c' -o -name '*.h' -o -name '*.m' -o -name '*.mm' -o -name '*.cpp' -o -name '*.cc' \ + -o -name '*.hpp' -o -name '*.s' -o -name '*.S' -o -name '*.modulemap' -o -name '*.a' \ + -o -name '*.dylib' -o -name '*.framework' -o -name '*.xcframework' \) -print)" +if [[ -n "$foreign" ]]; then + print -u2 -- "$foreign" + fail "non-Swift source or binary under swift/ (above)" +else + ok "swift/ contains only Swift sources" +fi +artifacts_ok=1 +for artifact in "$SWIFT_DIR/Package.resolved" "$SWIFT_DIR/Packages" "$SWIFT_DIR/vendor" \ + "$ROOT_DIR/Package.swift" "$ROOT_DIR/Package.resolved" \ + "$ROOT_DIR/Podfile" "$ROOT_DIR/Cartfile"; do + if [[ -e "$artifact" ]]; then fail "unexpected dependency artifact: ${artifact#$ROOT_DIR/}"; artifacts_ok=0; fi +done +# SwiftPM creates an empty checkouts directory even with no dependencies. +if [[ -d "$SWIFT_DIR/.build/checkouts" && -n "$(ls -A "$SWIFT_DIR/.build/checkouts")" ]]; then + fail "swift/.build/checkouts is not empty: SwiftPM fetched something"; artifacts_ok=0 +fi +(( artifacts_ok )) && ok "no Package.resolved, checkouts, Packages/, vendor/, Podfile, or Cartfile" + +# ---------------------------------------------------------------- 2 imports +section "2. Imports are on the allowlist" +check_imports "swift/Sources" "$SWIFT_DIR/Sources" "${ALLOWED_SOURCES[@]}" +check_imports "swift/Tests" "$SWIFT_DIR/Tests" "${ALLOWED_TESTS[@]}" +check_imports "gui" "$GUI_DIR" "${ALLOWED_GUI[@]}" + +# ---------------------------------------------------------------- 3 network +section "3. No network APIs in source" +NET_PATTERN='URLSession|URLRequest|NSURLConnection|NWConnection|NWListener|NWPathMonitor|CFNetwork|CFSocket|CFStream|InputStream|OutputStream|WKWebView|getaddrinfo|socket\(|connect\(|URL\(string:|http://|https://|ftp://' +# The one allowed URL is the plist DOCTYPE's public identifier: a fixed string +# written into a file, never opened. Anything else with a scheme still fails. +APPLE_DTD='http://www.apple.com/DTDs/PropertyList-1.0.dtd' +# The other is the credit line `simslim help` prints, copied from the Go CLI: text +# in Usage.swift that is written to stdout and never opened. Only that exact line +# in that one file is exempt. +HELP_CREDIT='Usage\.swift:[0-9]+: https://github\.com/mobai-app/simslim · by MobAI \(https://mobai\.run\)$' +net_hits="$(hits -rnE "$NET_PATTERN" "$SWIFT_DIR/Sources" "$GUI_DIR" --include='*.swift' \ + | grep -vF "$APPLE_DTD" | grep -vE "$HELP_CREDIT" || true)" +if [[ -n "$net_hits" ]]; then + print -u2 -- "$net_hits" + fail "network-capable API or URL found in source (above)" +else + ok "no URLSession, sockets, Network framework, or URLs in source" +fi + +# Data(contentsOf:) and friends fetch remote URLs too. Only local reads are +# allowed, which means the line must build its URL with fileURLWithPath. +remote_read_hits="$(hits -rnE '(Data|String|NSData|NSString|NSDictionary|NSArray|XMLDocument)\((contentsOf|contentsOfURL):|dataTask|downloadTask' "$SWIFT_DIR/Sources" "$GUI_DIR" --include='*.swift' \ + | hits -v 'fileURLWithPath')" +if [[ -n "$remote_read_hits" ]]; then + print -u2 -- "$remote_read_hits" + fail "contentsOf:/download call that is not a fileURLWithPath read (above)" +else + ok "every contentsOf: read is a local fileURLWithPath" +fi + +# ---------------------------------------------------------------- 4 subprocess +section "4. Subprocesses go through Subprocess.swift only" +SUBPROC="$SWIFT_DIR/Sources/SimSlimKit/Subprocess.swift" +# Only the one real Subprocess.swift is exempt, never a same-named file elsewhere. +outside_subproc() { grep -vF "$SUBPROC:" || true; } +spawn_hits="$(hits -rnE '\bProcess[[:space:]]*(\(|\.run)|NSTask|NSUserUnixTask|posix_spawn|\bpopen\(|\bsystem\(|\bexecv|\bfork\(|/bin/(ba|z)?sh' \ + "$SWIFT_DIR/Sources" --include='*.swift' | outside_subproc)" +if [[ -n "$spawn_hits" ]]; then + print -u2 -- "$spawn_hits" + fail "process spawning outside Subprocess.swift (above)" +else + ok "Process/posix_spawn/popen/system only in Subprocess.swift" +fi +path_hits="$(hits -rnE '"/(usr/(s)?bin|bin|sbin|opt|Applications|Library|System)/' "$SWIFT_DIR/Sources" --include='*.swift' \ + | outside_subproc)" +if [[ -n "$path_hits" ]]; then + print -u2 -- "$path_hits" + fail "hard-coded executable path outside Subprocess.swift (above)" +else + ok "no executable paths outside the Executable enum" +fi +env_hits="$(hits -nE 'getenv|environment\[|\.environment|/usr/bin/env|"PATH"' "$SUBPROC")" +if [[ -n "$env_hits" ]]; then + fail "Subprocess.swift reads the environment or PATH" +else + ok "Subprocess.swift reads no environment and does no PATH lookup" +fi + +# ---------------------------------------------------------------- 7 fetching +section "5. Build files fetch nothing" +fetch_hits="$(cd "$ROOT_DIR" && hits -nE 'curl|wget|git clone|git submodule|http://|https://|brew install|pip install|npm install' \ + swift/Package.swift Makefile scripts/build-app.sh | hits -v '^[^:]*:[0-9]*:[[:space:]]*echo ')" +if [[ -n "$fetch_hits" ]]; then + print -u2 -- "$fetch_hits" + fail "build files reference a download or installer (above)" +else + ok "swift/Package.swift, Makefile, and scripts/build-app.sh fetch nothing" +fi + +# ------------------------------------------------------------ binary checks +if (( CHECK_BINARY )); then + section "6. Release binary" + (cd "$SWIFT_DIR" && swift build -c release >/dev/null 2>&1) || { fail "swift build -c release failed"; } + BIN="$SWIFT_DIR/.build/release/simslim" + if [[ ! -x "$BIN" ]]; then + fail "release binary not found at ${BIN#$ROOT_DIR/}" + else + # Linked libraries must all be system libraries. + libs="$(otool -L "$BIN" | tail -n +2 | awk '{print $1}' | sort)" + non_system="$(print -r -- "$libs" | hits -vE '^(/usr/lib/|/System/Library/)')" + if [[ -n "$non_system" ]]; then + print -u2 -- "$non_system" + fail "binary links a non-system library (above)" + else + ok "every linked library is under /usr/lib or /System/Library" + fi + if (( UPDATE_LIBS )); then + print -r -- "$libs" > "$EXPECTED_LIBS" + ok "rewrote ${EXPECTED_LIBS#$ROOT_DIR/} (review the diff)" + elif [[ -f "$EXPECTED_LIBS" ]]; then + if diff <(print -r -- "$libs") "$EXPECTED_LIBS" >/dev/null; then + ok "linked libraries match swift/expected-libs.txt" + else + diff <(print -r -- "$libs") "$EXPECTED_LIBS" >&2 || true + fail "linked libraries differ from swift/expected-libs.txt" + fi + else + fail "swift/expected-libs.txt is missing (run with --update-libs, then review it)" + fi + + # Undefined symbols that would indicate networking. + NET_SYMBOLS='NSURLSession|NSURLConnection|CFNetwork|nw_connection|nw_listener|_getaddrinfo|_gethostbyname|_getifaddrs|_sendto|_socket$|_connect$|_bind$' + net_syms="$(nm -u "$BIN" | hits -E "$NET_SYMBOLS")" + if [[ -n "$net_syms" ]]; then + print -u2 -- "$net_syms" + fail "binary imports network symbols (above)" + else + ok "no network symbols among the binary's imports" + fi + + # Test-only hooks must never ship. By convention they are named SIMSLIM_TEST_*. + test_hooks="$(strings -a "$BIN" | hits 'SIMSLIM_TEST_')" + if [[ -n "$test_hooks" ]]; then + fail "release binary contains a SIMSLIM_TEST_ hook" + else + ok "no SIMSLIM_TEST_ hooks in the release binary" + fi + + # Behavior check: the binary still works with all network access denied. + if command -v sandbox-exec >/dev/null 2>&1; then + # Only commands that never touch a simulator are exercised here. + sandboxed() { sandbox-exec -p '(version 1)(allow default)(deny network*)' "$BIN" "$@" 2>&1; } + if out="$(sandboxed --version)"; then + ok "runs with network denied: $out" + else + fail "binary failed under sandbox-exec with network denied: $out" + fi + if out="$(sandboxed profiles --json)" && [[ "$out" == *'"id" : "widgets"'* ]]; then + ok "profiles --json works with network denied" + else + fail "profiles --json failed under sandbox-exec with network denied" + fi + if out="$(sandboxed doctor --list)" && [[ "$out" == *"com.apple.apsd"* ]]; then + ok "doctor --list works with network denied" + else + fail "doctor --list failed under sandbox-exec with network denied" + fi + else + print -- " skip: sandbox-exec not available" + fi + fi +fi + +print -- "" +if (( FAILED )); then + print -u2 -- "verify-deps: FAILED" + exit 1 +fi +print -- "verify-deps: all checks passed" diff --git a/service_descriptions.go b/service_descriptions.go deleted file mode 100644 index 9b7cf57..0000000 --- a/service_descriptions.go +++ /dev/null @@ -1,221 +0,0 @@ -package simslim - -// serviceDescriptionByLabel gives the GUI a short, user-facing explanation for -// every daemon that can be controlled individually. These descriptions explain -// the service's primary role without implying that private Apple daemons have a -// stable public API or an isolated memory cost. -var serviceDescriptionByLabel = map[string]string{ - // Widgets & Wallpaper - "com.apple.PosterBoard": "Renders Home and Lock Screen wallpaper scenes.", - "com.apple.chronod": "Refreshes widgets and complications on schedule.", - "com.apple.liveactivitiesd": "Updates Live Activities and Dynamic Island content.", - - // Siri & Intelligence - "com.apple.assistant_cdmd": "Routes commands and intents submitted to Siri.", - "com.apple.assistant_service": "Provides supporting services for Siri requests.", - "com.apple.siriactionsd": "Executes Siri actions and App Intents.", - "com.apple.siriinferenced": "Runs Siri inference and intent predictions.", - "com.apple.siriknowledged": "Maintains knowledge and context used by Siri.", - "com.apple.sirittsd": "Generates Siri's spoken responses.", - "com.apple.siri.context.service": "Builds device context for Siri requests.", - "com.apple.siri.acousticsignature": "Processes acoustic signatures for voice features.", - "com.apple.corespeechd": "Provides speech recognition and voice-trigger services.", - "com.apple.voiced": "Manages system voices and speech assets.", - "com.apple.voicebankingd": "Supports Personal Voice and voice banking.", - "com.apple.speechmodeltrainingd": "Adapts on-device speech recognition models.", - "com.apple.intelligenceplatformd": "Coordinates Apple Intelligence services.", - "com.apple.intelligencecontextd": "Collects local context for intelligence features.", - "com.apple.intelligenceflowd": "Orchestrates Apple Intelligence workflows.", - "com.apple.intelligencetasksd": "Runs background Apple Intelligence tasks.", - "com.apple.generativeexperiencesd": "Supports generative intelligence experiences.", - "com.apple.knowledgeconstructiond": "Builds on-device knowledge used by suggestions.", - "com.apple.naturallanguaged": "Performs natural-language analysis.", - "com.apple.textunderstandingd": "Extracts meaning and entities from text.", - "com.apple.modelcatalogd": "Tracks machine-learning models available to the system.", - "com.apple.modelmanagerd": "Downloads and manages on-device models.", - "com.apple.mlhostd": "Hosts system machine-learning services.", - "com.apple.mlruntimed": "Executes on-device machine-learning models.", - "com.apple.suggestd": "Generates system suggestions and predictions.", - "com.apple.parsecd": "Provides network-backed Siri and Spotlight suggestions.", - "com.apple.parsec-fbf": "Collects feedback for Siri and Spotlight suggestions.", - "com.apple.proactiveeventtrackerd": "Tracks events used by proactive suggestions.", - - // Spotlight & Search - "com.apple.searchd": "Coordinates system search queries.", - "com.apple.searchtoold": "Runs helper tasks for system search.", - "com.apple.spotlightknowledged": "Builds knowledge used by Spotlight results.", - "com.apple.spotlightknowledged.updater": "Refreshes Spotlight's knowledge data.", - "com.apple.corespotlightservice": "Indexes and searches app-provided content.", - - // iCloud & Apple Account - "com.apple.appleaccountd": "Maintains Apple Account state on the device.", - "com.apple.appleaccounttransparencyd": "Checks Apple Account security records.", - "com.apple.appleidsetupd": "Handles Apple Account setup workflows.", - "com.apple.akd": "Provides Apple Account authentication tokens.", - "com.apple.amsaccountsd": "Manages App Store and media account state.", - "com.apple.amsengagementd": "Handles App Store and media engagement messages.", - "com.apple.amsondevicestoraged": "Stores Apple media-service data on the device.", - "com.apple.cloudd": "Synchronizes CloudKit databases and records.", - "com.apple.cloudphotod": "Synchronizes the iCloud Photos library.", - "com.apple.ckdiscretionaryd": "Schedules non-urgent CloudKit transfers.", - "com.apple.cloudsettingssyncagent": "Synchronizes supported system settings through iCloud.", - "com.apple.bird": "Synchronizes iCloud Drive files.", - "com.apple.syncdefaultsd": "Synchronizes supported preferences between devices.", - "com.apple.cdpd": "Handles iCloud data-protection setup and recovery.", - "com.apple.sosd": "Synchronizes iCloud Keychain secure items.", - "com.apple.SecureBackupDaemon": "Handles secure backup and account recovery data.", - "com.apple.TrustedPeersHelper": "Maintains trusted peers for iCloud Keychain.", - "com.apple.protectedcloudstorage.protectedcloudkeysyncing": "Synchronizes protected cloud encryption keys.", - "com.apple.icloudmailagent": "Runs background services for iCloud Mail.", - "com.apple.icloudsubscriptionoptimizerd": "Evaluates iCloud storage subscription recommendations.", - "com.apple.communicationtrustd": "Maintains communication trust and safety state.", - - // App Store, Push & Media - "com.apple.appstored": "Installs and updates apps from the App Store.", - "com.apple.appstorecomponentsd": "Provides background components used by the App Store.", - "com.apple.apsd": "Receives Apple Push Notification service messages.", - "com.apple.itunescloudd": "Synchronizes purchased and cloud media libraries.", - "com.apple.itunesstored": "Handles media-store accounts and purchases.", - "com.apple.storekitd": "Processes StoreKit products and transactions.", - "com.apple.videosubscriptionsd": "Manages video subscriptions and TV providers.", - "com.apple.assetsubscriptiond": "Manages subscribed media assets and downloads.", - "com.apple.musicd": "Runs background Music library and playback services.", - - // Mail, Calendar & Contacts - "com.apple.email.maild": "Fetches, indexes, and sends Mail account data.", - "com.apple.exchangesyncd": "Synchronizes Microsoft Exchange account data.", - "com.apple.dataaccess.dataaccessd": "Synchronizes CalDAV, CardDAV, and related accounts.", - "com.apple.calaccessd": "Provides access to Calendar event data.", - "com.apple.remindd": "Stores and synchronizes reminders.", - "com.apple.contactsd": "Provides access to the Contacts database.", - "com.apple.contacts.postersyncd": "Synchronizes Contact Posters.", - "com.apple.peopled": "Builds people and relationship suggestions.", - - // Safari Sync & Web Services - "com.apple.SafariBookmarksSyncAgent": "Synchronizes Safari bookmarks through iCloud.", - "com.apple.Safari.History": "Maintains and synchronizes Safari history.", - "com.apple.Safari.passwordbreachd": "Checks saved passwords for known data leaks.", - "com.apple.Safari.SafeBrowsing.Service": "Checks sites against unsafe browsing data.", - "com.apple.safarifetcherd": "Fetches Safari content in the background.", - "com.apple.WebBookmarks.webbookmarksd": "Maintains web bookmarks, clips, and Reading List data.", - "com.apple.webkit.adattributiond": "Processes privacy-preserving web ad attribution.", - "com.apple.webkit.webpushd": "Receives push notifications for websites.", - "com.apple.webprivacyd": "Maintains Safari privacy-protection data.", - "com.apple.swcd": "Matches universal links with installed apps.", - - // Family & Screen Time - "com.apple.familycircled": "Maintains Family Sharing membership and state.", - "com.apple.FamilyControlsAgent": "Applies parental and Family Controls restrictions.", - "com.apple.familynotification": "Delivers Family Sharing invitations and notices.", - "com.apple.askpermissiond": "Handles Ask to Buy permission requests.", - "com.apple.asktod": "Routes family approval prompts and responses.", - "com.apple.ScreenTimeAgent": "Enforces Screen Time limits and reports usage.", - "com.apple.ScreenTimeSettingsAgent": "Connects Screen Time data to Settings.", - "com.apple.UsageTrackingAgent": "Tracks app and website usage duration.", - - // Health, Home & Fitness - "com.apple.healthd": "Stores and serves HealthKit data.", - "com.apple.healthappd": "Runs background tasks for the Health app.", - "com.apple.healthcontentd": "Provides educational and recommended health content.", - "com.apple.healtheventsd": "Processes health events and related notifications.", - "com.apple.healthrecordsd": "Synchronizes clinical health records.", - "com.apple.finhealthd": "Analyzes Wallet transactions and financial-health data.", - "com.apple.homed": "Manages HomeKit accessories, rooms, and automations. Kept enabled on watchOS.", - "com.apple.homeeventsd": "Processes HomeKit events and automation triggers.", - "com.apple.fitcore": "Runs Apple Fitness content and background services.", - "com.apple.fitcore.session": "Manages active Apple Fitness sessions.", - "com.apple.fitnesscoachingd": "Provides Fitness coaching recommendations.", - "com.apple.fitnessintelligenced": "Generates personalized Fitness insights.", - "com.apple.activityawardsd": "Tracks Activity awards and achievements.", - "com.apple.activitysharingd": "Synchronizes shared Activity and Fitness data.", - - // Photos & Media Analysis - "com.apple.photoanalysisd": "Analyzes photos for scenes, people, and search.", - "com.apple.photosface": "Performs face detection for the Photos library.", - "com.apple.mediaanalysisd": "Analyzes image, video, and audio content.", - "com.apple.mediaanalysisd.service": "Runs isolated media-analysis work.", - "com.apple.mediastream.mstreamd": "Synchronizes shared and streamed photo content.", - "com.apple.medialibraryd": "Maintains the system media library database.", - "com.apple.assetsd": "Provides access to Photos library assets.", - "com.apple.assetsd.nebulad": "Handles cloud-backed Photos asset transfers.", - - // News, Weather, Maps & Games - "com.apple.newsd": "Downloads and refreshes Apple News content.", - "com.apple.weatherd": "Fetches forecasts and weather data.", - "com.apple.Maps.mapssyncd": "Synchronizes Maps favorites, guides, and history.", - "com.apple.Maps.mapspushd": "Receives background updates for Maps.", - "com.apple.Maps.geocorrectiond": "Improves and corrects map location data.", - "com.apple.maps.destinationd": "Predicts and maintains suggested destinations.", - "com.apple.MapKit.SnapshotService": "Renders static map snapshots for apps.", - "com.apple.jetpackassetd": "Downloads assets used by Apple content apps.", - "com.apple.tipsd": "Selects and refreshes content for the Tips app.", - "com.apple.gamesaved": "Synchronizes supported game save data.", - "com.apple.GameController.gamecontrollerd": "Discovers controllers and routes their input.", - - // Messaging & FaceTime - "com.apple.identityservicesd": "Maintains identities used by iMessage and FaceTime.", - "com.apple.ids_simd": "Provides simulator support for Apple identity services.", - "com.apple.imautomatichistorydeletionagent": "Removes Messages history according to retention settings.", - "com.apple.imcore.imtransferagent": "Transfers Messages attachments and media.", - "com.apple.imdpersistence.IMDPersistenceAgent": "Stores Messages conversations and metadata.", - "com.apple.facetimemessagestored": "Stores FaceTime messages and related data.", - "com.apple.telephonyutilities.callservicesd": "Coordinates FaceTime and system call state.", - - // Sharing & Device Connectivity - "com.apple.rapportd": "Discovers nearby devices for Continuity features.", - "com.apple.companiond": "Coordinates communication with paired companion devices.", - "com.apple.carkitd": "Provides CarPlay connection and vehicle services.", - "com.apple.wcd": "Handles connectivity with a paired Apple Watch.", - "com.apple.tvremoted": "Provides Apple TV discovery and remote control.", - "com.apple.avatarsd": "Maintains avatars and Memoji assets.", - "com.apple.stickersd": "Maintains sticker packs and recently used stickers.", - "com.apple.sociallayerd": "Supports social sharing and activity features.", - "com.apple.announced": "Supports announced notifications and audio messages.", - "com.apple.navd": "Coordinates background navigation state.", - "com.apple.findmy.findmylocated": "Provides device location data to Find My.", - - // Ads, Diagnostics & Telemetry - "com.apple.ap.adprivacyd": "Maintains advertising privacy preferences and state.", - "com.apple.ap.promotedcontentd": "Fetches and manages promoted Apple content.", - "com.apple.diagnosticextensionsd": "Runs system diagnostic data collectors.", - "com.apple.feedbackd": "Collects and submits system feedback reports.", - "com.apple.rtcreportingd": "Reports diagnostics for real-time communications.", - "com.apple.securityuploadd": "Uploads security and trust telemetry.", - "com.apple.geoanalyticsd": "Collects Maps and location-quality analytics.", - "com.apple.triald": "Manages system feature experiments and configurations.", - "com.apple.followupd": "Schedules account and setup follow-up notices.", - "com.apple.purplebuddy.budd": "Maintains Setup Assistant completion state.", - "com.apple.devicecheckd": "Provides DeviceCheck and app-attestation services.", - - // Device Management - "com.apple.remotemanagementd": "Applies declarative device management configurations.", - "com.apple.RemoteManagementAgent": "Applies per-user declarative management configurations.", - "com.apple.managedassetsd": "Downloads assets referenced by management declarations.", - - // Other Background Services - "com.apple.financed": "Provides Wallet transaction and finance services.", - "com.apple.passd": "Manages Wallet passes and Apple Pay state.", - "com.apple.merchantd": "Looks up merchant details for Wallet transactions.", - "com.apple.coreidvd": "Manages supported digital identity credentials.", - "com.apple.businessservicesd": "Supports Apple business messaging and services.", - "com.apple.deviceaccessd": "Coordinates app access to supported accessories.", - "com.apple.replicatord": "Replicates supported system data between services.", - "com.apple.linkd": "Indexes App Intents and shortcut suggestions.", - "com.apple.ind": "Receives background iCloud notifications.", - "com.apple.storagedatad": "Calculates storage usage shown by the system.", - "com.apple.StatusKitAgent": "Shares Focus, presence, and status between devices.", - "com.apple.countryd": "Determines regional availability for system features.", - "com.apple.mobileassetd": "Downloads and manages system asset packages. Kept enabled on visionOS.", - "com.apple.managedconfiguration.passcodenagd": "Enforces managed passcode requirements.", - "com.apple.accessibility.axassetsd": "Downloads accessibility assets such as speech voices.", - "com.apple.ClipServices.clipserviced": "Downloads, launches, and manages App Clips.", -} - -func init() { - for i := range Categories { - Categories[i].ServiceDescriptions = make(map[string]string, len(Categories[i].Labels)) - for _, label := range Categories[i].Labels { - Categories[i].ServiceDescriptions[label] = serviceDescriptionByLabel[label] - } - } -} diff --git a/simctl.go b/simctl.go deleted file mode 100644 index e70f269..0000000 --- a/simctl.go +++ /dev/null @@ -1,675 +0,0 @@ -package simslim - -import ( - "context" - "encoding/json" - "errors" - "fmt" - "os/exec" - "sort" - "strings" - "sync" - "time" - "unicode" - "unicode/utf8" -) - -const ShutdownTimeout = 30 * time.Second - -// BootTimeout bounds a full boot-and-reconfigure (boots twice on a first slim); a -// var, not a const, so `--boot-timeout` / SIMSLIM_BOOT_TIMEOUT can raise it for CI. -var BootTimeout = 10 * time.Minute - -// Device is a simulator as reported by `simctl list`. -type Device struct { - UDID string `json:"udid"` - Name string `json:"name"` - State string `json:"state"` // "Booted" or "Shutdown" - Platform string `json:"platform"` // "iOS", "tvOS", "watchOS", or "visionOS" - OSVersion string `json:"osVersion"` - Set string `json:"set"` - DataPath string `json:"-"` - RuntimeID string `json:"-"` // e.g. com.apple.CoreSimulator.SimRuntime.iOS-26-5; leads to the RuntimeRoot's job plists -} - -// PlatformName preserves the iOS default for callers constructing Device values -// without platform metadata (as they did before multi-platform support). -func (d Device) PlatformName() string { - if d.Platform == "" { - return "iOS" - } - return d.Platform -} - -// RuntimeName is the platform and version shown in human-readable output. -func (d Device) RuntimeName() string { - return d.PlatformName() + " " + d.OSVersion -} - -type deviceSetInfo struct { - token string // "" for the default set; otherwise passed to `simctl --set` - name string -} - -// extraDeviceSets are sets named explicitly with --set -var extraDeviceSets []deviceSetInfo - -func knownDeviceSets() []deviceSetInfo { - sets := []deviceSetInfo{ - {token: "", name: "default"}, - {token: "testing", name: "testing"}, - } - return append(sets, extraDeviceSets...) -} - -// registerDeviceSet adds a --set value to the scanned sets -// ignoring any that duplicate an already-known token. -func RegisterDeviceSet(value string) { - for _, set := range knownDeviceSets() { - if set.token == value { - return - } - } - extraDeviceSets = append(extraDeviceSets, deviceSetInfo{token: value, name: value}) -} - -// ExtraDeviceSetTokens returns the tokens registered with RegisterDeviceSet, -// beyond the well-known default and testing sets. -func ExtraDeviceSetTokens() []string { - var tokens []string - for _, set := range extraDeviceSets { - tokens = append(tokens, set.token) - } - return tokens -} - -// ResetDeviceSets drops every set registered with RegisterDeviceSet. -func ResetDeviceSets() { - extraDeviceSets = nil -} - -func deviceSetToken(name string) string { - for _, set := range knownDeviceSets() { - if set.name == name { - return set.token - } - } - return "" -} - -// simctlArgs targets the named device set; deviceSetToken maps "default" to the -// empty --set token, "testing" and custom paths to themselves. -func simctlArgs(set string, sub ...string) []string { - return simctlArgsForSet(deviceSetToken(set), sub...) -} - -// The --set option must precede the subcommand. -func simctlArgsForSet(token string, sub ...string) []string { - if token == "" { - return append([]string{"simctl"}, sub...) - } - return append([]string{"simctl", "--set", token}, sub...) -} - -func xcrun(ctx context.Context, args ...string) ([]byte, error) { - out, err := exec.CommandContext(ctx, "xcrun", args...).CombinedOutput() - if err != nil { - return out, fmt.Errorf("xcrun %s: %w: %s", strings.Join(args, " "), err, strings.TrimSpace(string(out))) - } - return out, nil -} - -func listDevicesInSet(ctx context.Context, set deviceSetInfo) ([]Device, error) { - out, err := exec.CommandContext(ctx, "xcrun", simctlArgsForSet(set.token, "list", "devices", "-j")...).Output() - if err != nil { - return nil, listError(err) - } - var parsed struct { - Devices map[string][]struct { - UDID string `json:"udid"` - Name string `json:"name"` - State string `json:"state"` - IsAvailable bool `json:"isAvailable"` - DataPath string `json:"dataPath"` - } `json:"devices"` - } - if err := json.Unmarshal(out, &parsed); err != nil { - return nil, fmt.Errorf("parse simctl list: %w", err) - } - var devices []Device - for runtime, ds := range parsed.Devices { - platform, version := parseRuntime(runtime) - if platform == "" { - continue - } - for _, d := range ds { - if !d.IsAvailable { - continue - } - devices = append(devices, Device{UDID: d.UDID, Name: d.Name, State: d.State, Platform: platform, OSVersion: version, Set: set.name, DataPath: d.DataPath, RuntimeID: runtime}) - } - } - return devices, nil -} - -// listError surfaces xcrun's stderr, which Output (kept separate so stdout -// stays clean JSON) parks in ExitError.Stderr; without it a failed listing -// reports only an exit code. -func listError(err error) error { - var exitErr *exec.ExitError - if errors.As(err, &exitErr) { - return formatListError(err, string(exitErr.Stderr)) - } - return fmt.Errorf("simctl list: %w", err) -} - -// formatListError appends stderr to the listing error and, when xcrun cannot -// find simctl at all — xcode-select pointing at the Command Line Tools, which -// do not ship it — says how to select a full Xcode. -func formatListError(err error, stderr string) error { - stderr = strings.TrimSpace(stderr) - if stderr == "" { - return fmt.Errorf("simctl list: %w", err) - } - if strings.Contains(stderr, `unable to find utility "simctl"`) { - return fmt.Errorf("simctl list: %w: %s (simctl ships with full Xcode, not the Command Line Tools; select one with `sudo xcode-select -s /Applications/Xcode.app`)", err, stderr) - } - return fmt.Errorf("simctl list: %w: %s", err, stderr) -} - -// The default set is mandatory; a secondary set that cannot be listed (e.g. it -// does not exist) is skipped rather than failing the whole listing. -func ListDevices(ctx context.Context) ([]Device, error) { - var devices []Device - for _, set := range knownDeviceSets() { - found, err := listDevicesInSet(ctx, set) - if err != nil { - if set.token == "" { - return nil, err - } - continue - } - devices = append(devices, found...) - } - return devices, nil -} - -// parseRuntime accepts only the simulator platforms supported by slimming. -func parseRuntime(runtime string) (platform, version string) { - name, ok := strings.CutPrefix(runtime, "com.apple.CoreSimulator.SimRuntime.") - if !ok { - return "", "?" - } - platform, version, ok = strings.Cut(name, "-") - if !ok || version == "" { - return "", "?" - } - switch platform { - case "iOS", "tvOS", "watchOS": - return platform, strings.ReplaceAll(version, "-", ".") - case "xrOS": - // CoreSimulator still names the visionOS runtime xrOS. - return "visionOS", strings.ReplaceAll(version, "-", ".") - default: - return "", "?" - } -} - -// findDevice locates a simulator by UDID. An empty set searches every known set. -// A non-empty set looks only there, so repeated lookups need not rescan. -func FindDevice(ctx context.Context, udid, set string) (Device, error) { - for _, s := range knownDeviceSets() { - if set != "" && s.name != set { - continue - } - found, err := listDevicesInSet(ctx, s) - if err != nil { - if s.token == "" { - return Device{}, err - } - continue - } - for _, d := range found { - if d.UDID == udid { - return d, nil - } - } - } - return Device{}, fmt.Errorf("no simulator with udid %s", udid) -} - -func NormalizeSimulatorName(name string) (string, error) { - name = strings.TrimSpace(name) - if name == "" { - return "", fmt.Errorf("simulator name cannot be empty") - } - if utf8.RuneCountInString(name) > 128 { - return "", fmt.Errorf("simulator name cannot exceed 128 characters") - } - for _, r := range name { - if unicode.IsControl(r) { - return "", fmt.Errorf("simulator name cannot contain control characters") - } - } - return name, nil -} - -func parseClonedUDID(output []byte) (string, error) { - udid := strings.TrimSpace(string(output)) - if len(udid) != 36 { - return "", fmt.Errorf("simctl clone returned an invalid UDID %q", udid) - } - for i, r := range udid { - if i == 8 || i == 13 || i == 18 || i == 23 { - if r != '-' { - return "", fmt.Errorf("simctl clone returned an invalid UDID %q", udid) - } - continue - } - if !((r >= '0' && r <= '9') || (r >= 'a' && r <= 'f') || (r >= 'A' && r <= 'F')) { - return "", fmt.Errorf("simctl clone returned an invalid UDID %q", udid) - } - } - return udid, nil -} - -// shutdownIfBooted resolves an exact device before any destructive command, -// preventing simctl aliases such as "all" from entering these code paths. It -// returns the device's set so the caller can target its own simctl call there. -func shutdownIfBooted(ctx context.Context, udid string) (set string, wasBooted bool, err error) { - device, err := FindDevice(ctx, udid, "") - if err != nil { - return "", false, err - } - if device.State != "Booted" { - return device.Set, false, nil - } - if err := Shutdown(ctx, device.Set, udid); err != nil { - return device.Set, true, err - } - if err := WaitShutdown(ctx, device.Set, udid, ShutdownTimeout); err != nil { - return device.Set, true, err - } - return device.Set, true, nil -} - -func RenameDevice(ctx context.Context, udid, name string) error { - device, err := FindDevice(ctx, udid, "") - if err != nil { - return err - } - name, err = NormalizeSimulatorName(name) - if err != nil { - return err - } - _, err = xcrun(ctx, simctlArgs(device.Set, "rename", udid, name)...) - return err -} - -func EraseDevice(ctx context.Context, udid string) error { - set, _, err := shutdownIfBooted(ctx, udid) - if err != nil { - return err - } - _, err = xcrun(ctx, simctlArgs(set, "erase", udid)...) - return err -} - -func DeleteDevice(ctx context.Context, udid string) error { - set, _, err := shutdownIfBooted(ctx, udid) - if err != nil { - return err - } - _, err = xcrun(ctx, simctlArgs(set, "delete", udid)...) - return err -} - -// bootAndWait boots the device (tolerating an already-booted one) and blocks on -// bootstatus until its services are ready. -func BootAndWait(ctx context.Context, set, udid string) error { - out, err := exec.CommandContext(ctx, "xcrun", simctlArgs(set, "boot", udid)...).CombinedOutput() - if err != nil { - msg := strings.TrimSpace(string(out)) - if !strings.Contains(msg, "already booted") && !strings.Contains(msg, "current state: Booted") { - return fmt.Errorf("simctl boot: %w: %s", err, msg) - } - } - _, err = xcrun(ctx, simctlArgs(set, "bootstatus", udid, "-b")...) - return err -} - -func Shutdown(ctx context.Context, set, udid string) error { - out, err := exec.CommandContext(ctx, "xcrun", simctlArgs(set, "shutdown", udid)...).CombinedOutput() - if err != nil { - if strings.Contains(string(out), "current state: Shutdown") { - return nil - } - return fmt.Errorf("simctl shutdown: %w: %s", err, strings.TrimSpace(string(out))) - } - return nil -} - -// readDisabled returns the labels currently disabled in the device's system -// domain. A label absent from the output is enabled. -func readDisabled(ctx context.Context, set, udid string) (map[string]bool, error) { - out, err := readLaunchd(ctx, set, udid, "print-disabled", "system") - if err != nil { - return nil, err - } - return parseDisabled(string(out)), nil -} - -// launchdRetryDelays are the pauses between attempts to read a simulator's -// launchd state. Right after a boot, and while a reboot tears the old boot -// session down, launchd_sim refuses spawns for a few seconds -// (LaunchdSimError 124, "Domain is tearing down"); a read that fails that way -// is retried rather than failing the whole command. A var so tests can shorten -// it. -var launchdRetryDelays = []time.Duration{time.Second, 2 * time.Second, 4 * time.Second, 8 * time.Second} - -// spawnWaitDelay bounds how long a killed `simctl spawn` may keep its output -// pipe open. When a spawn times out only xcrun is killed; the simctl child it -// started still holds the pipe, and without this bound reading the output -// would never return. A var so tests can shorten it. -var spawnWaitDelay = 5 * time.Second - -// launchctlCmd builds a `simctl spawn launchctl ...` command whose -// output is abandoned spawnWaitDelay after ctx ends. -func launchctlCmd(ctx context.Context, set, udid string, args ...string) *exec.Cmd { - cmd := exec.CommandContext(ctx, "xcrun", simctlArgs(set, append([]string{"spawn", udid, "launchctl"}, args...)...)...) - cmd.WaitDelay = spawnWaitDelay - return cmd -} - -// readLaunchd runs a read-only launchctl command inside the simulator, each -// attempt bounded by SpawnTimeout. launchd_sim's transient error 124 and an -// attempt that ran out of time (a host so loaded that one read takes minutes) -// are retried, after each of launchdRetryDelays; any other failure is returned -// at once. -func readLaunchd(ctx context.Context, set, udid string, args ...string) ([]byte, error) { - for attempt := 0; ; attempt++ { - spawnCtx, cancel := context.WithTimeout(ctx, SpawnTimeout) - out, err := launchctlCmd(spawnCtx, set, udid, args...).CombinedOutput() - timedOut := errors.Is(spawnCtx.Err(), context.DeadlineExceeded) - cancel() - if err == nil { - return out, nil - } - settling := launchdSettling(err, out) || timedOut - err = fmt.Errorf("launchctl %s: %w: %s", args[0], err, strings.TrimSpace(string(out))) - if !settling || attempt == len(launchdRetryDelays) || ctx.Err() != nil { - return nil, err - } - select { - case <-ctx.Done(): - return nil, err - case <-time.After(launchdRetryDelays[attempt]): - } - } -} - -// launchdSettling reports whether a spawn failed with launchd_sim's error 124, -// which it answers while a boot session starts or tears down. -func launchdSettling(err error, out []byte) bool { - var exitErr *exec.ExitError - if errors.As(err, &exitErr) && exitErr.ExitCode() == 124 { - return true - } - return strings.Contains(string(out), "code=124") || strings.Contains(string(out), "Domain is tearing down") -} - -// parseDisabled reads `launchctl print-disabled` lines. Recent launchd prints -// `"com.apple.x" => disabled`; older builds print `=> true`/`=> false`. -func parseDisabled(output string) map[string]bool { - set := map[string]bool{} - for _, line := range strings.Split(output, "\n") { - open := strings.IndexByte(line, '"') - if open < 0 { - continue - } - rest := line[open+1:] - closeQ := strings.IndexByte(rest, '"') - if closeQ < 0 { - continue - } - label := rest[:closeQ] - arrow := strings.Index(rest[closeQ:], "=>") - if arrow < 0 { - continue - } - val := strings.TrimSpace(rest[closeQ+arrow+2:]) - if strings.HasPrefix(val, "disabled") || strings.HasPrefix(val, "true") { - set[label] = true - } - } - return set -} - -// SpawnTimeout bounds a single `simctl spawn launchctl` transition. Right -// after a first boot — especially on older Intel hosts — the simulator is -// saturated by data migration and Spotlight indexing, and an individual spawn -// can stall for many minutes. A per-spawn bound turns one stuck spawn into a -// retryable failure instead of letting it consume the whole reconfigure -// budget; the label is retried on a later pass once the device has settled. -// A var, not a const, so SIMSLIM_SPAWN_TIMEOUT can raise it for slow hosts. -var SpawnTimeout = 2 * time.Minute - -// applyPasses is how many times applyDelta walks the remaining labels. -// Disables are persistent, so each pass only retries what previous passes -// failed; on a freshly booted device the later passes run against a warm -// launchd and typically finish in seconds per label. -const applyPasses = 3 - -// spawnWorkers bounds how many `simctl spawn launchctl` transitions run at -// once. Overrides are independent launchd writes, so they parallelize cleanly, -// and a small pool hides most of the per-spawn simctl latency (~4x on an M1) -// without hammering a simulator that is still settling after its first boot. -const spawnWorkers = 8 - -// liveDisable is the applyDelta action that disables a label and then boots -// the running service out of launchd, so the daemon stops now and cannot -// respawn for the rest of the boot session. `disable` alone only blocks the -// next bootstrap; `bootout` is what removes the live job. -const liveDisable = "bootout" - -// bootoutGone is launchctl's exit status when the service to boot out is not -// loaded ("No such process"), which is already the state liveDisable wants. -const bootoutGone = 3 - -// applyDelta disables then enables the given labels; disableAction is -// "disable" (override only, applied at the next boot) or liveDisable. Each -// transition is its own `simctl spawn launchctl`, run through a pool of -// spawnWorkers so the per-spawn simctl latency overlaps instead of adding up. -// launchctl exits 0 even when it prints the benign "switch to user/foreground" -// note, so a non-zero exit is a real failure; failures are collected and -// retried on later passes rather than aborting the whole profile. -func applyDelta(ctx context.Context, set, udid string, toDisable, toEnable []string, disableAction string, report Reporter) error { - type transition struct{ action, label string } - pending := make([]transition, 0, len(toDisable)+len(toEnable)) - for _, l := range toDisable { - pending = append(pending, transition{disableAction, l}) - } - for _, l := range toEnable { - pending = append(pending, transition{"enable", l}) - } - total := len(pending) - launchctl := func(verb, label string) ([]byte, error) { - spawnCtx, cancel := context.WithTimeout(ctx, SpawnTimeout) - defer cancel() - return launchctlCmd(spawnCtx, set, udid, verb, "system/"+label).CombinedOutput() - } - run := func(action, label string) error { - verb := action - if action == liveDisable { - verb = "disable" - } - out, err := launchctl(verb, label) - if err != nil { - return fmt.Errorf("%s %s: %w: %s", verb, label, err, strings.TrimSpace(string(out))) - } - if action != liveDisable { - return nil - } - out, err = launchctl("bootout", label) - var exitErr *exec.ExitError - if err != nil && !(errors.As(err, &exitErr) && exitErr.ExitCode() == bootoutGone) { - return fmt.Errorf("bootout %s: %w: %s", label, err, strings.TrimSpace(string(out))) - } - return nil - } - - done := 0 - var failures []string - for pass := 1; pass <= applyPasses && len(pending) > 0; pass++ { - if pass > 1 { - report.report(fmt.Sprintf(" retrying %d failed services (pass %d/%d)...", - len(pending), pass, applyPasses)) - // Give a launchd that refused the spawns (still starting, or - // briefly unavailable) a moment before asking it again. - if n := len(launchdRetryDelays); n > 0 { - select { - case <-ctx.Done(): - case <-time.After(launchdRetryDelays[min(pass-2, n-1)]): - } - } - } - type result struct { - t transition - err error - } - // Buffered for every transition, so a worker never blocks on the - // reader and the pool keeps draining even while progress is printed. - results := make(chan result, len(pending)) - sem := make(chan struct{}, spawnWorkers) - var wg sync.WaitGroup - for _, t := range pending { - if ctx.Err() != nil { - break - } - sem <- struct{}{} - wg.Add(1) - go func() { - defer wg.Done() - defer func() { <-sem }() - results <- result{t, run(t.action, t.label)} - }() - } - go func() { - wg.Wait() - close(results) - }() - - var failed []transition - failures = failures[:0] - // Reporting happens here, on the one goroutine that owns Reporter. - for r := range results { - if r.err != nil { - failed = append(failed, r.t) - failures = append(failures, r.err.Error()) - continue - } - done++ - if done == total || done%20 == 0 { - report.report(fmt.Sprintf(" %d/%d services updated", done, total)) - } - } - if ctx.Err() != nil { - // The overall reconfigure budget is exhausted; stop instead of - // burning through the rest of the labels. - return fmt.Errorf("%d/%d launchctl transitions incomplete: %w", - total-done, total, ctx.Err()) - } - pending = failed - } - if len(pending) > 0 { - return fmt.Errorf("%d/%d launchctl transitions failed after %d passes: %s", - len(pending), total, applyPasses, strings.Join(failures, "; ")) - } - return nil -} - -func WaitShutdown(ctx context.Context, set, udid string, timeout time.Duration) error { - deadline := time.Now().Add(timeout) - for time.Now().Before(deadline) { - d, err := FindDevice(ctx, udid, set) - if err != nil { - return err - } - if d.State == "Shutdown" { - return nil - } - time.Sleep(500 * time.Millisecond) - } - return fmt.Errorf("timed out waiting for %s to shut down", udid) -} - -// runtimeRoot returns the host path of a CoreSimulator runtime's RuntimeRoot. -// Simulator processes see the host file system, so launchctl inside the -// simulator can read job plists by these paths. -func runtimeRoot(ctx context.Context, runtimeID string) (string, error) { - out, err := exec.CommandContext(ctx, "xcrun", "simctl", "list", "runtimes", "-j").Output() - if err != nil { - return "", listError(err) - } - return parseRuntimeRoot(out, runtimeID) -} - -// unloadJobs disables and unloads many jobs with one `launchctl unload -w` -// spawn per chunk of unloadChunk plists, instead of a disable and a bootout -// spawn per label. The exit status is not trusted: launchctl reports any single -// failure for the whole call, so the caller reads the state back and retries -// what is missing label by label. A chunk that runs out of time ends the -// batch, so a slow host keeps the rest of its budget for that per-label path. -func unloadJobs(ctx context.Context, set, udid string, paths []string) { - batchJobs(ctx, set, udid, "unload", paths) -} - -// loadJobs is the mirror of unloadJobs: one `launchctl load -w` per chunk lifts -// each job's disable override and loads it into the running boot session, in -// whichever domain its plist belongs to. launchctl exits 0 even when a job -// fails to load, so the caller reads the state back here too. -func loadJobs(ctx context.Context, set, udid string, paths []string) { - batchJobs(ctx, set, udid, "load", paths) -} - -func batchJobs(ctx context.Context, set, udid, verb string, paths []string) { - for start := 0; start < len(paths); start += unloadChunk { - end := min(start+unloadChunk, len(paths)) - args := simctlArgs(set, append([]string{"spawn", udid, "launchctl", verb, "-w"}, paths[start:end]...)...) - spawnCtx, cancel := context.WithTimeout(ctx, SpawnTimeout) - _ = exec.CommandContext(spawnCtx, "xcrun", args...).Run() - expired := spawnCtx.Err() != nil - cancel() - if expired { - return - } - } -} - -// bootstrapJobs loads each job into the running boot session with its own -// `launchctl bootstrap`, for the few the batch load left behind. launchd -// redirects the system domain to the one the job belongs in, as it does for -// every per-label transition. The exit status is not trusted either (an -// already-loaded job exits 37): the caller reads the state back. -func bootstrapJobs(ctx context.Context, set, udid string, plists map[string]string) { - labels := make([]string, 0, len(plists)) - for label := range plists { - labels = append(labels, label) - } - sort.Strings(labels) - for _, label := range labels { - spawnCtx, cancel := context.WithTimeout(ctx, SpawnTimeout) - _ = exec.CommandContext(spawnCtx, "xcrun", simctlArgs(set, "spawn", udid, - "launchctl", "bootstrap", "system", plists[label])...).Run() - cancel() - } -} - -// loadedLabels returns every label currently loaded in the simulator's launchd. -func loadedLabels(ctx context.Context, set, udid string) (map[string]bool, error) { - out, err := readLaunchd(ctx, set, udid, "list") - if err != nil { - return nil, err - } - return parseLaunchctlList(string(out)), nil -} diff --git a/simctl_test.go b/simctl_test.go deleted file mode 100644 index efffdc0..0000000 --- a/simctl_test.go +++ /dev/null @@ -1,260 +0,0 @@ -package simslim - -import ( - "context" - "errors" - "fmt" - "os" - "path/filepath" - "strconv" - "strings" - "testing" -) - -func TestNormalizeSimulatorName(t *testing.T) { - tests := []struct { - name string - input string - want string - wantError bool - }{ - {name: "ordinary", input: "QA iPhone", want: "QA iPhone"}, - {name: "trims whitespace", input: " QA iPhone ", want: "QA iPhone"}, - {name: "unicode", input: "Démo 📱", want: "Démo 📱"}, - {name: "empty", input: " ", wantError: true}, - {name: "embedded control", input: "QA\nPhone", wantError: true}, - {name: "too long", input: strings.Repeat("a", 129), wantError: true}, - } - - for _, tt := range tests { - t.Run(tt.name, func(t *testing.T) { - got, err := NormalizeSimulatorName(tt.input) - if (err != nil) != tt.wantError { - t.Fatalf("NormalizeSimulatorName() error = %v, wantError %v", err, tt.wantError) - } - if got != tt.want { - t.Errorf("NormalizeSimulatorName() = %q, want %q", got, tt.want) - } - }) - } -} - -func TestFormatListError(t *testing.T) { - exit72 := errors.New("exit status 72") - tests := []struct { - name string - stderr string - want []string - wantNot []string - }{ - { - name: "no stderr keeps the bare error", - stderr: "", - want: []string{"simctl list: exit status 72"}, - wantNot: []string{"xcode-select"}, - }, - { - name: "whitespace-only stderr keeps the bare error", - stderr: " \n", - want: []string{"simctl list: exit status 72"}, - wantNot: []string{"xcode-select"}, - }, - { - name: "stderr is appended", - stderr: "An error was encountered processing the command\n", - want: []string{"simctl list: exit status 72: An error was encountered processing the command"}, - }, - { - name: "missing simctl adds the xcode-select hint", - stderr: `xcrun: error: unable to find utility "simctl", not a developer tool or in PATH`, - want: []string{ - `unable to find utility "simctl"`, - "sudo xcode-select -s", - }, - }, - } - - for _, tt := range tests { - t.Run(tt.name, func(t *testing.T) { - got := formatListError(exit72, tt.stderr).Error() - for _, want := range tt.want { - if !strings.Contains(got, want) { - t.Errorf("formatListError() = %q, missing %q", got, want) - } - } - for _, wantNot := range tt.wantNot { - if strings.Contains(got, wantNot) { - t.Errorf("formatListError() = %q, should not contain %q", got, wantNot) - } - } - if !errors.Is(formatListError(exit72, tt.stderr), exit72) { - t.Errorf("formatListError() does not wrap the original error") - } - }) - } -} - -func TestParseClonedUDID(t *testing.T) { - const udid = "00000000-0000-0000-0000-000000000001" - got, err := parseClonedUDID([]byte("\n" + udid + "\n")) - if err != nil { - t.Fatalf("parseClonedUDID() error = %v", err) - } - if got != udid { - t.Errorf("parseClonedUDID() = %q, want %q", got, udid) - } - - for _, invalid := range []string{"", "not-a-udid", "00000000-0000-0000-0000-00000000000Z"} { - if _, err := parseClonedUDID([]byte(invalid)); err == nil { - t.Errorf("parseClonedUDID(%q) unexpectedly succeeded", invalid) - } - } -} - -func TestResetClonedLaunchServicesAt(t *testing.T) { - dataDirectory := filepath.Join(t.TempDir(), "data") - lsdDirectory := filepath.Join(dataDirectory, "var", "db", "lsd") - if err := os.MkdirAll(lsdDirectory, 0o755); err != nil { - t.Fatal(err) - } - - removed := []string{ - "com.apple.LaunchServices-20971544-v2.csstore", - "com.apple.LaunchServices-20971544-v2.csstore-shm", - "com.apple.LaunchServices-20971544-v2.csstore-wal", - } - preserved := []string{ - "SystemDataOnly-com.apple.LaunchServices-20971544-v2.csstore", - "com.apple.LaunchServicesAppProtectionStore.plist", - "unrelated.db", - } - for _, name := range append(append([]string{}, removed...), preserved...) { - if err := os.WriteFile(filepath.Join(lsdDirectory, name), []byte("test"), 0o600); err != nil { - t.Fatal(err) - } - } - - if err := resetClonedLaunchServicesAt(dataDirectory); err != nil { - t.Fatalf("resetClonedLaunchServicesAt() error = %v", err) - } - for _, name := range removed { - if _, err := os.Stat(filepath.Join(lsdDirectory, name)); !os.IsNotExist(err) { - t.Errorf("generated store %q still exists; stat error = %v", name, err) - } - } - for _, name := range preserved { - if _, err := os.Stat(filepath.Join(lsdDirectory, name)); err != nil { - t.Errorf("unrelated file %q was not preserved: %v", name, err) - } - } -} - -func TestResetClonedLaunchServicesAtAllowsMissingStore(t *testing.T) { - dataDirectory := filepath.Join(t.TempDir(), "data") - if err := os.MkdirAll(dataDirectory, 0o755); err != nil { - t.Fatal(err) - } - if err := resetClonedLaunchServicesAt(dataDirectory); err != nil { - t.Fatalf("resetClonedLaunchServicesAt() error = %v", err) - } -} - -func TestResetClonedLaunchServicesAtRejectsSymlink(t *testing.T) { - root := t.TempDir() - dataDirectory := filepath.Join(root, "data") - externalDirectory := filepath.Join(root, "external") - if err := os.MkdirAll(filepath.Join(dataDirectory, "var", "db"), 0o755); err != nil { - t.Fatal(err) - } - if err := os.MkdirAll(externalDirectory, 0o755); err != nil { - t.Fatal(err) - } - if err := os.Symlink(externalDirectory, filepath.Join(dataDirectory, "var", "db", "lsd")); err != nil { - t.Fatal(err) - } - - err := resetClonedLaunchServicesAt(dataDirectory) - if err == nil || !strings.Contains(err.Error(), "not a real directory") { - t.Fatalf("resetClonedLaunchServicesAt() error = %v, want symlink rejection", err) - } -} - -// TestApplyDeltaRunsTransitionsConcurrentlyButBounded drives applyDelta -// against a fake xcrun that records how many spawns are in flight while it -// works. The peak proves both halves of the contract: transitions really do -// overlap (the whole point of the pool), and never more than spawnWorkers of -// them at once, so a simulator still settling after a first boot is not -// hammered. -func TestApplyDeltaRunsTransitionsConcurrentlyButBounded(t *testing.T) { - dir := t.TempDir() - inFlight := filepath.Join(dir, "inflight") - peaks := filepath.Join(dir, "peaks") - if err := os.Mkdir(inFlight, 0o755); err != nil { - t.Fatal(err) - } - // Each spawn logs its arguments, marks itself present, records how many - // peers it sees, holds long enough for the rest of its wave to arrive, - // then leaves. - script := `#!/bin/sh -printf '%s\n' "$*" >> "$SIMSLIM_XCRUN_LOG" -: > "$SIMSLIM_INFLIGHT/$$" -ls "$SIMSLIM_INFLIGHT" | wc -l >> "$SIMSLIM_PEAKS" -sleep 0.2 -rm -f "$SIMSLIM_INFLIGHT/$$" -exit 0 -` - if err := os.WriteFile(filepath.Join(dir, "xcrun"), []byte(script), 0o755); err != nil { - t.Fatal(err) - } - t.Setenv("PATH", dir+string(os.PathListSeparator)+os.Getenv("PATH")) - t.Setenv("SIMSLIM_INFLIGHT", inFlight) - t.Setenv("SIMSLIM_PEAKS", peaks) - logPath := filepath.Join(dir, "xcrun.log") - t.Setenv("SIMSLIM_XCRUN_LOG", logPath) - - labels := make([]string, 3*spawnWorkers) - for i := range labels { - labels[i] = fmt.Sprintf("com.apple.probe%d", i) - } - if err := applyDelta(context.Background(), "default", "UDID", labels, nil, "disable", nil); err != nil { - t.Fatalf("applyDelta: %v", err) - } - - log, err := os.ReadFile(peaks) - if err != nil { - t.Fatal(err) - } - peak := 0 - for _, line := range strings.Fields(string(log)) { - n, err := strconv.Atoi(line) - if err != nil { - t.Fatalf("unparsable peak %q: %v", line, err) - } - peak = max(peak, n) - } - if peak <= 1 { - t.Errorf("peak concurrency = %d, want transitions to overlap", peak) - } - if peak > spawnWorkers { - t.Errorf("peak concurrency = %d, want at most spawnWorkers (%d)", peak, spawnWorkers) - } - - // Bounding the pool must not cost coverage: every label gets exactly the - // one transition it was queued for, whatever order the workers ran in. - want := make(map[string]bool, len(labels)) - for _, l := range labels { - want["simctl spawn UDID launchctl disable system/"+l] = true - } - got := map[string]int{} - for _, call := range xcrunCalls(t, logPath) { - got[call]++ - } - if len(got) != len(want) { - t.Errorf("saw %d distinct transitions, want %d", len(got), len(want)) - } - for call := range want { - if got[call] != 1 { - t.Errorf("transition %q ran %d times, want exactly 1", call, got[call]) - } - } -} diff --git a/slim.go b/slim.go deleted file mode 100644 index 2f53b30..0000000 --- a/slim.go +++ /dev/null @@ -1,381 +0,0 @@ -package simslim - -import ( - "context" - "errors" - "fmt" - "sort" - "strconv" - "strings" -) - -// Reporter receives human-readable progress lines. A nil Reporter is a no-op, -// so non-interactive callers can ignore progress entirely. -type Reporter func(string) - -func (r Reporter) report(msg string) { - if r != nil { - r(msg) - } -} - -// ensure brings the device to exactly the desired disabled state and boots it. -// The disabled overrides persist in the device's launchd DB, so once set a slim -// device comes up slim in a single boot; a reboot only happens when the state -// actually changes. A non-empty profile is rejected before boot on runtimes -// without persistent overrides. On a runtime that persists them the device -// takes the far cheaper ensureOffline route, whatever state it starts in. Each -// slow phase reports progress so the caller can show the user that a -// multi-minute reconfigure is still working. -func ensure(ctx context.Context, set, udid string, desired map[string]bool, report Reporter) (changed bool, err error) { - d, err := FindDevice(ctx, udid, set) - if err != nil { - return false, err - } - desired = desiredForDevice(d, desired) - persistent := d.SupportsPersistentOverrides() - if len(desired) > 0 && !persistent { - return false, fmt.Errorf("%s runtime cannot persist launchd disable overrides across reboot; simslim requires %s %s or newer, or `simslim on --no-reboot` to slim the current boot session only", d.RuntimeName(), d.PlatformName(), d.minimumPersistentVersion()) - } - // A shutdown device can be reconfigured by writing the overrides launchd_sim - // reads when it starts, which skips both the per-label launchctl spawns and - // the reboot that would apply them: minutes become seconds. - booted := d.State == "Booted" - if booted && persistent { - // `simctl list` says Booted from the moment the boot starts, so wait - // for launchd to be up before asking it anything; on a device that is - // really booted this costs a fraction of a second. - if err := BootAndWait(ctx, set, udid); err != nil { - return false, err - } - // An override only takes effect at the next boot, so a booted device - // already owes us a shutdown and a boot. Spending them up front, before - // touching launchd, makes it a shutdown device and lets the store - // replace every launchctl spawn for the same two state changes. - live, err := readDisabled(ctx, set, udid) - if err != nil { - return false, err - } - if toDisable, toEnable := delta(live, desired, managedSet()); len(toDisable) == 0 && len(toEnable) == 0 { - return false, nil - } - report.report("Shutting the simulator down to reconfigure it offline...") - if err := Shutdown(ctx, set, udid); err != nil { - return false, fmt.Errorf("shutdown before reconfigure: %w", err) - } - if err := WaitShutdown(ctx, set, udid, ShutdownTimeout); err != nil { - return false, err - } - d.State = "Shutdown" - } - if d.State == "Shutdown" && persistent { - changed, err := ensureOffline(ctx, set, udid, desired, report) - if !errors.Is(err, errOfflineIneffective) { - // A device that started booted only gets here with a real delta. - return changed || booted, err - } - report.report("Could not apply the changes while the simulator was off; reconfiguring it while booted instead...") - } - report.report("Booting the simulator (a first boot can take up to a minute)...") - if err := BootAndWait(ctx, set, udid); err != nil { - return false, err - } - current, err := readDisabled(ctx, set, udid) - if err != nil { - return false, err - } - toDisable, toEnable := delta(current, desired, managedSet()) - if len(toDisable) == 0 && len(toEnable) == 0 { - return false, nil - } - if len(toDisable) > 0 { - report.report(fmt.Sprintf("Disabling %d background services...", len(toDisable))) - } - if len(toEnable) > 0 { - report.report(fmt.Sprintf("Re-enabling %d background services...", len(toEnable))) - } - if err := applyDelta(ctx, set, udid, toDisable, toEnable, "disable", report); err != nil { - return true, err - } - report.report("Rebooting the simulator to apply the changes...") - if err := Shutdown(ctx, set, udid); err != nil { - return true, fmt.Errorf("shutdown before reboot: %w", err) - } - if err := WaitShutdown(ctx, set, udid, ShutdownTimeout); err != nil { - return true, err - } - if err := BootAndWait(ctx, set, udid); err != nil { - return true, err - } - after, err := readDisabled(ctx, set, udid) - if err != nil { - return true, err - } - if lost := countLost(after, desired, managedSet()); lost > 0 { - return true, fmt.Errorf("the disable overrides did not survive the reboot (%d of %d changes lost)", lost, len(toDisable)+len(toEnable)) - } - return true, nil -} - -// ensureOffline reaches the desired state on a shutdown device by writing its -// launchd overrides directly, then boots it once — already slim. That replaces a -// boot, one launchctl spawn per label, and a reboot with a single boot. The -// state is read back from the booted device rather than trusted: the store is a -// private CoreSimulator detail, so anything that stops it from working returns -// errOfflineIneffective and the caller takes the supported path instead. -func ensureOffline(ctx context.Context, set, udid string, desired map[string]bool, report Reporter) (changed bool, err error) { - current, err := readDisabledStore(udid) - if err != nil { - return false, fmt.Errorf("%w: %v", errOfflineIneffective, err) - } - toDisable, toEnable := delta(current, desired, managedSet()) - changed = len(toDisable) > 0 || len(toEnable) > 0 - if changed { - report.report(fmt.Sprintf("Reconfiguring %d background services while the simulator is off...", len(toDisable)+len(toEnable))) - if err := writeDisabledStore(udid, toDisable, toEnable); err != nil { - return false, fmt.Errorf("%w: %v", errOfflineIneffective, err) - } - } - report.report("Booting the simulator (a first boot can take up to a minute)...") - if err := BootAndWait(ctx, set, udid); err != nil { - return changed, err - } - after, err := readDisabled(ctx, set, udid) - if err != nil { - return changed, err - } - if lost := countLost(after, desired, managedSet()); lost > 0 { - return changed, fmt.Errorf("%d of %d offline overrides were not honoured at boot: %w", lost, len(toDisable)+len(toEnable), errOfflineIneffective) - } - return changed, nil -} - -// errOfflineIneffective means the store was written but the booted device did -// not come up in the desired state. The store is an undocumented CoreSimulator -// detail, so a runtime is always free to ignore it; callers treat this as "take -// the supported path instead", never as a failure. -var errOfflineIneffective = errors.New("offline launchd overrides not honoured") - -// countLost reports how many of the desired managed transitions are not -// reflected in the state read back after the reboot. -func countLost(after, desired, managed map[string]bool) int { - toDisable, toEnable := delta(after, desired, managed) - return len(toDisable) + len(toEnable) -} - -// PersistentOverridesSupported reports whether the runtime keeps launchd -// disable overrides across reboot. iOS 17.x and 18.3 hold them in memory only -// and come back stock; iOS 18.5 and newer are verified to persist them. -func PersistentOverridesSupported(version string) bool { - return (Device{OSVersion: version}).SupportsPersistentOverrides() -} - -func (d Device) minimumPersistentVersion() string { - switch d.PlatformName() { - case "watchOS": - return "11.5" - case "visionOS": - return "2.5" - } - return "18.5" -} - -// SupportsPersistentOverrides applies the launchd persistence version gate to -// the device's platform. tvOS 18.5, watchOS 11.5, and visionOS 2.5 are the -// release generation corresponding to iOS 18.5. This gate is not proof of -// persistence: ensure always reads overrides back after boot and fails if the -// runtime lost them. -func (d Device) SupportsPersistentOverrides() bool { - minimumMajor := 18 - switch d.PlatformName() { - case "iOS", "tvOS": - case "watchOS": - minimumMajor = 11 - case "visionOS": - minimumMajor = 2 - default: - return false - } - version := d.OSVersion - parts := strings.SplitN(version, ".", 3) - if len(parts) < 2 { - return false - } - major, majorErr := strconv.Atoi(parts[0]) - minor, minorErr := strconv.Atoi(parts[1]) - return majorErr == nil && minorErr == nil && minor >= 0 && (major > minimumMajor || major == minimumMajor && minor >= 5) -} - -// enableSlim disables the profile's daemons and boots the device slim. -func EnableSlim(ctx context.Context, set, udid string, p Profile, report Reporter) (bool, error) { - return ensure(ctx, set, udid, p.Desired(), report) -} - -// EnableSlimNoReboot slims the running boot session without a reboot: each -// daemon the profile disables is booted out of launchd, and the disable -// override keeps launchd from respawning it. It works on every runtime, but on -// runtimes without persistent overrides the simulator comes back stock at its -// next boot. Live slimming only moves toward more-disabled: managed labels -// disabled beyond the profile are left alone, because a live re-enable would -// have to bootstrap each daemon again; `off` restores them with a reboot. -func EnableSlimNoReboot(ctx context.Context, set, udid string, p Profile, report Reporter) (changed bool, err error) { - d, err := FindDevice(ctx, udid, set) - if err != nil { - return false, err - } - desired := p.DesiredForDevice(d) - report.report("Booting the simulator (a first boot can take up to a minute)...") - if err := BootAndWait(ctx, set, udid); err != nil { - return false, err - } - current, err := readDisabled(ctx, set, udid) - if err != nil { - return false, err - } - managed := managedSet() - toDisable, extra := delta(current, desired, managed) - if len(extra) > 0 { - report.report(fmt.Sprintf("Leaving %d services disabled beyond this profile; only `simslim off` re-enables them.", len(extra))) - } - // Check every profiled label, not just those without an override: an - // override says nothing about whether the job is still loaded (an earlier - // run may have disabled it and then failed to boot it out). Labels that are - // both disabled and unloaded are skipped, so the command stays idempotent. - changed = len(toDisable) > 0 - labels := make([]string, 0, len(desired)) - for l := range desired { - if managed[l] { - labels = append(labels, l) - } - } - sort.Strings(labels) - report.report(fmt.Sprintf("Stopping %d background services for this boot session...", len(labels))) - remaining := unloadInBatch(ctx, set, udid, d.RuntimeID, labels, readPlistLabel, report) - if err := applyDelta(ctx, set, udid, remaining, nil, liveDisable, report); err != nil { - return changed, err - } - after, err := readDisabled(ctx, set, udid) - if err != nil { - return changed, err - } - if missing, _ := delta(after, desired, managed); len(missing) > 0 { - return changed, fmt.Errorf("%d of %d disable overrides did not take", len(missing), len(labels)) - } - return changed, nil -} - -// unloadInBatch disables and unloads the labels whose job plist it can find with -// one `launchctl unload -w` per chunk, then reads the state back and returns -// what still needs the per-label disable and bootout. Two spawns per label add -// up on a busy host; one spawn per chunk does not. Anything that goes wrong -// here only means more labels take the per-label path. -func unloadInBatch(ctx context.Context, set, udid, runtimeID string, labels []string, plistLabel func(context.Context, string) (string, error), report Reporter) []string { - if runtimeID == "" { - return labels - } - root, err := runtimeRoot(ctx, runtimeID) - if err != nil { - return labels - } - // Only what is still enabled or loaded needs stopping, so a device that is - // already slim spawns no unload and does not report work it did not do. - pending, err := stopState(ctx, set, udid, labels) - if err != nil { - return labels - } - if len(pending) == 0 { - report.report(fmt.Sprintf(" all %d services were already stopped", len(labels))) - return nil - } - plists := launchdJobPlists(ctx, root, pending, plistLabel) - if len(plists) == 0 { - return pending - } - paths := make([]string, 0, len(plists)) - for _, l := range pending { - if p, ok := plists[l]; ok { - paths = append(paths, p) - } - } - unloadJobs(ctx, set, udid, paths) - rest, err := stopState(ctx, set, udid, pending) - if err != nil { - return pending - } - report.report(fmt.Sprintf(" %d/%d services stopped in one batch", len(pending)-len(rest), len(pending))) - return rest -} - -// stopState returns the labels that are still enabled or still loaded. -func stopState(ctx context.Context, set, udid string, labels []string) ([]string, error) { - disabled, err := readDisabled(ctx, set, udid) - if err != nil { - return nil, err - } - loaded, err := loadedLabels(ctx, set, udid) - if err != nil { - return nil, err - } - return stillToStop(labels, disabled, loaded), nil -} - -// disableSlim re-enables every managed daemon, returning the device to stock. -func DisableSlim(ctx context.Context, set, udid string, report Reporter) (bool, error) { - return ensure(ctx, set, udid, map[string]bool{}, report) -} - -// Status describes how slim a device currently is. -type Status struct { - ManagedDisabled int `json:"managedDisabled"` // managed labels currently disabled - ManagedTotal int `json:"managedTotal"` // size of the managed universe - Booted bool `json:"booted"` - Persistent bool `json:"persistent"` // the runtime keeps disabled state across reboot -} - -// status reports how slim a device is and returns the labels it currently has -// disabled (nil when the device is not booted). -func ReadStatus(ctx context.Context, udid string) (Status, map[string]bool, error) { - d, err := FindDevice(ctx, udid, "") - if err != nil { - return Status{}, nil, err - } - return ReadStatusForDevice(ctx, d) -} - -func ReadStatusForDevice(ctx context.Context, d Device) (Status, map[string]bool, error) { - managed := (Profile{}).DesiredForDevice(d) - st := Status{ManagedTotal: len(managed), Booted: d.State == "Booted", Persistent: d.SupportsPersistentOverrides()} - if !st.Booted { - return st, nil, fmt.Errorf("simulator must be booted to read its state (it is %s)", d.State) - } - disabled, err := readDisabled(ctx, d.Set, d.UDID) - if err != nil { - return st, nil, err - } - for l := range disabled { - if managed[l] { - st.ManagedDisabled++ - } - } - return st, disabled, nil -} - -// droppedCategories groups the disabled managed daemons by category, in category -// order, omitting categories with nothing disabled. -func DroppedCategories(disabled map[string]bool) []DroppedCategory { - var out []DroppedCategory - for _, c := range Categories { - var labels []string - for _, l := range c.Labels { - if disabled[l] { - labels = append(labels, l) - } - } - if len(labels) == 0 { - continue - } - sort.Strings(labels) - out = append(out, DroppedCategory{ID: c.ID, Name: c.Name, Downside: c.Downside, Labels: labels}) - } - return out -} diff --git a/slim_no_reboot_test.go b/slim_no_reboot_test.go deleted file mode 100644 index 7d6745d..0000000 --- a/slim_no_reboot_test.go +++ /dev/null @@ -1,72 +0,0 @@ -package simslim - -import ( - "context" - "os" - "path/filepath" - "strings" - "testing" -) - -// TestEnableSlimNoRebootNeverReboots drives EnableSlimNoReboot against a fake -// xcrun on an iOS 18.3 device: every profiled label gets a disable and a -// bootout, including com.apple.b whose override already exists (a previous run -// may have failed before booting it out), a bootout of an already-missing -// service (exit 3) counts as done, and no shutdown or second boot ever happens. -func TestEnableSlimNoRebootNeverReboots(t *testing.T) { - const udid = "00000000-0000-0000-0000-000000000038" - dir := t.TempDir() - logPath := filepath.Join(dir, "xcrun.log") - script := `#!/bin/sh -printf '%s\n' "$*" >> "$SIMSLIM_XCRUN_LOG" -case "$*" in - "simctl list devices -j") - printf '%s\n' '{"devices":{"com.apple.CoreSimulator.SimRuntime.iOS-18-3":[{"udid":"00000000-0000-0000-0000-000000000038","name":"Issue 38","state":"Booted","isAvailable":true,"dataPath":"/tmp/issue-38"}]}}' ;; - "simctl boot "*) echo "Unable to boot device in current state: Booted" >&2; exit 1 ;; - "simctl bootstatus "*) exit 0 ;; - *"launchctl print-disabled system") - printf '\t"%s" => disabled\n' com.apple.b - if [ -f "$SIMSLIM_XCRUN_LOG.applied" ]; then - printf '\t"%s" => disabled\n' com.apple.a - fi ;; - *"launchctl disable system/"*) exit 0 ;; - *"launchctl bootout system/com.apple.a") : > "$SIMSLIM_XCRUN_LOG.applied"; exit 0 ;; - *"launchctl bootout system/com.apple.b") echo "Boot-out failed: 3: No such process" >&2; exit 3 ;; - *) exit 99 ;; -esac -` - if err := os.WriteFile(filepath.Join(dir, "xcrun"), []byte(script), 0o755); err != nil { - t.Fatal(err) - } - t.Setenv("PATH", dir+string(os.PathListSeparator)+os.Getenv("PATH")) - t.Setenv("SIMSLIM_XCRUN_LOG", logPath) - saved := Categories - Categories = []Category{{ID: "t", Name: "t", Labels: []string{"com.apple.a", "com.apple.b"}, ApproxMemoryMB: 1}} - defer func() { Categories = saved }() - - changed, err := EnableSlimNoReboot(context.Background(), "default", udid, Profile{}, nil) - if err != nil || !changed { - t.Fatalf("EnableSlimNoReboot = (%t, %v), want (true, nil)", changed, err) - } - log, err := os.ReadFile(logPath) - if err != nil { - t.Fatal(err) - } - calls := string(log) - for _, want := range []string{ - "launchctl disable system/com.apple.a", "launchctl bootout system/com.apple.a", - "launchctl disable system/com.apple.b", "launchctl bootout system/com.apple.b", - } { - if !strings.Contains(calls, want) { - t.Errorf("missing %q in xcrun calls:\n%s", want, calls) - } - } - for _, forbidden := range []string{"simctl shutdown", "launchctl enable"} { - if strings.Contains(calls, forbidden) { - t.Errorf("unexpected %q in xcrun calls:\n%s", forbidden, calls) - } - } - if n := strings.Count(calls, "simctl boot "); n != 1 { - t.Errorf("simctl boot called %d times, want 1 (no reboot):\n%s", n, calls) - } -} diff --git a/slim_offline_test.go b/slim_offline_test.go deleted file mode 100644 index 6aa280e..0000000 --- a/slim_offline_test.go +++ /dev/null @@ -1,264 +0,0 @@ -package simslim - -import ( - "context" - "os" - "path/filepath" - "sort" - "strings" - "testing" -) - -// fakeXcrunScript logs every call, answers the device lookup, and hands any -// `simctl spawn` straight to the stub launchctl below, so the transitions run -// as written instead of being matched by a pattern. -const fakeXcrunScript = `#!/bin/sh -printf '%s\n' "$*" >> "$SIMSLIM_XCRUN_LOG" -case "$1 $2" in - "simctl list") - printf '%s\n' "$SIMSLIM_TEST_DEVICES" | sed "s/@STATE@/$(cat "$SIMSLIM_TEST_STATE")/" - ;; - "simctl spawn") - shift 3 - export DYLD_ROOT_PATH="$SIMULATOR_ROOT" - exec "$@" - ;; - "simctl boot") - printf Booted > "$SIMSLIM_TEST_STATE" - ;; - "simctl shutdown") - printf Shutdown > "$SIMSLIM_TEST_STATE" - ;; - "simctl bootstatus") - ;; - *) - exit 99 - ;; -esac -` - -// fakeLaunchctlScript is a stand-in launchd. Live overrides are one file per -// label, so applyDelta's concurrent workers cannot race each other, and -// print-disabled renders the union of those and the offline store — which is -// how the real launchd_sim behaves, having read the store when it started. -// SIMSLIM_TEST_IGNORE_STORE models a runtime that does not honour the store. -const fakeLaunchctlScript = `#!/bin/sh -label=${2#system/} -case "$1" in - print-disabled) - if [ "$SIMSLIM_TEST_IGNORE_STORE" != 1 ] && [ -f "$SIMSLIM_TEST_STORE" ]; then - awk ' - // { sub(/.*/, ""); sub(/<\/key>.*/, ""); l=$0; next } - // { if (l != "") printf "\t\"%s\" => disabled\n", l; l="" } - // { l="" } - ' "$SIMSLIM_TEST_STORE" - fi - for f in "$SIMSLIM_TEST_LIVE"/*; do - [ -e "$f" ] && printf '\t"%s" => disabled\n' "${f##*/}" - done - ;; - disable) mkdir -p "$SIMSLIM_TEST_LIVE" && : > "$SIMSLIM_TEST_LIVE/$label" ;; - enable) rm -f "$SIMSLIM_TEST_LIVE/$label" ;; - bootout) exit 3 ;; - *) exit 99 ;; -esac -exit 0 -` - -// fakeSimctl puts the stub toolchain on PATH for one device and returns the -// path of the xcrun call log. -func fakeSimctl(t *testing.T, udid, runtime, state string) string { - t.Helper() - dir := t.TempDir() - for name, script := range map[string]string{"xcrun": fakeXcrunScript, "launchctl": fakeLaunchctlScript} { - if err := os.WriteFile(filepath.Join(dir, name), []byte(script), 0o755); err != nil { - t.Fatal(err) - } - } - logPath := filepath.Join(dir, "xcrun.log") - // @STATE@ is substituted from the state file, so a boot or shutdown the - // code under test issues is reflected by the next `simctl list`. - devices := `{"devices":{"com.apple.CoreSimulator.SimRuntime.` + runtime + `":[{"udid":"` + udid + - `","name":"Offline Probe","state":"@STATE@","isAvailable":true,"dataPath":"` + dir + `/data"}]}}` - statePath := filepath.Join(dir, "state") - if err := os.WriteFile(statePath, []byte(state), 0o644); err != nil { - t.Fatal(err) - } - t.Setenv("SIMSLIM_TEST_STATE", statePath) - t.Setenv("PATH", dir+string(os.PathListSeparator)+os.Getenv("PATH")) - t.Setenv("SIMSLIM_XCRUN_LOG", logPath) - t.Setenv("SIMSLIM_TEST_DEVICES", devices) - t.Setenv("SIMSLIM_TEST_STORE", disabledStorePath(udid)) - t.Setenv("SIMSLIM_TEST_LIVE", filepath.Join(dir, "live")) - // simctl exports this into a spawned process alongside DYLD_ROOT_PATH. - t.Setenv("SIMULATOR_ROOT", dir+"/runtime") - return logPath -} - -func xcrunCalls(t *testing.T, logPath string) []string { - t.Helper() - log, err := os.ReadFile(logPath) - if err != nil { - t.Fatal(err) - } - return strings.Split(strings.TrimSpace(string(log)), "\n") -} - -// twoSlimmableLabels returns a stable pair of real managed labels. -func twoSlimmableLabels(t *testing.T) []string { - t.Helper() - var labels []string - for l := range SlimmableSet() { - labels = append(labels, l) - } - sort.Strings(labels) - if len(labels) < 2 { - t.Fatalf("need at least 2 slimmable labels, got %d", len(labels)) - } - return labels[:2] -} - -func TestEnsureSlimsAShutdownDeviceWithoutLaunchctlSpawns(t *testing.T) { - const udid = "00000000-0000-0000-0000-0000000000E1" - useTempStoreRoot(t) - logPath := fakeSimctl(t, udid, "iOS-26-5", "Shutdown") - labels := twoSlimmableLabels(t) - - changed, err := ensure(context.Background(), "default", udid, map[string]bool{labels[0]: true, labels[1]: true}, nil) - if err != nil { - t.Fatalf("ensure: %v", err) - } - if !changed { - t.Error("ensure reported no change after slimming a stock device") - } - - disabled, err := readDisabledStore(udid) - if err != nil { - t.Fatalf("readDisabledStore: %v", err) - } - for _, l := range labels { - if !disabled[l] { - t.Errorf("label %q not disabled in the store; store = %v", l, disabled) - } - } - - // One boot, no launchctl transitions, no reboot: that is the whole win. - want := []string{ - "simctl list devices -j", - "simctl boot " + udid, - "simctl bootstatus " + udid + " -b", - "simctl spawn " + udid + " launchctl print-disabled system", - } - if got := xcrunCalls(t, logPath); strings.Join(got, "\n") != strings.Join(want, "\n") { - t.Errorf("xcrun calls =\n%s\nwant\n%s", strings.Join(got, "\n"), strings.Join(want, "\n")) - } -} - -func TestEnsureFallsBackWhenTheStoreCannotBeWritten(t *testing.T) { - const udid = "00000000-0000-0000-0000-0000000000E3" - root := useTempStoreRoot(t) - // A regular file where the store root should be: every write under it fails, - // which stands in for a sandboxed or permission-denied host. - blocked := filepath.Join(root, "blocked") - if err := os.WriteFile(blocked, nil, 0o644); err != nil { - t.Fatal(err) - } - disabledStoreRoot = blocked - logPath := fakeSimctl(t, udid, "iOS-26-5", "Shutdown") - labels := twoSlimmableLabels(t) - - changed, err := ensure(context.Background(), "default", udid, map[string]bool{labels[0]: true, labels[1]: true}, nil) - if err != nil { - t.Fatalf("ensure did not fall back when the store was unwritable: %v", err) - } - if !changed { - t.Error("ensure reported no change after slimming a stock device") - } - if calls := strings.Join(xcrunCalls(t, logPath), "\n"); !strings.Contains(calls, "launchctl") { - t.Errorf("expected a fallback to launchctl, got:\n%s", calls) - } -} - -func TestEnsureFallsBackToLaunchctlWhenTheRuntimeIgnoresTheStore(t *testing.T) { - const udid = "00000000-0000-0000-0000-0000000000E2" - useTempStoreRoot(t) - logPath := fakeSimctl(t, udid, "iOS-26-5", "Shutdown") - t.Setenv("SIMSLIM_TEST_IGNORE_STORE", "1") - labels := twoSlimmableLabels(t) - - changed, err := ensure(context.Background(), "default", udid, map[string]bool{labels[0]: true, labels[1]: true}, nil) - if err != nil { - t.Fatalf("ensure did not fall back to the supported path: %v", err) - } - if !changed { - t.Error("ensure reported no change after slimming a stock device") - } - - calls := strings.Join(xcrunCalls(t, logPath), "\n") - if !strings.Contains(calls, "launchctl") || !strings.Contains(calls, "simctl shutdown "+udid) { - t.Errorf("expected a fallback to launchctl plus a reboot, got:\n%s", calls) - } -} - -func TestEnsureSlimsABootedDeviceThroughTheOfflineStore(t *testing.T) { - const udid = "00000000-0000-0000-0000-0000000000E4" - useTempStoreRoot(t) - logPath := fakeSimctl(t, udid, "iOS-26-5", "Booted") - labels := twoSlimmableLabels(t) - - changed, err := ensure(context.Background(), "default", udid, map[string]bool{labels[0]: true, labels[1]: true}, nil) - if err != nil { - t.Fatalf("ensure: %v", err) - } - if !changed { - t.Error("ensure reported no change after slimming a stock device") - } - - // A booted device owes a shutdown and a boot either way, so spending them - // first buys the whole offline path: no launchctl transition at all. - want := []string{ - "simctl list devices -j", - "simctl boot " + udid, - "simctl bootstatus " + udid + " -b", - "simctl spawn " + udid + " launchctl print-disabled system", - "simctl shutdown " + udid, - "simctl list devices -j", - "simctl boot " + udid, - "simctl bootstatus " + udid + " -b", - "simctl spawn " + udid + " launchctl print-disabled system", - } - if got := xcrunCalls(t, logPath); strings.Join(got, "\n") != strings.Join(want, "\n") { - t.Errorf("xcrun calls =\n%s\nwant\n%s", strings.Join(got, "\n"), strings.Join(want, "\n")) - } -} - -func TestEnsureLeavesAnAlreadySlimBootedDeviceAlone(t *testing.T) { - const udid = "00000000-0000-0000-0000-0000000000E5" - useTempStoreRoot(t) - logPath := fakeSimctl(t, udid, "iOS-26-5", "Booted") - labels := twoSlimmableLabels(t) - desired := map[string]bool{labels[0]: true, labels[1]: true} - if err := writeDisabledStore(udid, labels, nil); err != nil { - t.Fatal(err) - } - - changed, err := ensure(context.Background(), "default", udid, desired, nil) - if err != nil { - t.Fatalf("ensure: %v", err) - } - if changed { - t.Error("ensure reported a change on a device that already matched the profile") - } - - // Reading the live state is enough to prove there is nothing to do; a - // matching profile must not cost a shutdown or a reboot. - want := []string{ - "simctl list devices -j", - "simctl boot " + udid, - "simctl bootstatus " + udid + " -b", - "simctl spawn " + udid + " launchctl print-disabled system", - } - if got := xcrunCalls(t, logPath); strings.Join(got, "\n") != strings.Join(want, "\n") { - t.Errorf("xcrun calls =\n%s\nwant\n%s", strings.Join(got, "\n"), strings.Join(want, "\n")) - } -} diff --git a/slim_persist_test.go b/slim_persist_test.go deleted file mode 100644 index c49019e..0000000 --- a/slim_persist_test.go +++ /dev/null @@ -1,95 +0,0 @@ -package simslim - -import ( - "context" - "os" - "path/filepath" - "strings" - "testing" -) - -func TestEnsureRejectsIOS183BeforeBoot(t *testing.T) { - const udid = "00000000-0000-0000-0000-000000000034" - dir := t.TempDir() - logPath := filepath.Join(dir, "xcrun.log") - xcrunPath := filepath.Join(dir, "xcrun") - script := `#!/bin/sh -printf '%s\n' "$*" >> "$SIMSLIM_XCRUN_LOG" -if [ "$*" = "simctl list devices -j" ]; then - printf '%s\n' '{"devices":{"com.apple.CoreSimulator.SimRuntime.iOS-18-3":[{"udid":"00000000-0000-0000-0000-000000000034","name":"Issue 34","state":"Shutdown","isAvailable":true,"dataPath":"/tmp/issue-34"}]}}' - exit 0 -fi -exit 99 -` - if err := os.WriteFile(xcrunPath, []byte(script), 0o755); err != nil { - t.Fatal(err) - } - t.Setenv("PATH", dir+string(os.PathListSeparator)+os.Getenv("PATH")) - t.Setenv("SIMSLIM_XCRUN_LOG", logPath) - - var label string - for label = range SlimmableSet() { - break - } - changed, err := ensure(context.Background(), "default", udid, map[string]bool{label: true}, nil) - if changed { - t.Fatal("ensure reported a change on an unsupported runtime") - } - const want = "iOS 18.3 runtime cannot persist launchd disable overrides across reboot; simslim requires iOS 18.5 or newer, or `simslim on --no-reboot` to slim the current boot session only" - if err == nil || err.Error() != want { - t.Fatalf("ensure error = %v, want %q", err, want) - } - log, readErr := os.ReadFile(logPath) - if readErr != nil { - t.Fatal(readErr) - } - if got := strings.TrimSpace(string(log)); got != "simctl list devices -j" { - t.Fatalf("xcrun calls = %q, want only the read-only device lookup", got) - } -} - -func TestCountLost(t *testing.T) { - managed := map[string]bool{"a": true, "b": true, "c": true} - tests := []struct { - name string - after map[string]bool - desired map[string]bool - want int - }{ - {"all persisted", map[string]bool{"a": true, "b": true}, map[string]bool{"a": true, "b": true}, 0}, - {"nothing persisted", map[string]bool{}, map[string]bool{"a": true, "b": true}, 2}, - {"partially persisted", map[string]bool{"a": true}, map[string]bool{"a": true, "b": true}, 1}, - {"stale disable not re-enabled", map[string]bool{"a": true, "c": true}, map[string]bool{"a": true}, 1}, - {"unmanaged labels ignored", map[string]bool{"a": true, "com.example.x": true}, map[string]bool{"a": true}, 0}, - {"stock desired and reached", map[string]bool{}, map[string]bool{}, 0}, - } - for _, tt := range tests { - t.Run(tt.name, func(t *testing.T) { - if got := countLost(tt.after, tt.desired, managed); got != tt.want { - t.Errorf("countLost() = %d, want %d", got, tt.want) - } - }) - } -} - -func TestPersistentOverridesSupported(t *testing.T) { - tests := []struct { - v string - want bool - }{ - {"17.5", false}, - {"18.3", false}, - {"18.4.1", false}, - {"18.5", true}, - {"18.5.1", true}, - {"26.5", true}, - {"18", false}, - {"", false}, - {"garbage", false}, - } - for _, tt := range tests { - if got := PersistentOverridesSupported(tt.v); got != tt.want { - t.Errorf("PersistentOverridesSupported(%q) = %t, want %t", tt.v, got, tt.want) - } - } -} diff --git a/status_test.go b/status_test.go deleted file mode 100644 index 3650571..0000000 --- a/status_test.go +++ /dev/null @@ -1,43 +0,0 @@ -package simslim - -import "testing" - -func TestDroppedCategories(t *testing.T) { - search, ok := CategoryByID("search") - if !ok { - t.Fatal("search category not found") - } - disabled := map[string]bool{ - search.Labels[0]: true, - search.Labels[1]: true, - "com.apple.assistant_cdmd": true, - "com.apple.not-a-managed-d": true, - } - - got := DroppedCategories(disabled) - - byID := map[string]DroppedCategory{} - for _, c := range got { - byID[c.ID] = c - } - if len(got) != 2 { - t.Fatalf("dropped categories = %d, want 2 (search, siri)", len(got)) - } - if labels := byID["search"].Labels; len(labels) != 2 { - t.Errorf("search dropped labels = %v, want 2", labels) - } - if labels := byID["siri"].Labels; len(labels) != 1 || labels[0] != "com.apple.assistant_cdmd" { - t.Errorf("siri dropped labels = %v, want [com.apple.assistant_cdmd]", labels) - } - for _, c := range got { - if c.Downside == "" { - t.Errorf("dropped category %q has no downside", c.ID) - } - } -} - -func TestDroppedCategoriesEmpty(t *testing.T) { - if got := DroppedCategories(map[string]bool{}); len(got) != 0 { - t.Errorf("DroppedCategories(stock) = %v, want empty", got) - } -} diff --git a/swift/Package.swift b/swift/Package.swift new file mode 100644 index 0000000..647cf02 --- /dev/null +++ b/swift/Package.swift @@ -0,0 +1,30 @@ +// swift-tools-version:6.0 +// Copyright (c) 2026 Pavel Akhrameev (Swift port). MIT License; see LICENSE. + +import PackageDescription + +// No third-party packages, ever. `scripts/verify-deps.sh` fails the check if +// the package declares one. +let package = Package( + name: "simslim", + platforms: [.macOS(.v14)], + products: [ + .executable(name: "simslim", targets: ["simslim"]) + ], + dependencies: [], + targets: [ + // All logic. Never writes to stdout. + .target(name: "SimSlimKit"), + // Argument parsing and printing, with injected output and command runner so + // every command is testable without a terminal or a simulator. + .target(name: "SimSlimCLI", dependencies: ["SimSlimKit"]), + // main.swift only. + .executableTarget(name: "simslim", dependencies: ["SimSlimCLI", "SimSlimKit"]), + // Test-only helpers (a fake simulator host). Not a dependency of any product. + .target(name: "TestSupport", dependencies: ["SimSlimKit"], path: "Tests/TestSupport"), + .testTarget(name: "SimSlimKitTests", dependencies: ["SimSlimKit", "TestSupport"]), + .testTarget( + name: "SimSlimCLITests", dependencies: ["SimSlimCLI", "SimSlimKit", "TestSupport"]), + ], + swiftLanguageModes: [.v5] +) diff --git a/swift/Sources/SimSlimCLI/Arguments.swift b/swift/Sources/SimSlimCLI/Arguments.swift new file mode 100644 index 0000000..cea7311 --- /dev/null +++ b/swift/Sources/SimSlimCLI/Arguments.swift @@ -0,0 +1,79 @@ +// Copyright (c) 2026 Pavel Akhrameev (Swift port). MIT License; see LICENSE. + +import Foundation +import SimSlimKit + +struct FlagSpec { + let name: String + let isBool: Bool + var onlyOnce = false + + static func bool(_ name: String, onlyOnce: Bool = false) -> FlagSpec { + FlagSpec(name: name, isBool: true, onlyOnce: onlyOnce) + } + static func string(_ name: String) -> FlagSpec { FlagSpec(name: name, isBool: false) } +} + +struct ParsedArguments { + var positionals: [String] = [] + var bools: [String: Bool] = [:] + var strings: [String: String] = [:] + + func bool(_ name: String) -> Bool { bools[name] ?? false } + func string(_ name: String) -> String { strings[name] ?? "" } + func has(_ name: String) -> Bool { bools[name] != nil || strings[name] != nil } +} + +/// Parses flags and positionals in any order (`on --except search` and +/// `on --except search ` are the same), as the Go CLI does. Accepts `-flag` +/// and `--flag`, `--flag=value` and `--flag value`; `--` ends flag parsing. A bool +/// flag never consumes the next token. +func parseArguments(_ tokens: [String], specs: [FlagSpec]) throws -> ParsedArguments { + var parsed = ParsedArguments() + var i = 0 + while i < tokens.count { + let token = tokens[i] + i += 1 + if token == "--" { + parsed.positionals.append(contentsOf: tokens[i...]) + break + } + guard token.hasPrefix("-"), token.count > 1 else { + parsed.positionals.append(token) + continue + } + + let body = token.drop(while: { $0 == "-" }) + let name: String + var inline: String? + if let eq = body.firstIndex(of: "=") { + name = String(body[.. Void + + public var version: String + public var environment: [String: String] + public var runner: CommandRunning + /// Where simulators' launchd disable overrides live on the host; tests redirect it. + public var storeRoot: String + /// Whose `Library/Developer` holds the device sets `watch` observes. + public var home: String + /// Whether `top` may draw its live screen; false sends it to one-shot output. + public var isInteractive: @Sendable () -> Bool + /// Set by Ctrl-C; `watch` and `top` run until it is. + public var interrupt: InterruptFlag + /// Where `profile` reads its prompts and keys; nil uses the terminal. + var wizardInput: WizardInput? + public var stdout: Sink + public var stderr: Sink + + public init( + version: String = simslimVersion, + environment: [String: String] = ProcessInfo.processInfo.environment, + runner: CommandRunning = SystemCommandRunner(), + storeRoot: String = "/private/var/tmp", + home: String = NSHomeDirectory(), + isInteractive: @escaping @Sendable () -> Bool = { + isatty(STDIN_FILENO) != 0 && isatty(STDOUT_FILENO) != 0 + }, + interrupt: InterruptFlag = InterruptFlag(), + stdout: @escaping Sink, + stderr: @escaping Sink + ) { + self.version = version + self.environment = environment + self.runner = runner + self.storeRoot = storeRoot + self.home = home + self.isInteractive = isInteractive + self.interrupt = interrupt + self.stdout = stdout + self.stderr = stderr + } + + /// Everything a command needs, after the global options are applied. + struct Context { + var simctl: Simctl + var bootTimeout: TimeInterval + var parsed: ParsedArguments + var home: String + var isInteractive: Bool + var interrupt: InterruptFlag + var wizardInput: WizardInput + var stdout: Sink + var stderr: Sink + } + + static let globalSpecs: [FlagSpec] = [ + .string("set"), .string("boot-timeout"), .string("spawn-timeout"), + ] + + static let commandSpecs: [String: [FlagSpec]] = [ + "list": [.bool("json", onlyOnce: true), .bool("booted")], + "profiles": [.bool("json", onlyOnce: true)], + "status": [.bool("json", onlyOnce: true), .bool("dropped")], + "verify": [ + .bool("json", onlyOnce: true), .string("profile"), .string("except"), .string("keep"), + ], + "doctor": [.bool("json", onlyOnce: true), .string("requires"), .bool("list")], + "measure": [.bool("json", onlyOnce: true)], + "boot": [.bool("json", onlyOnce: true)], + "shutdown": [.bool("json", onlyOnce: true)], + "on": [ + .string("profile"), .string("except"), .string("keep"), .bool("no-reboot"), + .bool("preserve-boot-state"), + ], + "off": [.bool("preserve-boot-state")], + "profile": [], + "clone": [.bool("json", onlyOnce: true)], + "repair-clone": [.bool("json", onlyOnce: true)], + "top": [.bool("json", onlyOnce: true)], + "size": [.bool("json", onlyOnce: true)], + "disk-categories": [.bool("json", onlyOnce: true)], + "disk-plan": [.bool("json", onlyOnce: true)], + "disk-clean": [ + .bool("json", onlyOnce: true), .string("categories"), .bool("confirm"), + .bool("preserve-boot-state"), + ], + "watch": [ + .bool("json"), .string("profile"), .string("except"), .string("keep"), .string("interval"), + ], + "rename": [.bool("json", onlyOnce: true)], + "erase": [.bool("json", onlyOnce: true)], + "delete": [.bool("json", onlyOnce: true)], + "enable": [.bool("json", onlyOnce: true), .string("save")], + "disable": [.bool("json", onlyOnce: true), .string("save")], + ] + + /// Runs the command line (without the program name) and returns the exit status. + public func run(_ arguments: [String]) -> Int32 { + guard let first = arguments.first else { + stdout(usageText) + return 2 + } + switch first { + case "-v", "--version", "version": + stdout("simslim \(version)\n") + return 0 + case "-h", "--help", "help": + stdout(usageText) + return 0 + default: + break + } + + do { + return try dispatch(arguments) + } catch let error as SimSlimError { + stderr("simslim: \(error.message)\n") + return 1 + } catch { + stderr("simslim: \(error.localizedDescription)\n") + return 1 + } + } + + private func dispatch(_ arguments: [String]) throws -> Int32 { + // Global options may precede the command name. + var index = 0 + var leading: [String] = [] + while index < arguments.count, arguments[index].hasPrefix("-") { + leading.append(arguments[index]) + let name = arguments[index].drop(while: { $0 == "-" }) + index += 1 + if !name.contains("="), CLI.globalSpecs.first(where: { $0.name == name }) != nil, + index < arguments.count + { + leading.append(arguments[index]) + index += 1 + } + } + guard index < arguments.count else { + // Only global options were given. + _ = try parseArguments(leading, specs: CLI.globalSpecs) + stdout(usageText) + return 2 + } + + let command = arguments[index] + let rest = leading + Array(arguments[(index + 1)...]) + + guard let specs = CLI.commandSpecs[command] else { + stderr("unknown command \"\(command)\"\n\n") + stdout(usageText) + return 2 + } + + let parsed: ParsedArguments + do { + parsed = try parseArguments(rest, specs: specs + CLI.globalSpecs) + } catch let error as SimSlimError where error.message == "flag needs an argument: --set" { + throw SimSlimError("--set requires a device set name (such as `testing`) or a path") + } + + var simctl = Simctl(runner: runner) + simctl.storeRoot = storeRoot + let bootTimeout = try applyGlobalOptions(parsed, to: &simctl) + let context = Context( + simctl: simctl, bootTimeout: bootTimeout, parsed: parsed, home: home, + isInteractive: isInteractive(), interrupt: interrupt, + wizardInput: wizardInput ?? .terminal(write: stderr), + stdout: stdout, stderr: stderr) + + switch command { + case "list": return try cmdList(context) + case "profiles": return try cmdProfiles(context) + case "status": return try cmdStatus(context) + case "verify": return try cmdVerify(context) + case "doctor": return try cmdDoctor(context) + case "measure": return try cmdMeasure(context) + case "boot": return try cmdBoot(context) + case "shutdown": return try cmdShutdown(context) + case "on": return try cmdOn(context) + case "off": return try cmdOff(context) + case "clone": return try cmdClone(context) + case "repair-clone": return try cmdRepairClone(context) + case "rename": return try cmdRename(context) + case "erase": return try cmdErase(context) + case "delete": return try cmdDelete(context) + case "profile": return try cmdProfile(context) + case "top": return try cmdTop(context) + case "size": return try cmdSize(context) + case "disk-categories": return try cmdDiskCategories(context) + case "disk-plan": return try cmdDiskPlan(context) + case "disk-clean": return try cmdDiskClean(context) + case "watch": return try cmdWatch(context) + case "enable": return try cmdEnable(context) + case "disable": return try cmdDisable(context) + default: preconditionFailure("command \(command) has specs but no handler") + } + } + + /// Applies --set, --boot-timeout and --spawn-timeout (each also settable from + /// the environment, for the two timeouts) and returns the boot timeout. + private func applyGlobalOptions(_ parsed: ParsedArguments, to simctl: inout Simctl) throws + -> TimeInterval + { + if parsed.has("set") { + let sets = splitList(parsed.string("set")) + if sets.isEmpty { + throw SimSlimError("--set requires a device set name (such as `testing`) or a path") + } + for set in sets { simctl.registerDeviceSet(set) } + } + + func duration(flag: String, env: String, fallback: TimeInterval) throws -> TimeInterval { + let raw = parsed.has(flag) ? parsed.string(flag) : (environment[env] ?? "") + if raw.isEmpty { return fallback } + let value: TimeInterval + do { + value = try parseGoDuration(raw) + } catch { + throw SimSlimError( + "invalid value \"\(raw)\" for flag -\(flag): \((error as? SimSlimError)?.message ?? "parse error")" + ) + } + if value <= 0 { + let example = flag == "boot-timeout" ? "15m" : "2m" + throw SimSlimError("--\(flag) must be a positive duration (such as `\(example)`)") + } + return value + } + + simctl.spawnTimeout = try duration( + flag: "spawn-timeout", env: "SIMSLIM_SPAWN_TIMEOUT", fallback: simctl.spawnTimeout) + return try duration(flag: "boot-timeout", env: "SIMSLIM_BOOT_TIMEOUT", fallback: 600) + } +} + +func oneUDID(_ positionals: [String]) throws -> String { + guard positionals.count == 1 else { + throw SimSlimError("expected exactly one simulator UDID (see `simslim list`)") + } + return positionals[0] +} diff --git a/swift/Sources/SimSlimCLI/CloneCommands.swift b/swift/Sources/SimSlimCLI/CloneCommands.swift new file mode 100644 index 0000000..de817ca --- /dev/null +++ b/swift/Sources/SimSlimCLI/CloneCommands.swift @@ -0,0 +1,67 @@ +// Copyright (c) 2026 Pavel Akhrameev (Swift port). MIT License; see LICENSE. + +import Foundation +import SimSlimKit + +extension CLI { + /// The clone budget, and Ctrl-C handling: an interrupt stops the next step, and + /// the cleanup that deletes an unsafe clone or restores a boot state still runs. + private func cloneHandle(_ context: Context) -> Simctl { + context.interrupt.install() + var simctl = context.simctl + let interrupt = context.interrupt + simctl.cancelled = { interrupt.isSet } + simctl.deadline = simctl.now().addingTimeInterval( + Simctl.cloneOperationTimeout(bootTimeout: context.bootTimeout)) + return simctl + } + + private func progressReporter(_ context: Context, quiet: Bool) -> Reporter? { + if quiet { return nil } + let stderr = context.stderr + return { message in stderr(message + "\n") } + } + + func cmdClone(_ context: Context) throws -> Int32 { + let json = context.parsed.bool("json") + let args = context.parsed.positionals + guard args.count == 2 else { + throw SimSlimError("clone expects a simulator UDID and a new name") + } + let name = try normalizeSimulatorName(args[1]) + let reporter = progressReporter(context, quiet: json) + let created = try cloneHandle(context).cloneDevice( + udid: args[0], name: name, home: context.home, restoreTimeout: context.bootTimeout, + reporter: reporter) + if json { + context.stdout( + try jsonText( + SimulatorMutationOutput(action: "clone", udid: created, name: name, sourceUdid: args[0]))) + } else { + context.stdout("Cloned \(args[0]) as \(goQuote(name)) (\(created)).\n") + } + return 0 + } + + func cmdRepairClone(_ context: Context) throws -> Int32 { + let json = context.parsed.bool("json") + let args = context.parsed.positionals + guard args.count == 2 else { + throw SimSlimError("repair-clone expects the source UDID and cloned simulator UDID") + } + let reporter = progressReporter(context, quiet: json) + try cloneHandle(context).repairClonedDevice( + sourceUDID: args[0], cloneUDID: args[1], home: context.home, + restoreTimeout: context.bootTimeout, reporter: reporter) + if json { + context.stdout( + try jsonText( + SimulatorMutationOutput(action: "repair-clone", udid: args[1], sourceUdid: args[0]))) + } else { + context.stdout( + "Repaired clone \(args[1]) and verified no links or open files into specified source \(args[0]).\n" + ) + } + return 0 + } +} diff --git a/swift/Sources/SimSlimCLI/Commands.swift b/swift/Sources/SimSlimCLI/Commands.swift new file mode 100644 index 0000000..53bd735 --- /dev/null +++ b/swift/Sources/SimSlimCLI/Commands.swift @@ -0,0 +1,236 @@ +// Copyright (c) 2026 Pavel Akhrameev (Swift port). MIT License; see LICENSE. + +import Foundation +import SimSlimKit + +// The read-only commands. Each returns the exit status; an error is reported by +// the caller as `simslim: ` with status 1. + +extension CLI { + func cmdList(_ context: Context) throws -> Int32 { + let json = context.parsed.bool("json") + guard context.parsed.positionals.isEmpty else { + throw SimSlimError("list takes no arguments") + } + let simctl = context.simctl + var devices = try simctl.listDevices() + if context.parsed.bool("booted") { devices = devices.filter { $0.state == "Booted" } } + devices.sort { a, b in + if a.platformName != b.platformName { return a.platformName < b.platformName } + if a.osVersion != b.osVersion { return a.osVersion > b.osVersion } + if a.name != b.name { return a.name < b.name } + return a.udid < b.udid + } + + var memory: [String: MemoryMeasurement] = [:] + var memoryErrors: [String: String] = [:] + if json { + let booted = devices.filter { $0.state == "Booted" }.map(\.udid) + (memory, memoryErrors) = simctl.measureMany(udids: booted) + } + + var summaries: [DeviceSummary] = [] + for device in devices { + let managed = Profile().desired(for: device).count + var tag = "shutdown" + var summary = DeviceSummary(device: device, managedTotal: managed) + if device.state == "Booted" { + tag = "booted" + summary.memory = memory[device.udid] + summary.memoryError = memoryErrors[device.udid] ?? "" + do { + let status = try simctl.readStatus(for: device).status + tag = "booted · \(status.managedDisabled)/\(managed) slim" + summary.managedDisabled = status.managedDisabled + } catch { + summary.statusError = error.localizedDescription + } + } + summaries.append(summary) + if !json { + var line = + "\(device.udid) \(padRight(truncate(device.name, 22), 22)) " + + "\(padRight(device.runtimeName, 14)) \(tag)" + if !device.set.isEmpty && device.set != "default" { line += " (\(device.set))" } + context.stdout(line + "\n") + } + } + if json { context.stdout(try jsonText(summaries)) } + return 0 + } + + func cmdProfiles(_ context: Context) throws -> Int32 { + let json = context.parsed.bool("json") + let args = context.parsed.positionals + guard args.count <= 1 else { + throw SimSlimError("profiles takes at most one category ID (see `simslim profiles`)") + } + let out = context.stdout + + if let id = args.first { + guard let category = Catalog.category(id: id) else { + throw SimSlimError("unknown category \"\(id)\" (see `simslim profiles`)") + } + if json { + out(try jsonText(category)) + return 0 + } + out("\(padRight(category.id, 14)) \(category.name)\n") + out(" \(category.description)\n") + out( + " \(category.labels.count) daemons · ~\(category.approxMemoryMB) MB idle footprint when enabled\n" + ) + out(" When disabled: \(category.downside)\n") + out("\nDaemons:\n") + for label in category.labels { + let description = category.serviceDescriptions[label] ?? "" + out(description.isEmpty ? " \(label)\n" : " \(padRight(label, 44)) \(description)\n") + } + for service in category.alwaysEnabled { + out(" \(padRight(service.label, 44)) Always on — \(service.reason)\n") + } + return 0 + } + + if json { + out(try jsonText(Catalog.categories)) + return 0 + } + for category in Catalog.categories { + out("\(padRight(category.id, 14)) \(category.name)\n") + out( + " \(category.labels.count) daemons · ~\(category.approxMemoryMB) MB idle footprint when enabled\n" + ) + out(" When disabled: \(category.downside)\n") + for service in category.alwaysEnabled { + out(" Always on: \(service.label) — \(service.reason)\n") + } + } + out( + "\n\(Catalog.slimmableSet.count) daemons across \(Catalog.categories.count) categories. " + + "Core workflow and deadlock-prone daemons are never disabled.\n") + out( + "Memory estimates are iOS 26.5 clean-boot measurements; they vary by runtime and workload and are not additive.\n" + ) + return 0 + } + + func cmdStatus(_ context: Context) throws -> Int32 { + let json = context.parsed.bool("json") + let showDropped = context.parsed.bool("dropped") + let udid = try oneUDID(context.parsed.positionals) + let (status, disabled) = try context.simctl.readStatus(udid: udid) + let dropped = showDropped ? Catalog.droppedCategories(disabled: disabled) : [] + + if json { + context.stdout( + try jsonText(StatusOutput(status: status, verdict: status.verdict, dropped: dropped))) + return 0 + } + let out = context.stdout + out( + "\(udid): \(status.managedDisabled)/\(status.managedTotal) managed launchd labels disabled (\(status.verdict))\n" + ) + if status.managedDisabled > 0 && !status.persistent { + out( + " This runtime cannot persist launchd overrides: the state reverts to stock at the next reboot.\n" + ) + } + if showDropped { + if dropped.isEmpty { out(" Nothing dropped; every managed launchd label is enabled.\n") } + for category in dropped { + out(" \(padRight(category.id, 14)) \(category.name) — \(category.downside)\n") + for label in category.labels { out(" \(label)\n") } + } + } + return 0 + } + + func cmdVerify(_ context: Context) throws -> Int32 { + let json = context.parsed.bool("json") + let udid = try oneUDID(context.parsed.positionals) + let profile = try buildProfile( + profilePath: context.parsed.string("profile"), except: context.parsed.string("except"), + keep: context.parsed.string("keep")) + let result = try context.simctl.verifyProfile(udid: udid, profile: profile) + let out = context.stdout + + if json { + out(try jsonText(result)) + } else if result.ok { + out("\(udid) matches the profile: all expected disable overrides are applied.\n") + } else { + out( + "\(udid) does not match the profile (\(result.missing.count) missing, \(result.extra.count) extra):\n" + ) + for label in result.missing { + out(" missing \(label) (should be disabled, is enabled)\n") + } + for label in result.extra { out(" extra \(label) (disabled beyond the profile)\n") } + out("Re-run `simslim on` with the same profile to repair.\n") + } + return result.ok ? 0 : 1 + } + + func cmdDoctor(_ context: Context) throws -> Int32 { + let json = context.parsed.bool("json") + let out = context.stdout + + if context.parsed.bool("list") { + guard context.parsed.positionals.isEmpty else { + throw SimSlimError("doctor --list takes no arguments") + } + if json { + out(try jsonText(Catalog.features)) + return 0 + } + for feature in Catalog.features { + out( + "\(padRight(feature.id, 16)) \(padRight(feature.name, 38)) \(feature.labels.joined(separator: ", "))\n" + ) + } + return 0 + } + + let udid = try oneUDID(context.parsed.positionals) + let features = try Catalog.resolveFeatures(splitList(context.parsed.string("requires"))) + guard !features.isEmpty else { + throw SimSlimError( + "doctor needs at least one feature via --requires (see `simslim doctor --list`)") + } + + let (_, disabled) = try context.simctl.readStatus(udid: udid) + var report = Catalog.diagnoseFeatures(features, disabled: disabled) + report.udid = udid + + if json { + out(try jsonText(report)) + } else { + let broken = report.features.filter { !$0.ok }.count + out( + "\(udid): \(report.features.count - broken)/\(report.features.count) required features OK\n" + ) + for feature in report.features { + if feature.ok { + out(" ok \(feature.id)\n") + } else { + out(" BROKEN \(feature.id) — \(feature.disabled.joined(separator: ", ")) disabled\n") + } + } + } + return report.ok ? 0 : 1 + } + + func cmdMeasure(_ context: Context) throws -> Int32 { + let udid = try oneUDID(context.parsed.positionals) + let measurement = try context.simctl.measure(udid: udid) + if context.parsed.bool("json") { + context.stdout(try jsonText(measurement)) + } else { + context.stdout( + "\(udid): \(measurement.processes) processes, \(humanBytes(measurement.bytes)) memory footprint (phys_footprint)\n" + ) + } + return 0 + } +} diff --git a/swift/Sources/SimSlimCLI/DiskCommands.swift b/swift/Sources/SimSlimCLI/DiskCommands.swift new file mode 100644 index 0000000..c99a2e9 --- /dev/null +++ b/swift/Sources/SimSlimCLI/DiskCommands.swift @@ -0,0 +1,90 @@ +// Copyright (c) 2026 Pavel Akhrameev (Swift port). MIT License; see LICENSE. + +import Foundation +import SimSlimKit + +extension CLI { + private func bounded(_ simctl: Simctl, by seconds: TimeInterval) -> Simctl { + var copy = simctl + copy.deadline = copy.now().addingTimeInterval(seconds) + return copy + } + + func cmdSize(_ context: Context) throws -> Int32 { + let json = context.parsed.bool("json") + let udid = try oneUDID(context.parsed.positionals) + let bytes = try bounded(context.simctl, by: context.bootTimeout).deviceDiskUsage(udid: udid) + if json { + context.stdout(try jsonText(DiskMeasurement(bytes: bytes))) + } else { + context.stdout("\(udid): \(humanBytes(bytes)) on disk\n") + } + return 0 + } + + func cmdDiskCategories(_ context: Context) throws -> Int32 { + guard context.parsed.positionals.isEmpty else { + throw SimSlimError("disk-categories takes no arguments") + } + if context.parsed.bool("json") { + context.stdout(try jsonText(diskCleanupCategories)) + return 0 + } + for category in diskCleanupCategories { + let availability = category.canClean ? "cleanable" : "measured only" + context.stdout( + "\(padRight(category.id, 22)) \(padRight(category.name, 28)) \(category.risk) · \(availability)\n" + ) + context.stdout(" \(category.downside)\n") + } + return 0 + } + + func cmdDiskPlan(_ context: Context) throws -> Int32 { + let json = context.parsed.bool("json") + let udid = try oneUDID(context.parsed.positionals) + let plan = try bounded(context.simctl, by: context.bootTimeout).planDiskCleanup(udid: udid) + if json { + context.stdout(try jsonText(plan)) + return 0 + } + context.stdout("\(udid): \(humanBytes(plan.cleanableBytes)) currently cleanable\n") + for measurement in plan.categories { + let note = measurement.category.canClean ? "" : " (iOS-managed; measured only)" + context.stdout( + " \(padRight(measurement.category.id, 22)) \(padLeft(humanBytes(measurement.bytes), 8))\(note)\n" + ) + } + if !plan.storage.isEmpty { + context.stdout(" Stored data (read only)\n") + for storage in plan.storage { + context.stdout( + " \(padRight(storage.id, 20)) \(padLeft(humanBytes(storage.bytes), 8))\n") + } + } + return 0 + } + + func cmdDiskClean(_ context: Context) throws -> Int32 { + let json = context.parsed.bool("json") + let udid = try oneUDID(context.parsed.positionals) + guard context.parsed.bool("confirm") else { + throw SimSlimError( + "disk-clean permanently deletes data; pass --confirm after reviewing `simslim disk-plan \(udid)`" + ) + } + let categoryIDs = splitList(context.parsed.string("categories")) + _ = try validateDiskCleanupSelection(categoryIDs) + let result = try bounded(context.simctl, by: context.bootTimeout).cleanDeviceDisk( + udid: udid, categoryIDs: categoryIDs, + preserveBootState: context.parsed.bool("preserve-boot-state")) + if json { + context.stdout(try jsonText(result)) + } else { + context.stdout( + "Cleaned \(udid) and reclaimed \(humanBytes(result.reclaimedBytes)). Generated contents stay deleted; on-demand assets may download again when needed.\n" + ) + } + return 0 + } +} diff --git a/swift/Sources/SimSlimCLI/Duration.swift b/swift/Sources/SimSlimCLI/Duration.swift new file mode 100644 index 0000000..36ec580 --- /dev/null +++ b/swift/Sources/SimSlimCLI/Duration.swift @@ -0,0 +1,59 @@ +// Copyright (c) 2026 Pavel Akhrameev (Swift port). MIT License; see LICENSE. + +import Foundation +import SimSlimKit + +/// Parses durations the way Go's time.ParseDuration does ("90s", "10m", "1h30m", +/// "1.5h", "500ms"), so `--boot-timeout 15m` and SIMSLIM_BOOT_TIMEOUT behave the +/// same in both tools. Returns seconds. +func parseGoDuration(_ text: String) throws -> TimeInterval { + let invalid = SimSlimErrorMessage.invalidDuration(text) + var rest = Substring(text) + var sign = 1.0 + if let first = rest.first, first == "-" || first == "+" { + if first == "-" { sign = -1 } + rest = rest.dropFirst() + } + if rest == "0" { return 0 } + if rest.isEmpty { throw invalid } + + let units: [(String, Double)] = [ + ("ns", 1e-9), ("us", 1e-6), ("µs", 1e-6), ("μs", 1e-6), ("ms", 1e-3), + ("s", 1), ("m", 60), ("h", 3600), + ] + var total = 0.0 + while !rest.isEmpty { + var number = "" + while let c = rest.first, c.isASCII, c.isNumber || c == "." { + number.append(c) + rest = rest.dropFirst() + } + guard !number.isEmpty, let value = Double(number) else { throw invalid } + var unit = "" + while let c = rest.first, !(c.isASCII && (c.isNumber || c == ".")) { + unit.append(c) + rest = rest.dropFirst() + } + if unit.isEmpty { throw SimSlimErrorMessage.missingUnit(text) } + guard let scale = units.first(where: { $0.0 == unit })?.1 else { + throw SimSlimErrorMessage.unknownUnit(unit, text) + } + total += value * scale + } + // Go rejects what overflows int64 nanoseconds (about 292 years); an inf or + // huge value here would also trap later when converted to an Int. + guard total.isFinite, total <= 9_223_372_036.0 else { throw invalid } + return sign * total +} + +enum SimSlimErrorMessage { + static func invalidDuration(_ s: String) -> SimSlimError { + SimSlimError("time: invalid duration \"\(s)\"") + } + static func missingUnit(_ s: String) -> SimSlimError { + SimSlimError("time: missing unit in duration \"\(s)\"") + } + static func unknownUnit(_ unit: String, _ s: String) -> SimSlimError { + SimSlimError("time: unknown unit \"\(unit)\" in duration \"\(s)\"") + } +} diff --git a/swift/Sources/SimSlimCLI/Format.swift b/swift/Sources/SimSlimCLI/Format.swift new file mode 100644 index 0000000..f6b94a5 --- /dev/null +++ b/swift/Sources/SimSlimCLI/Format.swift @@ -0,0 +1,38 @@ +// Copyright (c) 2026 Pavel Akhrameev (Swift port). MIT License; see LICENSE. + +import Foundation +import SimSlimKit + +/// Pads on the right to `width`, counting Unicode scalars like Go's `%-Ns`. +func padRight(_ text: String, _ width: Int) -> String { + let count = text.unicodeScalars.count + return count >= width ? text : text + String(repeating: " ", count: width - count) +} + +/// Shortens to at most `limit` scalars, ending with an ellipsis when cut. +func truncate(_ text: String, _ limit: Int) -> String { + let scalars = Array(text.unicodeScalars) + if scalars.count <= limit { return text } + if limit <= 1 { return "…" } + var out = String.UnicodeScalarView() + out.append(contentsOf: scalars[..<(limit - 1)]) + return String(out) + "…" +} + +func humanBytes(_ bytes: Int64) -> String { + switch bytes { + case (1 << 30)...: return String(format: "%.2f GB", Double(bytes) / Double(1 << 30)) + case (1 << 20)...: return String(format: "%.0f MB", Double(bytes) / Double(1 << 20)) + case (1 << 10)...: return String(format: "%.0f KB", Double(bytes) / Double(1 << 10)) + default: return "\(bytes) B" + } +} + +/// Renders machine-readable output: indented, keys sorted so the output is +/// deterministic, with a trailing newline. (Go emits struct-field order; JSON +/// consumers do not depend on key order.) +func jsonText(_ value: T) throws -> String { + let encoder = JSONEncoder() + encoder.outputFormatting = [.prettyPrinted, .sortedKeys, .withoutEscapingSlashes] + return String(decoding: try encoder.encode(value), as: UTF8.self) + "\n" +} diff --git a/swift/Sources/SimSlimCLI/Mutations.swift b/swift/Sources/SimSlimCLI/Mutations.swift new file mode 100644 index 0000000..f2b9e4d --- /dev/null +++ b/swift/Sources/SimSlimCLI/Mutations.swift @@ -0,0 +1,331 @@ +// Copyright (c) 2026 Pavel Akhrameev (Swift port). MIT License; see LICENSE. + +import Foundation +import SimSlimKit + +// The commands that change simulator state. Each resolves the exact device +// first, so a simctl alias such as `all` can never fan out a boot or a slim. + +extension CLI { + /// A copy of the simctl handle that gives up `seconds` from now. + private func bounded(_ simctl: Simctl, by seconds: TimeInterval) -> Simctl { + var copy = simctl + copy.deadline = copy.now().addingTimeInterval(seconds) + return copy + } + + private func progress(_ context: Context) -> Reporter { + let stderr = context.stderr + return { stderr($0 + "\n") } + } + + func cmdBoot(_ context: Context) throws -> Int32 { + let json = context.parsed.bool("json") + let udid = try oneUDID(context.parsed.positionals) + let device = try context.simctl.findDevice(udid: udid) + let result = SimulatorMutationOutput(action: "boot", udid: udid) + if device.state == "Booted" { + if json { + context.stdout(try jsonText(result)) + } else { + context.stdout("Simulator \(udid) is already booted.\n") + } + return 0 + } + // Booting and waiting for services can take about a minute. Stderr is quiet + // under --json so a consumer reading a combined stream gets clean JSON. + if !json { context.stderr("Booting \(udid)...\n") } + try bounded(context.simctl, by: context.bootTimeout).bootAndWait( + set: device.set, udid: udid) + context.stdout(json ? try jsonText(result) : "Booted \(udid).\n") + return 0 + } + + func cmdShutdown(_ context: Context) throws -> Int32 { + let json = context.parsed.bool("json") + let udid = try oneUDID(context.parsed.positionals) + let device = try context.simctl.findDevice(udid: udid) + let result = SimulatorMutationOutput(action: "shutdown", udid: udid) + if device.state != "Booted" { + if json { + context.stdout(try jsonText(result)) + } else { + context.stdout("Simulator \(udid) is already shut down.\n") + } + return 0 + } + try bounded(context.simctl, by: Simctl.shutdownTimeout).shutdownAndWait( + set: device.set, udid: udid) + context.stdout(json ? try jsonText(result) : "Shut down \(udid).\n") + return 0 + } + + /// Returns a simulator that started shut down to that state. + private func returnToShutdown(_ context: Context, set: String, udid: String) throws { + do { + try context.simctl.shutdownAndWait(set: set, udid: udid) + } catch { + throw SimSlimError("restore original shutdown state: \(error.localizedDescription)") + } + } + + /// Runs `operation`, then restores a shut-down state when asked. The restore + /// happens even when the operation failed, and both failures are reported. + private func withBootStateRestored( + _ context: Context, restore: Bool, set: String, udid: String, + operation: () throws -> Bool + ) throws -> Bool { + var changed = false + var operationError: Error? + do { changed = try operation() } catch { operationError = error } + if restore { + do { + try returnToShutdown(context, set: set, udid: udid) + } catch { + if let operationError { + throw SimSlimError( + "\(operationError.localizedDescription); additionally could not restore original shutdown state: \(error.localizedDescription)" + ) + } + throw error + } + } + if let operationError { throw operationError } + return changed + } + + func cmdOn(_ context: Context) throws -> Int32 { + let parsed = context.parsed + let preserve = parsed.bool("preserve-boot-state") + let noReboot = parsed.bool("no-reboot") + if noReboot && preserve { + throw SimSlimError( + "--no-reboot cannot be combined with --preserve-boot-state: shutting the simulator down discards a no-reboot slim" + ) + } + let udid = try oneUDID(parsed.positionals) + let profile = try buildProfile( + profilePath: parsed.string("profile"), except: parsed.string("except"), + keep: parsed.string("keep")) + // Resolve once: this pins the device's set (routing every simctl call below), + // fails fast on an unknown UDID, and says whether to restore a shut-down state. + let device = try context.simctl.findDevice(udid: udid) + let reporter = progress(context) + let simctl = bounded(context.simctl, by: context.bootTimeout) + let count = profile.desired(for: device).count + + if noReboot { + context.stderr( + "Slimming \(udid) for this boot session: stopping \(count) background services without a reboot.\n" + ) + let changed = try simctl.enableSlimNoReboot( + set: device.set, udid: udid, profile: profile, reporter: reporter) + context.stdout( + changed + ? "Done. Simulator slimmed for this boot session without a reboot.\n" + : "Already slim. Confirmed every profiled daemon is stopped for this boot session.\n") + if device.supportsPersistentOverrides { + context.stdout( + "The disable overrides are also stored, so the next boot should come up slim; `simslim verify` after a reboot confirms it.\n" + ) + } else { + context.stdout( + "\(device.runtimeName) cannot persist overrides: the simulator returns to stock at its next boot, so re-run this command after every boot.\n" + ) + } + return 0 + } + + let startedShutdown = device.state == "Shutdown" + let originallyShutdown = preserve && startedShutdown + if startedShutdown { + context.stderr( + "Slimming \(udid): disabling \(count) background services while it is off, then booting it slim.\n" + ) + } else { + context.stderr( + "Slimming \(udid): disabling \(count) background services. The simulator will reboot to apply the changes.\n" + ) + } + let changed = try withBootStateRestored( + context, restore: originallyShutdown, set: device.set, udid: udid + ) { + try simctl.enableSlim(set: device.set, udid: udid, profile: profile, reporter: reporter) + } + if changed { + if originallyShutdown { + context.stdout("Done. Simulator reconfigured slim and returned to shutdown.\n") + } else if startedShutdown { + context.stdout("Done. Simulator reconfigured slim and booted.\n") + } else { + context.stdout("Done. Simulator reconfigured and rebooted slim.\n") + } + } else if originallyShutdown { + context.stdout("Already slim. Original shutdown state restored.\n") + } else { + context.stdout("Already slim. Nothing to change.\n") + } + return 0 + } + + func cmdOff(_ context: Context) throws -> Int32 { + let preserve = context.parsed.bool("preserve-boot-state") + let udid = try oneUDID(context.parsed.positionals) + let device = try context.simctl.findDevice(udid: udid) + let startedShutdown = device.state == "Shutdown" + let originallyShutdown = preserve && startedShutdown + if startedShutdown { + context.stderr("Restoring \(udid) to stock while it is off, then booting it.\n") + } else { + context.stderr( + "Restoring \(udid) to stock. The simulator will reboot to apply the changes.\n") + } + let reporter = progress(context) + let simctl = bounded(context.simctl, by: context.bootTimeout) + let changed = try withBootStateRestored( + context, restore: originallyShutdown, set: device.set, udid: udid + ) { + try simctl.disableSlim(set: device.set, udid: udid, reporter: reporter) + } + if changed { + if originallyShutdown { + context.stdout("Done. All daemons re-enabled and simulator returned to shutdown.\n") + } else if startedShutdown { + context.stdout("Done. All daemons re-enabled and simulator booted.\n") + } else { + context.stdout("Done. All daemons re-enabled and simulator rebooted.\n") + } + } else if originallyShutdown { + context.stdout("Already stock. Original shutdown state restored.\n") + } else { + context.stdout("Already stock. Nothing to change.\n") + } + return 0 + } + + // MARK: - enable / disable + + /// ` [ids...]`, where each ID argument may itself be a comma-separated + /// list, as in `simslim enable icloud,photos`. + private func udidAndIDs(_ args: [String]) throws -> (udid: String, ids: [String]) { + guard let udid = args.first else { + throw SimSlimError( + "expected a simulator UDID (see `simslim list`), then category IDs or launchd labels (see `simslim profiles`)" + ) + } + return (udid, args.dropFirst().flatMap { splitList($0) }) + } + + /// Progress goes to stderr, except under --json, where a consumer reading a + /// combined stream must get clean JSON. + private func quietIfJSON(_ context: Context) -> Reporter? { + context.parsed.bool("json") ? nil : progress(context) + } + + func cmdEnable(_ context: Context) throws -> Int32 { + let json = context.parsed.bool("json") + let (udid, ids) = try udidAndIDs(context.parsed.positionals) + let out = try bounded(context.simctl, by: context.bootTimeout).enableServices( + udid: udid, ids: ids, save: context.parsed.string("save"), + reporter: quietIfJSON(context)) + if json { + context.stdout(try jsonText(out)) + return 0 + } + if out.live { + context.stdout("Enabled \(out.labels.count) services on \(udid) without a reboot.\n") + } + if !out.notStarted.isEmpty { + context.stdout( + " launchd starts \(out.notStarted.count) of them at the next boot, not in this one: \(out.notStarted.joined(separator: ", "))\n" + ) + } + printSaved(context, out) + return 0 + } + + func cmdDisable(_ context: Context) throws -> Int32 { + let json = context.parsed.bool("json") + let (udid, ids) = try udidAndIDs(context.parsed.positionals) + let out = try bounded(context.simctl, by: context.bootTimeout).disableServices( + udid: udid, ids: ids, save: context.parsed.string("save"), + reporter: quietIfJSON(context)) + if json { + context.stdout(try jsonText(out)) + return 0 + } + if out.live { + if out.labels.isEmpty { + context.stdout("Nothing to stop on \(udid).\n") + } else { + context.stdout("Stopped \(out.labels.count) services on \(udid) without a reboot.\n") + } + } + if !out.stillEnabled.isEmpty { + context.stdout( + " \(out.stillEnabled.count) stay enabled for another fully enabled category or the platform: \(out.stillEnabled.joined(separator: ", "))\n" + ) + } + printSaved(context, out) + return 0 + } + + /// Closes enable and disable with what persists: the saved profile, or a + /// reminder that the next `on` or `watch` pass applies its profile again. + private func printSaved(_ context: Context, _ out: ServicesOutput) { + if out.saved.isEmpty { + context.stdout( + "This lasts until the next `on` or `watch` pass; pass --save to keep it in a profile.\n" + ) + } else if out.live { + context.stdout( + "Saved to \(out.saved). Apply it later with `simslim on \(out.udid) --profile \(out.saved)`.\n" + ) + } else { + context.stdout( + "Saved to \(out.saved); nothing was applied, the simulator is not booted. Apply it with `simslim on \(out.udid) --profile \(out.saved)`.\n" + ) + } + } + + // MARK: - rename / erase / delete + + func cmdRename(_ context: Context) throws -> Int32 { + let json = context.parsed.bool("json") + let args = context.parsed.positionals + guard args.count == 2 else { + throw SimSlimError("rename expects a simulator UDID and a new name") + } + let name = try normalizeSimulatorName(args[1]) + try bounded(context.simctl, by: Simctl.shutdownTimeout).renameDevice(udid: args[0], name: name) + if json { + context.stdout( + try jsonText(SimulatorMutationOutput(action: "rename", udid: args[0], name: name))) + } else { + context.stdout("Renamed \(args[0]) to \(goQuote(name)).\n") + } + return 0 + } + + func cmdErase(_ context: Context) throws -> Int32 { + let json = context.parsed.bool("json") + let udid = try oneUDID(context.parsed.positionals) + try bounded(context.simctl, by: context.bootTimeout).eraseDevice(udid: udid) + context.stdout( + json + ? try jsonText(SimulatorMutationOutput(action: "erase", udid: udid)) + : "Erased simulator \(udid).\n") + return 0 + } + + func cmdDelete(_ context: Context) throws -> Int32 { + let json = context.parsed.bool("json") + let udid = try oneUDID(context.parsed.positionals) + try bounded(context.simctl, by: context.bootTimeout).deleteDevice(udid: udid) + context.stdout( + json + ? try jsonText(SimulatorMutationOutput(action: "delete", udid: udid)) + : "Deleted simulator \(udid).\n") + return 0 + } +} diff --git a/swift/Sources/SimSlimCLI/TopCommand.swift b/swift/Sources/SimSlimCLI/TopCommand.swift new file mode 100644 index 0000000..e3c4fa4 --- /dev/null +++ b/swift/Sources/SimSlimCLI/TopCommand.swift @@ -0,0 +1,45 @@ +// Copyright (c) 2026 Pavel Akhrameev (Swift port). MIT License; see LICENSE. + +import Foundation +import SimSlimKit + +extension CLI { + func cmdTop(_ context: Context) throws -> Int32 { + let args = context.parsed.positionals + guard args.count <= 1 else { throw SimSlimError("top takes at most one simulator UDID") } + let udid = args.first ?? "" + let simctl = context.simctl + + /// A friendly name for a UDID, empty when it cannot be resolved so the output + /// degrades to the short UDID. + func deviceName() -> String { + udid.isEmpty ? "" : ((try? simctl.findDevice(udid: udid))?.name ?? "") + } + func processes() throws -> TopProcesses { + let list = try simctl.measureProcesses(udid: udid) + return TopProcesses( + udid: udid, name: deviceName(), processes: list, + totalBytes: list.reduce(0) { $0 + $1.bytes }) + } + + // --json and piped output are one-shot; the live screen needs a real terminal. + if context.parsed.bool("json") { + context.stdout( + udid.isEmpty + ? try jsonText(try simctl.fleetSnapshot(withDisk: true)) : try jsonText(try processes())) + return 0 + } + if !context.isInteractive { + context.stdout( + udid.isEmpty + ? staticFleet(try simctl.fleetSnapshot(withDisk: false)) : staticProcs(try processes())) + return 0 + } + + context.interrupt.install() + runTopTerminal( + simctl: simctl, udid: udid, name: deviceName(), interrupt: context.interrupt, + write: context.stdout) + return 0 + } +} diff --git a/swift/Sources/SimSlimCLI/TopModel.swift b/swift/Sources/SimSlimCLI/TopModel.swift new file mode 100644 index 0000000..98e1cb0 --- /dev/null +++ b/swift/Sources/SimSlimCLI/TopModel.swift @@ -0,0 +1,516 @@ +// Copyright (c) 2026 Pavel Akhrameev (Swift port). MIT License; see LICENSE. + +import Foundation +import SimSlimKit + +// The state and rendering of `simslim top`, free of any terminal I/O so it can be +// tested: a keypress or a finished measurement goes in, the effects to run and the +// screen text come out. + +let topRefresh: TimeInterval = 2 // fleet/process memory refresh cadence +let topDiskTTL: TimeInterval = 30 // disk usage is slow, so refresh it rarely + +enum TopKey: Equatable { + case up, down, left, right, enter, escape, ctrlC + case character(Character) +} + +/// The column both the fleet table and the drill-down sort on. +enum TopSort { + case ram, cpu, proc, disk, name, state, os +} + +/// Header order: name, os, state, proc, cpu, ram, disk. Vim-nav keys (h/j/k/l) +/// are excluded. +let topSortKeys: [Character: TopSort] = [ + "n": .name, "o": .os, "s": .state, "p": .proc, "c": .cpu, "m": .ram, "d": .disk, +] + +/// Work the model asks the runner to do; each posts a `TopMessage` when done. +enum TopEffect: Equatable { + case refreshFleet + case refreshDisk([String]) + case refreshProcs(String) + case quit +} + +enum TopMessage { + case resize(width: Int, height: Int) + case fleet(Result) + case disk([String: Int64]) + case procs(udid: String, Result<[ProcessUsage], SimSlimError>) +} + +struct TopModel { + enum Screen { case fleet, drill } + + var screen = Screen.fleet + var width = 0 + var height = 0 + + var sims: [TopSim] = [] + var total: Int64 = 0 + var cursor = 0 + var cursorUDID = "" // the selected sim; keeps the cursor anchored across live re-sorts + var error: String? + var loaded = false // the first fleet snapshot has arrived + + var disk: [String: Int64] = [:] + var diskAt: Date? + var diskBusy = false // a du sweep is in flight; don't start another + var sortCol = TopSort.ram + var sortDesc = true + + var selUDID = "" + var selName = "" + var procs: [ProcessUsage] = [] + var procError: String? + var scroll = 0 + + /// Opens straight into one simulator's per-daemon drill-down when given a UDID. + init(drillInto udid: String = "", name: String = "") { + if !udid.isEmpty { + screen = .drill + selUDID = udid + selName = name + } + } + + // MARK: - Update + + mutating func start() -> [TopEffect] { + var effects: [TopEffect] = [.refreshFleet] + if let procs = refreshProcs() { effects.append(procs) } + return effects + } + + private func refreshProcs() -> TopEffect? { + screen == .drill && !selUDID.isEmpty ? .refreshProcs(selUDID) : nil + } + + /// The refresh timer fired. + mutating func tick(now: Date) -> [TopEffect] { + var effects: [TopEffect] = [.refreshFleet] + if let procs = refreshProcs() { effects.append(procs) } + if !diskBusy, let at = diskAt, now.timeIntervalSince(at) > topDiskTTL { + diskBusy = true + effects.append(.refreshDisk(sims.map { $0.device.udid })) + } + return effects + } + + mutating func apply(_ message: TopMessage, now: Date) -> [TopEffect] { + switch message { + case .resize(let w, let h): + width = w + height = h + + case .fleet(.failure(let failure)): + error = failure.message // keep showing the previous snapshot; the footer reports it + + case .fleet(.success(let output)): + error = nil + loaded = true + sims = output.sims + total = output.totalBytes + applySort() + reanchor() + let missing = sims.map { $0.device.udid }.filter { disk[$0] == nil } + if !missing.isEmpty && !diskBusy { + diskBusy = true + return [.refreshDisk(missing)] + } + + case .disk(let sizes): + diskBusy = false + disk.merge(sizes) { _, new in new } + diskAt = now + if sortCol == .disk { + applySort() + reanchor() + } + + case .procs(let udid, let result): + guard udid == selUDID else { break } + switch result { + case .success(let list): + procs = list + procError = nil + case .failure(let failure): + procs = [] + procError = failure.message + } + sortProcs() + if scroll >= procs.count { scroll = max(0, procs.count - 1) } + } + return [] + } + + mutating func key(_ key: TopKey) -> [TopEffect] { + switch key { + case .ctrlC, .character("q"): + return [.quit] + case .up, .character("k"): + if screen == .fleet && cursor > 0 { + cursor -= 1 + cursorUDID = sims[cursor].device.udid + } else if screen == .drill && scroll > 0 { + scroll -= 1 + } + case .down, .character("j"): + if screen == .fleet && cursor < sims.count - 1 { + cursor += 1 + cursorUDID = sims[cursor].device.udid + } else if screen == .drill && scroll < procs.count - 1 { + scroll += 1 + } + case .enter, .right, .character("l"): + if screen == .fleet && cursor < sims.count { + let sim = sims[cursor] + screen = .drill + selUDID = sim.device.udid + selName = sim.device.name + procs = [] + procError = nil + scroll = 0 + return [.refreshProcs(selUDID)] + } + case .escape, .left, .character("h"): + if screen == .drill { + screen = .fleet + selUDID = "" + procs = [] + } + case .character(let ch): + if let column = topSortKeys[ch] { + if screen == .drill && column != .ram && column != .cpu && column != .name { return [] } + setSort(column) + } + } + return [] + } + + /// Points the cursor back at the selected sim after a re-sort or refresh + /// reorders (or removes) rows. + mutating func reanchor() { + if !cursorUDID.isEmpty { + if let index = sims.firstIndex(where: { $0.device.udid == cursorUDID }) { + cursor = index + return + } + cursorUDID = "" + } + if cursor >= sims.count { cursor = max(0, sims.count - 1) } + } + + /// Switches the sort column, or flips direction when the column is already + /// active, then re-sorts the current view. + mutating func setSort(_ column: TopSort) { + if sortCol == column { + sortDesc.toggle() + } else { + sortCol = column + sortDesc = true + } + applySort() + reanchor() + sortProcs() + } + + mutating func applySort() { + let less: (TopSim, TopSim) -> Bool = { a, b in + switch self.sortCol { + case .cpu: return a.memory?.cpu ?? -1 < b.memory?.cpu ?? -1 + case .proc: return a.memory?.processes ?? -1 < b.memory?.processes ?? -1 + case .disk: return self.disk[a.device.udid] ?? 0 < self.disk[b.device.udid] ?? 0 + case .name: return a.device.name < b.device.name + case .state: return a.managedDisabled ?? -1 < b.managedDisabled ?? -1 + case .os: + if a.device.platformName != b.device.platformName { + return a.device.platformName < b.device.platformName + } + return osLess(a.device.osVersion, b.device.osVersion) + case .ram: return a.memory?.bytes ?? -1 < b.memory?.bytes ?? -1 + } + } + sims = stableSorted(sims, descending: sortDesc, less: less) + } + + /// Only RAM, CPU and name apply to processes; other columns fall back to RAM so a + /// fleet sort choice still behaves sensibly in the drill-down. + mutating func sortProcs() { + let less: (ProcessUsage, ProcessUsage) -> Bool = { a, b in + switch self.sortCol { + case .cpu: return a.cpu < b.cpu + case .name: return a.command < b.command + default: return a.bytes < b.bytes + } + } + procs = stableSorted(procs, descending: sortDesc, less: less) + } + + private func stableSorted(_ items: [T], descending: Bool, less: (T, T) -> Bool) -> [T] { + items.enumerated().sorted { a, b in + let (x, y) = descending ? (b.element, a.element) : (a.element, b.element) + if less(x, y) { return true } + if less(y, x) { return false } + return a.offset < b.offset + }.map(\.element) + } + + // MARK: - Rendering + + /// The screen, as lines. Styles are ANSI; every line is cut to the width. + func screenLines() -> [String] { + var lines = screen == .drill ? drillLines() : fleetLines() + if width > 0 { lines = lines.map { fit($0, width) } } + return lines + } + + private static let bold = ("\u{1B}[1m", "\u{1B}[0m") + private static let reverse = ("\u{1B}[7m", "\u{1B}[0m") + private static let faint = ("\u{1B}[2m", "\u{1B}[0m") + + private func styled(_ style: (String, String), _ text: String) -> String { + style.0 + text + style.1 + } + + /// Cuts a plain line to `limit` columns; styling is applied afterwards. + private func fit(_ line: String, _ limit: Int) -> String { + // Lines carry ANSI only at their ends, so cut the visible text in between. + guard let open = line.range(of: "m"), line.hasPrefix("\u{1B}[") else { + return String(String.UnicodeScalarView(line.unicodeScalars.prefix(limit))) + } + let prefix = String(line[.. [String] { + var lines = [styled(TopModel.bold, fleetHeader())] + if let error, !loaded { + lines.append(styled(TopModel.faint, error)) + return lines + } + if !loaded { + lines.append(styled(TopModel.faint, "Loading booted simulators…")) + return lines + } + if sims.isEmpty { + lines.append( + styled(TopModel.faint, "No booted simulators. Boot one with `simslim boot `.")) + return lines + footer() + } + + let foot = footer() + // Keep the cursor row on screen when there are more simulators than lines. + var visible = sims.count + var first = 0 + if height > 0 { + visible = max(1, height - 1 - foot.count) + if visible < sims.count { + first = min(max(0, cursor - visible / 2), sims.count - visible) + } + } + let nameWidth = self.nameWidth + for index in first.. String { + sortCol == column ? (sortDesc ? "▼" : "▲") : "" + } + + func fleetHeader() -> String { + padRight("SIMULATOR" + sortArrow(.name), nameWidth) + " " + padRight("OS" + sortArrow(.os), 14) + + " " + padRight("STATE" + sortArrow(.state), 6) + " " + + padLeft("PROC" + sortArrow(.proc), 5) + " " + padLeft("CPU" + sortArrow(.cpu), 6) + " " + + padLeft("RAM" + sortArrow(.ram), 8) + " " + padLeft("DISK" + sortArrow(.disk), 8) + } + + /// OS(14)+STATE(6)+PROC(5)+CPU(6)+RAM(8)+DISK(8) + 6 separators. + static let fleetFixedColumns = 53 + + /// The SIMULATOR column flexes to fill the terminal: it grows when there is room + /// and shrinks (down to a floor) when there is not. + var nameWidth: Int { + if width <= 0 { return 30 } // no size yet + return min(max(width - TopModel.fleetFixedColumns, 16), 60) + } + + private func footer() -> [String] { + let summary = "\(sims.count) booted · total \(fmtBytes(total))" + let hint = "↑↓ select · ↵ open · sort n·o·s·p·c·m·d · q quit" + var lines = [ + styled(TopModel.faint, String(repeating: "─", count: nameWidth + TopModel.fleetFixedColumns)), + styled(TopModel.faint, summary + " · " + hint), + ] + if let error { lines.append(styled(TopModel.faint, "refresh error: " + error)) } + return lines + } + + func drillLines() -> [String] { + let title = selName.isEmpty ? shortUDID(selUDID) : selName + var lines = [styled(TopModel.bold, "\(title) — daemons by \(drillSortLabel)"), ""] + if let procError { + return lines + [ + styled(TopModel.faint, procError), "", styled(TopModel.faint, "esc back · q quit"), + ] + } + if procs.isEmpty { + return lines + [ + styled(TopModel.faint, "measuring…"), "", styled(TopModel.faint, "esc back · q quit"), + ] + } + lines.append( + styled( + TopModel.bold, + padLeft("RAM" + sortArrow(.ram), 8) + " " + padLeft("CPU" + sortArrow(.cpu), 6) + " " + + "COMMAND" + sortArrow(.name))) + let rows = max(1, visibleRows) + let start = clampScroll(scroll, procs.count, rows) + let end = min(procs.count, start + rows) + for p in procs[start.. String { + guard sim.statusError.isEmpty, let disabled = sim.managedDisabled else { return "?" } + if disabled == sim.managedTotal { return "slim" } + return disabled > 0 ? "part" : "stock" + } + + func osLabel(_ sim: TopSim) -> String { + sim.device.osVersion.isEmpty ? "?" : truncate(sim.device.runtimeName, 14) + } + + func procCount(_ sim: TopSim) -> String { + sim.memory.map { String($0.processes) } ?? "—" + } + + func cpuLabel(_ sim: TopSim) -> String { + sim.memory.map { String(format: "%.0f%%", $0.cpu) } ?? "—" + } + + func ramLabel(_ sim: TopSim) -> String { + if let memory = sim.memory { return fmtBytes(memory.bytes) } + return sim.memoryError.isEmpty ? "—" : "err" + } + + func diskLabel(_ udid: String) -> String { + disk[udid].map(fmtBytes) ?? "…" + } +} + +// MARK: - Shared formatting + +/// Pads on the left to `width`, counting Unicode scalars like Go's `%Ns`. +func padLeft(_ text: String, _ width: Int) -> String { + let count = text.unicodeScalars.count + return count >= width ? text : String(repeating: " ", count: width - count) + text +} + +/// Binary units with one decimal: "512B", "1.5K", "14.2G". +func fmtBytes(_ bytes: Int64) -> String { + let unit: Int64 = 1024 + if bytes < unit { return "\(bytes)B" } + var div = unit + var exp = 0 + var n = bytes / unit + while n >= unit { + div *= unit + exp += 1 + n /= unit + } + let suffix = Array("KMGTPE")[exp] + return String(format: "%.1f", Double(bytes) / Double(div)) + String(suffix) +} + +func shortUDID(_ udid: String) -> String { + udid.unicodeScalars.count > 8 + ? String(String.UnicodeScalarView(udid.unicodeScalars.prefix(8))) : udid +} + +func clampScroll(_ scroll: Int, _ total: Int, _ rows: Int) -> Int { + if scroll < 0 { return 0 } + if scroll > total - rows { return max(0, total - rows) } + return scroll +} + +/// Compares dotted version strings numerically ("9.0" < "26.4", which lexical +/// order gets wrong). Non-numeric segments compare lexically; a missing version +/// sorts first. +func osLess(_ a: String, _ b: String) -> Bool { + let left = a.split(separator: ".", omittingEmptySubsequences: false) + let right = b.split(separator: ".", omittingEmptySubsequences: false) + for i in 0.. String { + var text = + padRight("SIMULATOR", 30) + " " + padRight("OS", 14) + " " + padRight("STATE", 6) + " " + + padLeft("PROC", 5) + " " + padLeft("CPU", 6) + " " + padLeft("RAM", 8) + "\n" + let labels = TopModel() + for sim in out.sims { + text += + padRight(truncate("\(sim.device.name) · \(shortUDID(sim.device.udid))", 30), 30) + " " + + padRight(labels.osLabel(sim), 14) + " " + padRight(labels.stateLabel(sim), 6) + " " + + padLeft(labels.procCount(sim), 5) + " " + padLeft(labels.cpuLabel(sim), 6) + " " + + padLeft(labels.ramLabel(sim), 8) + "\n" + } + return text + "\(out.sims.count) booted · total \(fmtBytes(out.totalBytes))\n" +} + +func staticProcs(_ top: TopProcesses) -> String { + let name = top.name.isEmpty ? shortUDID(top.udid) : top.name + var text = + "\(name) — daemons by RAM\n" + padLeft("RAM", 8) + " " + padLeft("CPU", 6) + " COMMAND\n" + for p in top.processes { + text += + padLeft(fmtBytes(p.bytes), 8) + " " + padLeft(String(format: "%.1f", p.cpu), 5) + + "% " + p.command + "\n" + } + return text +} diff --git a/swift/Sources/SimSlimCLI/TopTerminal.swift b/swift/Sources/SimSlimCLI/TopTerminal.swift new file mode 100644 index 0000000..0a7778a --- /dev/null +++ b/swift/Sources/SimSlimCLI/TopTerminal.swift @@ -0,0 +1,179 @@ +// Copyright (c) 2026 Pavel Akhrameev (Swift port). MIT License; see LICENSE. + +import Foundation +import SimSlimKit + +// The interactive `simslim top`: raw terminal input, an alternate screen, and a +// refresh loop. Everything it decides lives in TopModel; this file only moves +// bytes. Measurements run on their own threads so the screen never waits on one. + +private final class TopMailbox: @unchecked Sendable { + private let lock = NSLock() + private var messages: [TopMessage] = [] + + func post(_ message: TopMessage) { + lock.lock() + messages.append(message) + lock.unlock() + } + + func drain() -> [TopMessage] { + lock.lock() + defer { lock.unlock() } + let all = messages + messages = [] + return all + } +} + +/// Turns terminal input bytes into keys. A lone ESC at the end of the input is the +/// Escape key; ESC followed by `[` or `O` and a letter is an arrow key. +func parseTopKeys(_ bytes: [UInt8]) -> [TopKey] { + var keys: [TopKey] = [] + var i = 0 + while i < bytes.count { + let b = bytes[i] + switch b { + case 0x1B: + if i + 2 < bytes.count, bytes[i + 1] == 0x5B || bytes[i + 1] == 0x4F { + switch bytes[i + 2] { + case 0x41: keys.append(.up) + case 0x42: keys.append(.down) + case 0x43: keys.append(.right) + case 0x44: keys.append(.left) + default: break + } + i += 3 + continue + } + keys.append(.escape) + case 0x03: keys.append(.ctrlC) + case 0x0D, 0x0A: keys.append(.enter) + case 0x20...0x7E: keys.append(.character(Character(Unicode.Scalar(b)))) + default: break // other control bytes and UTF-8 continuation bytes + } + i += 1 + } + return keys +} + +private func terminalSize() -> (width: Int, height: Int) { + var size = winsize() + if ioctl(STDOUT_FILENO, TIOCGWINSZ, &size) == 0, size.ws_col > 0 { + return (Int(size.ws_col), Int(size.ws_row)) + } + return (0, 0) +} + +/// Runs the live monitor until `q`, Ctrl-C, or an interrupt. It restores the +/// terminal on every way out. +func runTopTerminal( + simctl: Simctl, udid: String, name: String, interrupt: InterruptFlag, write: CLI.Sink +) { + var original = termios() + guard tcgetattr(STDIN_FILENO, &original) == 0 else { return } + var raw = original + cfmakeraw(&raw) + raw.c_oflag |= tcflag_t(OPOST) // keep "\n" meaning a new line + tcsetattr(STDIN_FILENO, TCSANOW, &raw) + write("\u{1B}[?1049h\u{1B}[?25l") + defer { + write("\u{1B}[?25h\u{1B}[?1049l") + tcsetattr(STDIN_FILENO, TCSANOW, &original) + } + + let mailbox = TopMailbox() + var ctl = simctl + ctl.cancelled = { interrupt.isSet } + let work = ctl + + func run(_ effects: [TopEffect]) -> Bool { + for effect in effects { + switch effect { + case .quit: + return false + case .refreshFleet: + Thread.detachNewThread { + mailbox.post( + .fleet( + Result { try work.fleetSnapshot(withDisk: false) }.mapError { + SimSlimError($0.localizedDescription) + })) + } + case .refreshDisk(let udids): + Thread.detachNewThread { + var sizes: [String: Int64] = [:] + for udid in udids { + if let bytes = try? work.deviceDiskUsage(udid: udid) { sizes[udid] = bytes } + } + mailbox.post(.disk(sizes)) + } + case .refreshProcs(let udid): + Thread.detachNewThread { + mailbox.post( + .procs( + udid: udid, + Result { try work.measureProcesses(udid: udid) }.mapError { + SimSlimError($0.localizedDescription) + })) + } + } + } + return true + } + + var model = TopModel(drillInto: udid, name: name) + let size = terminalSize() + model.width = size.width + model.height = size.height + var running = run(model.start()) + var nextTick = Date().addingTimeInterval(topRefresh) + var lastSize = size + var dirty = true + var lastScreen = "" + + while running && !interrupt.isSet { + let current = terminalSize() + if current != lastSize { + lastSize = current + _ = model.apply(.resize(width: current.width, height: current.height), now: Date()) + dirty = true + } + + var input = pollfd(fd: STDIN_FILENO, events: Int16(POLLIN), revents: 0) + if poll(&input, 1, 50) > 0, input.revents & Int16(POLLIN) != 0 { + var buffer = [UInt8](repeating: 0, count: 64) + let n = read(STDIN_FILENO, &buffer, buffer.count) + if n > 0 { + for key in parseTopKeys(Array(buffer[0..= nextTick { + nextTick = Date().addingTimeInterval(topRefresh) + running = run(model.tick(now: Date())) && running + } + + if dirty { + dirty = false + var lines = model.screenLines() + if model.height > 0 && lines.count > model.height { + lines = Array(lines.prefix(model.height)) + } + let screen = lines.map { $0 + "\u{1B}[K" }.joined(separator: "\n") + "\u{1B}[J" + if screen != lastScreen { + lastScreen = screen + write("\u{1B}[H" + screen) + } + } + } +} diff --git a/swift/Sources/SimSlimCLI/Usage.swift b/swift/Sources/SimSlimCLI/Usage.swift new file mode 100644 index 0000000..1155317 --- /dev/null +++ b/swift/Sources/SimSlimCLI/Usage.swift @@ -0,0 +1,134 @@ +// Copyright (c) 2026 Pavel Akhrameev (Swift port). MIT License; see LICENSE. + +/// `simslim --help`. +let usageText = """ + simslim runs more iOS, tvOS, watchOS, and visionOS simulators on the same Mac by disabling the + background daemons a simulator does not need. + + USAGE + simslim [args] + + GLOBAL OPTIONS + --set Also scan these device sets (comma-separated). The default + and Xcode `testing` (parallel-testing) sets are always + scanned; use this to add a set at a custom path. + --boot-timeout dur Max time to boot and reconfigure a simulator (default 10m; + e.g. `15m`). Raise it for slow CI runners. Also settable + via the SIMSLIM_BOOT_TIMEOUT environment variable. + --spawn-timeout dur Max time for a single launchctl transition inside the + simulator (default 2m). Raise it for hosts where a busy + first boot makes individual spawns very slow. Also + settable via the SIMSLIM_SPAWN_TIMEOUT environment + variable. + + COMMANDS + list List available simulators and their slim status + --booted Only list booted simulators + profiles [id] Show the daemon categories a slim boot disables; + pass a category ID to list that category's daemons + profile [path] Interactively build a --profile JSON file (writes to + path or into a directory, or stdout when omitted) + on Slim a simulator (persist disables + reboot slim) + --profile path Apply a committed JSON profile (see below); mutually + exclusive with --except/--keep + --except ids Leave these categories enabled (comma-separated) + --keep labels Keep these individual daemons running (comma-separated) + --no-reboot Stop the daemons in the current boot session without a + reboot. Works on every runtime, including iOS 17.x and + 18.3, where it is the only way to slim; there the state + is gone at the next reboot + --preserve-boot-state + Return an initially shutdown simulator to shutdown + off Restore a simulator to stock (re-enable + reboot) + --preserve-boot-state + Return an initially shutdown simulator to shutdown + enable Re-enable categories or individual daemons on a booted + simulator now, without a reboot. IDs are category IDs + or launchd labels, comma- or space-separated. Like + `on --no-reboot`, it lasts until the next `on` or `watch` + pass applies its profile again + --save path Also add them to this profile file ("except" for a + category, "keep" for a daemon), creating it from the + default profile if needed; on a simulator that is not + booted, only the file changes + disable Stop categories or daemons on a booted simulator now, + without a reboot. A daemon shared with another category + that is fully enabled keeps running. To go back to a + profile, run `on --no-reboot --profile path` + --save path Also remove them from this profile file + watch Slim every simulator until Ctrl-C: a shut-down one before + it boots (iOS/tvOS 18.5+, watchOS 11.5+, visionOS 2.5+), + so even its first boot starts none of the profile's + daemons, and every one no-reboot as it boots. The hook + for xcodebuild parallel-testing clones, which are + created stock and deleted per run; point --set at the + parallel-testing device set + --profile path Apply a committed JSON profile (see below); mutually + exclusive with --except/--keep + --except ids Leave these categories enabled (comma-separated) + --keep labels Keep these individual daemons running (comma-separated) + --interval dur How often to rescan for booting simulators (default 3s) + --json One JSON object per event on stdout, a stable interface + for wrappers: wait for "slimmed" after a boot before + enabling services on it + status Report how slim a booted simulator is + --dropped Also list the disabled daemons grouped by category + verify Check that a booted simulator's disable overrides still + match a profile exactly; exits non-zero and lists the + drift otherwise. Catches a silently stock recreated or + erased device; re-run `on` to repair + --profile path Verify against a committed JSON profile; mutually + exclusive with --except/--keep + --except ids The profile's enabled categories (comma-separated) + --keep labels The profile's kept daemons (comma-separated) + doctor Check required features against a booted simulator; + exits non-zero if slimming has broken any of them + --requires ids Comma-separated feature IDs to verify + --list List every checkable feature and its daemons + measure Report a booted simulator's memory footprint + top [udid] Live fleet monitor: booted simulators and their RAM, + CPU, and process counts. Enter a row to drill into a + simulator's per-daemon footprint. Pass a UDID to open + that drill-down directly. --json prints a one-shot snapshot + size Report a simulator's allocated disk footprint + disk-categories Show cleanup and protected system-asset categories + disk-plan Measure reclaimable and stored data without deleting + disk-clean Permanently delete selected per-device data + --categories ids Comma-separated cleanable category IDs + --confirm Required acknowledgement of permanent deletion + --preserve-boot-state + Reboot a simulator that was booted before cleanup + clone Clone apps, data, settings, and the service profile + repair-clone + Repair source-bound state in an existing clone + rename Rename a simulator + boot Boot a simulator and wait for its services + shutdown Shut down a booted simulator + erase Erase a simulator's apps, data, and settings + delete Permanently delete a simulator + --json Print machine-readable JSON (also supported by list, + profiles, status, verify, doctor, enable, disable, and + simulator-management commands) + version Print the version + + Disabling is persistent (stored in the simulator's launchd overrides) and fully + reversible with `simslim off`. Deadlock-prone daemons are never touched. + `simslim enable` and `simslim disable` change a booted simulator live and keep + no state; with --save they also edit a profile, the only record of a slim + simulator, which `on`, `watch`, and `verify` read back. + + A `--profile` file is JSON you commit alongside your project and apply per run + (for example a ci.json and a dev.json). Its "except" and "keep" arrays match the + flags of the same name: + + { "name": "ci", "except": ["search", "store"], "keep": ["com.apple.apsd"] } + + Cleanup permanently removes existing cache, log, diagnostic, and temporary-file + contents; Erase does not bring that history back, although new generated data + appears as iOS and apps run. Downloaded language data is opt-in and may return + when a feature needs it. Required Siri assets are informational only because iOS + restores them after deletion. simslim never modifies the shared iOS runtime. + + https://github.com/mobai-app/simslim · by MobAI (https://mobai.run) + + """ diff --git a/swift/Sources/SimSlimCLI/WatchCommand.swift b/swift/Sources/SimSlimCLI/WatchCommand.swift new file mode 100644 index 0000000..a1d5601 --- /dev/null +++ b/swift/Sources/SimSlimCLI/WatchCommand.swift @@ -0,0 +1,91 @@ +// Copyright (c) 2026 Pavel Akhrameev (Swift port). MIT License; see LICENSE. + +import Foundation +import SimSlimKit + +/// Set when the user presses Ctrl-C (or a test calls `trigger`). `install` makes +/// SIGINT and SIGTERM set it instead of killing the process, so `watch` can stop +/// its in-flight work and return; only `watch` installs it. +public final class InterruptFlag: @unchecked Sendable { + private let lock = NSLock() + private var set = false + private var sources: [DispatchSourceSignal] = [] + + public init() {} + + public var isSet: Bool { + lock.lock() + defer { lock.unlock() } + return set + } + + public func trigger() { + lock.lock() + set = true + lock.unlock() + } + + func install() { + lock.lock() + defer { lock.unlock() } + if !sources.isEmpty { return } + for sig in [SIGINT, SIGTERM] { + signal(sig, SIG_IGN) + // The main thread is busy running the command, so handle on a global queue. + let source = DispatchSource.makeSignalSource(signal: sig, queue: .global()) + source.setEventHandler { [weak self] in self?.trigger() } + source.resume() + sources.append(source) + } + } +} + +extension CLI { + func cmdWatch(_ context: Context) throws -> Int32 { + let parsed = context.parsed + guard parsed.positionals.isEmpty else { throw SimSlimError("watch takes no arguments") } + let profile = try buildProfile( + profilePath: parsed.string("profile"), except: parsed.string("except"), + keep: parsed.string("keep")) + var interval = defaultWatchInterval + if parsed.has("interval") { + let raw = parsed.string("interval") + do { + interval = try parseGoDuration(raw) + } catch { + throw SimSlimError( + "invalid value \"\(raw)\" for flag -interval: \((error as? SimSlimError)?.message ?? "parse error")" + ) + } + } + + let simctl = context.simctl + let interrupt = context.interrupt + interrupt.install() + let stop: @Sendable () -> Bool = { interrupt.isSet } + let stdout = context.stdout + let stderr = context.stderr + + let watcher: Watcher + if parsed.bool("json") { + // One JSON object per event, from several threads at once. + let lock = NSLock() + watcher = Watcher( + simctl: simctl, profile: profile, home: context.home, report: nil, + events: { event in + lock.lock() + stdout(event.jsonLine + "\n") + lock.unlock() + }) + } else { + let sets = simctl.knownSets.map(\.name) + stderr( + "Watching device sets [\(sets.joined(separator: ", "))]; slimming each simulator before it boots where its runtime allows, and no-reboot as it boots. Ctrl-C to stop.\n" + ) + watcher = Watcher( + simctl: simctl, profile: profile, home: context.home, report: { stderr($0 + "\n") }) + } + watcher.run(interval: interval, stop: stop) + return 0 + } +} diff --git a/swift/Sources/SimSlimCLI/WizardModel.swift b/swift/Sources/SimSlimCLI/WizardModel.swift new file mode 100644 index 0000000..26a3b97 --- /dev/null +++ b/swift/Sources/SimSlimCLI/WizardModel.swift @@ -0,0 +1,188 @@ +// Copyright (c) 2026 Pavel Akhrameev (Swift port). MIT License; see LICENSE. + +import Foundation +import SimSlimKit + +// The `simslim profile` checklist as a pure state machine: keys in, screen lines +// out. The terminal side (raw mode, reading bytes) lives in WizardTerminal.swift. + +struct WizardModel { + enum Screen: Equatable { + case features + case daemons(Int) // index into Catalog.categories + } + + enum Outcome: Equatable { + case running, saved, cancelled + } + + let categories: [SimSlimKit.Category] + var screen: Screen = .features + var except: Set = [] + var keep: Set = [] + var cursor = 0 + var top = 0 + var termRows: Int + private(set) var outcome: Outcome = .running + + init(categories: [SimSlimKit.Category] = Catalog.categories, termRows: Int = 24) { + self.categories = categories + self.termRows = termRows + } + + private var rowCount: Int { + switch screen { + case .features: return categories.count + case .daemons(let i): return categories[i].labels.count + } + } + + private var headerLines: [String] { + switch screen { + case .features: + return [ + "Features to keep enabled — everything unchecked is slimmed.", + "[x] whole feature kept · [~] some daemons kept", + ] + case .daemons(let i): + return [ + categories[i].name + " — keep individual daemons enabled.", + "Unchecked daemons in this feature are slimmed.", + ] + } + } + + private var footer: String { + switch screen { + case .features: + return + "↑/↓ move · space keep feature · → pick daemons · a all · n none · enter save · q cancel" + case .daemons: + return "↑/↓ move · space keep daemon · a all · n none · ← back · q cancel" + } + } + + private var visible: Int { max(3, termRows - headerLines.count - 2) } + + mutating func key(_ key: TopKey) { + guard outcome == .running else { return } + switch screen { + case .features: featureKey(key) + case .daemons(let i): daemonKey(key, category: categories[i]) + } + scroll() + } + + private mutating func move(_ delta: Int) { + cursor = min(max(cursor + delta, 0), rowCount - 1) + } + + private mutating func featureKey(_ key: TopKey) { + switch key { + case .up, .character("k"): move(-1) + case .down, .character("j"): move(1) + case .enter: outcome = .saved + case .ctrlC, .character("q"), .character("Q"): outcome = .cancelled + case .character(" "): toggle(&except, categories[cursor].id) + case .right, .character("l"): + screen = .daemons(cursor) + cursor = 0 + top = 0 + case .character("a"), .character("A"): + for c in categories { except.insert(c.id) } + case .character("n"), .character("N"): except = [] + default: break + } + } + + private mutating func daemonKey(_ key: TopKey, category: SimSlimKit.Category) { + switch key { + case .up, .character("k"): move(-1) + case .down, .character("j"): move(1) + case .left, .enter, .character("h"), .character("q"), .character("Q"): + guard case .daemons(let i) = screen else { return } + screen = .features + cursor = i + top = 0 + case .ctrlC: outcome = .cancelled + case .character(" "): toggle(&keep, category.labels[cursor]) + case .character("a"), .character("A"): + for l in category.labels { keep.insert(l) } + case .character("n"), .character("N"): + for l in category.labels { keep.remove(l) } + default: break + } + } + + private func toggle(_ set: inout Set, _ value: String) { + if set.contains(value) { set.remove(value) } else { set.insert(value) } + } + + private mutating func scroll() { + let total = rowCount + if total <= visible { + top = 0 + return + } + if cursor < top { top = cursor } + if cursor >= top + visible { top = cursor - visible + 1 } + top = max(0, min(top, total - visible)) + } + + func rows() -> [String] { + switch screen { + case .features: + return categories.map { c in + var box = "[ ]" + var suffix = "" + if except.contains(c.id) { + box = "[x]" + } else { + let n = c.labels.filter { keep.contains($0) }.count + if n > 0 { + box = "[~]" + suffix = " (\(n) kept)" + } + } + return "\(box) \(padRight(c.id, 14)) \(c.name)\(suffix)" + } + case .daemons(let i): + let c = categories[i] + return c.labels.map { label in + let box = keep.contains(label) ? "[x]" : "[ ]" + if let desc = c.serviceDescriptions[label], !desc.isEmpty { + return truncate("\(box) \(padRight(label, 44)) \(desc)", 76) + } + return truncate("\(box) \(label)", 76) + } + } + } + + /// The full frame, lines separated for a raw terminal ("\r\n" joins them). + func frame() -> String { + let all = rows() + let end = min(top + visible, all.count) + var out = "\u{1B}[H\u{1B}[J" + for h in headerLines { out += h + "\r\n" } + for i in top.. 0 { more += " ↑more" } + if end < all.count { more += " ↓more" } + return out + "\r\n" + footer + more + } + + /// What the wizard produced: whole features in catalog order, and kept daemons + /// that no kept feature already covers, each once, in catalog order. + func selection() -> (except: [String], keep: [String]) { + let exceptIDs = categories.filter { except.contains($0.id) }.map { $0.id } + let covered = Set(categories.filter { except.contains($0.id) }.flatMap { $0.labels }) + var keptLabels: [String] = [] + var seen = Set() + for c in categories where !except.contains(c.id) { + for l in c.labels where keep.contains(l) && !covered.contains(l) && seen.insert(l).inserted { + keptLabels.append(l) + } + } + return (exceptIDs, keptLabels) + } +} diff --git a/swift/Sources/SimSlimCLI/WizardTerminal.swift b/swift/Sources/SimSlimCLI/WizardTerminal.swift new file mode 100644 index 0000000..4a31c9a --- /dev/null +++ b/swift/Sources/SimSlimCLI/WizardTerminal.swift @@ -0,0 +1,141 @@ +// Copyright (c) 2026 Pavel Akhrameev (Swift port). MIT License; see LICENSE. + +import Foundation +import SimSlimKit + +/// Where `simslim profile` gets its input. The default talks to the terminal; +/// tests supply a script. +struct WizardInput { + /// Reads one line in normal (cooked) mode; nil at end of input. + var readLine: (_ prompt: String) -> String? + /// Puts the terminal in per-key mode; returns its height and a restore function. + var enterRaw: () -> (rows: Int, restore: () -> Void)? + /// The next keystroke; nil at end of input. + var nextKey: () -> TopKey? + + static func terminal(write: @escaping CLI.Sink) -> WizardInput { + var pending: [TopKey] = [] + return WizardInput( + readLine: { prompt in + write(prompt) + // One byte at a time: a buffered reader would swallow the keys that follow. + var bytes: [UInt8] = [] + var byte: UInt8 = 0 + while read(STDIN_FILENO, &byte, 1) == 1 { + if byte == 0x0A { return String(decoding: bytes, as: UTF8.self) } + bytes.append(byte) + } + return bytes.isEmpty ? nil : String(decoding: bytes, as: UTF8.self) + }, + enterRaw: { + var original = termios() + guard tcgetattr(STDIN_FILENO, &original) == 0 else { return nil } + var raw = original + cfmakeraw(&raw) + raw.c_oflag |= tcflag_t(OPOST) + guard tcsetattr(STDIN_FILENO, TCSANOW, &raw) == 0 else { return nil } + write("\u{1B}[?1049h\u{1B}[?25l") + var size = winsize() + var rows = 24 + if ioctl(STDOUT_FILENO, TIOCGWINSZ, &size) == 0, size.ws_row >= 6 { + rows = Int(size.ws_row) + } + return ( + rows, + { + write("\u{1B}[?25h\u{1B}[?1049l") + tcsetattr(STDIN_FILENO, TCSANOW, &original) + } + ) + }, + nextKey: { + while pending.isEmpty { + var buffer = [UInt8](repeating: 0, count: 64) + let n = read(STDIN_FILENO, &buffer, buffer.count) + if n <= 0 { return nil } + pending = parseTopKeys(Array(buffer[0.. Int32 { + let args = context.parsed.positionals + guard args.count <= 1 else { throw SimSlimError("profile takes an optional output path") } + let dest = args.first ?? "" + + var intoDir = false + if !dest.isEmpty { + var isDir: ObjCBool = false + if FileManager.default.fileExists(atPath: dest, isDirectory: &isDir) { + if isDir.boolValue { + intoDir = true + } else { + throw SimSlimError("refusing to overwrite \(dest)") + } + } + } + guard context.isInteractive else { + throw SimSlimError("profile is interactive; run it in a terminal") + } + + let input = context.wizardInput + context.stderr("Create a slim profile.\n\n") + let name = (input.readLine("Name (optional): ") ?? "").trimmingCharacters( + in: .whitespacesAndNewlines) + let description = (input.readLine("Description (optional): ") ?? "") + .trimmingCharacters(in: .whitespacesAndNewlines) + + guard let raw = input.enterRaw() else { throw SimSlimError("enter raw mode: not a terminal") } + var model = WizardModel(termRows: raw.rows) + context.stderr(model.frame()) + while model.outcome == .running { + guard let key = input.nextKey() else { + model.key(.ctrlC) // end of input cancels, like Go + break + } + model.key(key) + if model.outcome == .running { context.stderr(model.frame()) } + } + raw.restore() + guard model.outcome == .saved else { + context.stderr("Cancelled; no profile written.\n") + return 0 + } + + let chosen = model.selection() + let data = marshalProfile( + SlimProfile(name: name, description: description, except: chosen.except, keep: chosen.keep)) + context.stderr( + "Keeping \(chosen.except.count) feature(s) fully enabled and \(chosen.keep.count) individual daemon(s); slimming the rest.\n" + ) + let text = String(decoding: data, as: UTF8.self) + + if dest.isEmpty { + context.stdout(text) + return 0 + } + let path = intoDir ? (dest as NSString).appendingPathComponent(profileFileName(name)) : dest + // Exclusive create: never replace a file, even one that appeared during the wizard. + let fd = open(path, O_WRONLY | O_CREAT | O_EXCL | O_NOFOLLOW, 0o644) + if fd < 0 { + if errno == EEXIST && intoDir { + context.stdout(text) + throw SimSlimError( + "\(path) already exists; printed the profile above instead of overwriting it") + } + if errno == EEXIST { throw SimSlimError("refusing to overwrite \(dest)") } + throw SimSlimError("write \(path): \(String(cString: strerror(errno)))") + } + defer { close(fd) } + let written = data.withUnsafeBytes { write(fd, $0.baseAddress, $0.count) } + guard written == data.count else { + unlink(path) + throw SimSlimError("write \(path): \(String(cString: strerror(errno)))") + } + context.stderr("Wrote \(path). Apply it with `simslim on --profile \(path)`.\n") + return 0 + } +} diff --git a/swift/Sources/SimSlimKit/Catalog.swift b/swift/Sources/SimSlimKit/Catalog.swift new file mode 100644 index 0000000..fe5f87a --- /dev/null +++ b/swift/Sources/SimSlimKit/Catalog.swift @@ -0,0 +1,107 @@ +// Copyright (c) 2026 Pavel Akhrameev (Swift port). MIT License; see LICENSE. + +import Foundation + +/// Shown alongside a category for transparency but never part of a slim +/// profile. Earlier versions may have disabled it, so it stays in the mutation +/// allowlist solely to repair that legacy state. +public struct AlwaysEnabledService: Codable, Equatable, Sendable { + public let label: String + public let reason: String + + public init(label: String, reason: String) { + self.label = label + self.reason = reason + } +} + +/// Raw, generated category data (see Generated/CatalogData.swift). +struct CategorySeed { + let id: String + let name: String + let description: String + let downside: String + let approxMemoryMB: Int + let labels: [String] + let alwaysEnabled: [AlwaysEnabledService] +} + +/// Groups launchd daemon labels that a slim boot disables together. +/// +/// The JSON shape is a contract with the SwiftUI app (`gui/Models.swift`). +public struct Category: Codable, Equatable, Sendable { + public let id: String + public let name: String + public let description: String + public let downside: String + public let approxMemoryMB: Int + public let labels: [String] + public let serviceDescriptions: [String: String] + public let alwaysEnabled: [AlwaysEnabledService] + + init(seed: CategorySeed) { + id = seed.id + name = seed.name + description = seed.description + downside = seed.downside + approxMemoryMB = seed.approxMemoryMB + labels = seed.labels + // A label without a description maps to "", exactly like the Go map + // lookup; the tests reject any such label. + serviceDescriptions = Dictionary( + uniqueKeysWithValues: seed.labels.map { ($0, serviceDescriptionByLabel[$0] ?? "") } + ) + alwaysEnabled = seed.alwaysEnabled + } + + private enum CodingKeys: String, CodingKey { + case id, name, description, downside, approxMemoryMB, labels, serviceDescriptions, alwaysEnabled + } + + public func encode(to encoder: Encoder) throws { + var c = encoder.container(keyedBy: CodingKeys.self) + try c.encode(id, forKey: .id) + try c.encode(name, forKey: .name) + try c.encode(description, forKey: .description) + try c.encode(downside, forKey: .downside) + try c.encode(approxMemoryMB, forKey: .approxMemoryMB) + try c.encode(labels, forKey: .labels) + try c.encode(serviceDescriptions, forKey: .serviceDescriptions) + // Go's `omitempty`: absent when there are none. + if !alwaysEnabled.isEmpty { try c.encode(alwaysEnabled, forKey: .alwaysEnabled) } + } + + public init(from decoder: Decoder) throws { + let c = try decoder.container(keyedBy: CodingKeys.self) + id = try c.decode(String.self, forKey: .id) + name = try c.decode(String.self, forKey: .name) + description = try c.decode(String.self, forKey: .description) + downside = try c.decode(String.self, forKey: .downside) + approxMemoryMB = try c.decode(Int.self, forKey: .approxMemoryMB) + labels = try c.decode([String].self, forKey: .labels) + serviceDescriptions = try c.decode([String: String].self, forKey: .serviceDescriptions) + alwaysEnabled = try c.decodeIfPresent([AlwaysEnabledService].self, forKey: .alwaysEnabled) ?? [] + } +} + +/// The complete allowlist of daemons a profile may disable. +/// +/// Categories may overlap: a label lives in every category whose feature needs +/// it, and an excepted category keeps all its labels enabled even when a +/// slimmed category also lists them. `approxMemoryMB` values are rounded median +/// increases in phys_footprint, not additive. +public enum Catalog { + public static let categories: [Category] = categorySeeds.map(Category.init(seed:)) + + public static func category(id: String) -> Category? { + categories.first { $0.id == id } + } + + /// Every label a service profile may disable. + public static let slimmableSet: Set = Set(categories.flatMap(\.labels)) + + /// The complete mutation allowlist. Most labels are slimmable; required + /// labels may only transition back to enabled, for compatibility. + public static let managedSet: Set = + slimmableSet.union(categories.flatMap(\.alwaysEnabled).map(\.label)) +} diff --git a/swift/Sources/SimSlimKit/Clone.swift b/swift/Sources/SimSlimKit/Clone.swift new file mode 100644 index 0000000..69e0c9e --- /dev/null +++ b/swift/Sources/SimSlimKit/Clone.swift @@ -0,0 +1,465 @@ +// Copyright (c) 2026 Pavel Akhrameev (Swift port). MIT License; see LICENSE. + +import Foundation + +// `clone` and `repair-clone`. CoreSimulator's raw clone carries absolute source +// paths in symlinks and generated registries, so the source stays shut down until +// the copy has been rebased, its app registrations rebuilt, its service profile +// verified, and the running clone audited for open source paths. A clone that +// fails any step is deleted rather than returned as ready. + +/// The labels a clone may carry over: only ones simslim is allowed to disable. A +/// source can hold unrelated or obsolete overrides, and cloning must not turn +/// those into managed state or spread an unsafe one. +func desiredCloneDisabled(_ disabled: Set) -> Set { + disabled.intersection(Catalog.slimmableSet) +} + +extension Simctl { + /// The operation budget for one clone or repair, derived from the boot + /// timeout like Go's `CloneOperationTimeout`. + public static func cloneOperationTimeout(bootTimeout: TimeInterval) -> TimeInterval { + 3 * bootTimeout + 2 * Simctl.shutdownTimeout + } + + /// A handle for cleanup that must still run after the operation was cancelled + /// or ran out of time, with a fresh budget. + private func detached(_ seconds: TimeInterval) -> Simctl { + var copy = self + copy.cancelled = nil + copy.deadline = copy.now().addingTimeInterval(seconds) + return copy + } + + // MARK: - clone + + /// Clones a booted or shut-down simulator and returns the new UDID. The source + /// is returned to the boot state it started in, and a clone that cannot be + /// made independent of it is deleted. + public func cloneDevice( + udid: String, name requested: String, home: String, restoreTimeout: TimeInterval, + reporter: Reporter? = nil + ) throws -> String { + let name = try normalizeSimulatorName(requested) + let (source, sourceData) = try simulatorDataDirectory(udid: udid) + if source.state != "Booted" && source.state != "Shutdown" { + throw SimSlimError( + "simulator must be booted or shutdown before cloning (it is \(source.state))") + } + let sourceWasBooted = source.state == "Booted" + + var created: String? + var failure: Error? + do { + created = try cloneBody( + source: source, sourceData: sourceData, name: name, home: home, + restoreTimeout: restoreTimeout, reporter: reporter) + } catch { + failure = error + } + + do { + try detached(restoreTimeout).restoreState( + set: source.set, udid: udid, booted: sourceWasBooted) + } catch { + let restore = error.localizedDescription + if let failure { + throw SimSlimError( + "\(failure.localizedDescription); additionally could not restore the source boot state: \(restore)" + ) + } + if let created { + throw SimSlimError( + "cloned simulator \(created), but could not restore the source boot state: \(restore)") + } + throw SimSlimError("could not restore the source boot state: \(restore)") + } + if let failure { throw failure } + return created ?? "" + } + + private func cloneBody( + source: Device, sourceData: String, name: String, home: String, restoreTimeout: TimeInterval, + reporter: Reporter? + ) throws -> String { + // launchctl state can only be read from a fully booted device, so a shut-down + // source is booted for a moment; both states converge here before the copy. + report(reporter, "Booting \(source.udid) to capture its service profile...") + do { try bootAndWait(set: source.set, udid: source.udid) } catch { + throw SimSlimError( + "boot source to capture its service profile: \(error.localizedDescription)") + } + let disabled: Set + do { disabled = try readDisabled(set: source.set, udid: source.udid) } catch { + throw SimSlimError("capture source service profile: \(error.localizedDescription)") + } + let desired = desiredCloneDisabled(disabled) + do { try shutdown(set: source.set, udid: source.udid) } catch { + throw SimSlimError("shutdown source before cloning: \(error.localizedDescription)") + } + do { try waitShutdown(set: source.set, udid: source.udid) } catch { + throw SimSlimError( + "wait for source shutdown before cloning: \(error.localizedDescription)") + } + + // What exists now, so a clone UDID that names an existing simulator (the + // source included) is recognised before anything can be deleted by it. + let existing = Set(try listDevices().map { $0.udid.uppercased() }) + report(reporter, "Cloning \(source.udid)...") + let output = try xcrunChecked(simctlArgs(set: source.set, ["clone", source.udid, name])) + let created = try Simctl.parseClonedUDID(output.stdoutText) + if created.uppercased() == source.udid.uppercased() || existing.contains(created.uppercased()) { + throw SimSlimError( + "simctl clone returned the UDID of an existing simulator (\(created)); nothing was deleted") + } + + do { + let paths = try cloneFilesystem( + source: source, sourceData: sourceData, cloneUDID: created, home: home) + report(reporter, "Rebasing the clone away from its source...") + try sanitizeClonedDevice(paths) + + // Enforce the captured state instead of trusting a copied launchd database. + // `ensure` also clears a required-to-run label that was disabled in the + // source, and verifies persistence across a reboot when it changes. + do { + try ensure(set: source.set, udid: created, desired: desired, reporter: reporter) + } catch { + throw SimSlimError("restore cloned service profile: \(error.localizedDescription)") + } + try verifyRunningCloneDoesNotOpenSource(paths) + do { try shutdown(set: source.set, udid: created) } catch { + throw SimSlimError("shutdown prepared clone: \(error.localizedDescription)") + } + do { try waitShutdown(set: source.set, udid: created) } catch { + throw SimSlimError("wait for prepared clone shutdown: \(error.localizedDescription)") + } + try verifyCloneIndependence(paths) + } catch { + let cleanup = detached(restoreTimeout).deleteUnsafeClone(set: source.set, udid: created) + if let cleanup { + throw SimSlimError( + "prepare cloned simulator \(created): \(error.localizedDescription); additionally could not delete the unsafe clone: \(cleanup)" + ) + } + throw SimSlimError( + "prepare cloned simulator \(created): \(error.localizedDescription); deleted the unsafe clone" + ) + } + return created + } + + /// Parses `simctl clone` output: exactly one 36-character UDID. + static func parseClonedUDID(_ output: String) throws -> String { + let udid = goTrimSpace(output) + let invalid = SimSlimError("simctl clone returned an invalid UDID \(goQuote(udid))") + let scalars = Array(udid.unicodeScalars) + guard scalars.count == 36 else { throw invalid } + for (index, scalar) in scalars.enumerated() { + if [8, 13, 18, 23].contains(index) { + guard scalar == "-" else { throw invalid } + } else { + guard + ("0"..."9").contains(scalar) || ("a"..."f").contains(scalar) + || ("A"..."F").contains(scalar) + else { throw invalid } + } + } + return udid + } + + // MARK: - repair-clone + + /// Removes direct file-system links and open paths into `sourceUDID` from a + /// clone made by an older simslim. CoreSimulator keeps no clone lineage, so the + /// caller names the real source. The clone keeps its apps, data, settings and + /// service profile, and its boot state; a failed repair leaves it shut down. + public func repairClonedDevice( + sourceUDID: String, cloneUDID: String, home: String, restoreTimeout: TimeInterval, + reporter: Reporter? = nil + ) throws { + if sourceUDID == cloneUDID { + throw SimSlimError("clone source and destination UDIDs must be distinct") + } + let (source, sourceData) = try simulatorDataDirectory(udid: sourceUDID) + let (clone, _) = try simulatorDataDirectory(udid: cloneUDID) + if source.set != clone.set { + throw SimSlimError("source and clone must belong to the same simulator set") + } + if source.platformName != clone.platformName || source.osVersion != clone.osVersion { + throw SimSlimError( + "source and clone runtimes differ (\(source.runtimeName) and \(clone.runtimeName))") + } + for device in [source, clone] where device.state != "Booted" && device.state != "Shutdown" { + throw SimSlimError( + "simulator \(device.udid) must be booted or shutdown before repair (it is \(device.state))" + ) + } + let paths = try cloneFilesystem( + source: source, sourceData: sourceData, cloneUDID: cloneUDID, home: home) + let sourceWasBooted = source.state == "Booted" + let cloneWasBooted = clone.state == "Booted" + + var failure: Error? + do { + try repairBody( + source: source, clone: clone, paths: paths, cloneWasBooted: cloneWasBooted, + reporter: reporter) + } catch { + failure = error + } + + // A failed repair leaves the clone shut down, then the source goes back. + if failure != nil { + do { + try detached(restoreTimeout).restoreState(set: clone.set, udid: cloneUDID, booted: false) + } catch { + failure = SimSlimError( + "\(failure!.localizedDescription); additionally could not leave the clone safely shutdown: \(error.localizedDescription)" + ) + } + } + do { + try detached(restoreTimeout).restoreState( + set: source.set, udid: sourceUDID, booted: sourceWasBooted) + } catch { + let restore = error.localizedDescription + if let failure { + throw SimSlimError( + "\(failure.localizedDescription); additionally could not restore the source boot state: \(restore)" + ) + } + throw SimSlimError("clone repaired, but could not restore the source boot state: \(restore)") + } + if let failure { throw failure } + } + + private func repairBody( + source: Device, clone: Device, paths: CloneFilesystem, cloneWasBooted: Bool, + reporter: Reporter? + ) throws { + // Stop a running legacy clone first so it cannot keep writing through a + // source-bound symlink while the source shuts down. Both devices are offline + // before any copied state is rebuilt. + report(reporter, "Shutting both simulators down...") + do { try restoreState(set: clone.set, udid: clone.udid, booted: false) } catch { + throw SimSlimError("shutdown clone before repair: \(error.localizedDescription)") + } + do { try restoreState(set: source.set, udid: source.udid, booted: false) } catch { + throw SimSlimError("shutdown source before clone repair: \(error.localizedDescription)") + } + + // Sanitizing does not touch launchd's override database. It runs before the + // first boot so a shut-down legacy clone never starts with a Library symlink + // that still resolves into the source. + report(reporter, "Rebasing the clone away from its source...") + try sanitizeClonedDevice(paths) + do { try bootAndWait(set: clone.set, udid: clone.udid) } catch { + throw SimSlimError("boot clone to capture its service profile: \(error.localizedDescription)") + } + let disabled: Set + do { disabled = try readDisabled(set: clone.set, udid: clone.udid) } catch { + throw SimSlimError("capture cloned service profile: \(error.localizedDescription)") + } + do { + try ensure( + set: clone.set, udid: clone.udid, desired: desiredCloneDisabled(disabled), + reporter: reporter) + } catch { + throw SimSlimError("restore repaired clone service profile: \(error.localizedDescription)") + } + try verifyRunningCloneDoesNotOpenSource(paths) + if !cloneWasBooted { + do { try restoreState(set: clone.set, udid: clone.udid, booted: false) } catch { + throw SimSlimError("restore clone shutdown state: \(error.localizedDescription)") + } + } + } + + // MARK: - shared steps + + /// Brings a device to Booted or Shutdown, doing nothing if it already is. + func restoreState(set: String, udid: String, booted: Bool) throws { + let device = try findDevice(udid: udid, set: set) + if booted { + if device.state == "Booted" { return } + try bootAndWait(set: set, udid: udid) + return + } + if device.state == "Shutdown" { return } + try shutdown(set: set, udid: udid) + try waitShutdown(set: set, udid: udid) + } + + /// Stops and deletes a clone that could not be made independent. Returns what + /// went wrong, or nil. + private func deleteUnsafeClone(set: String, udid: String) -> String? { + var stopError: String? + do { + try shutdown(set: set, udid: udid) + try waitShutdown(set: set, udid: udid) + } catch { + stopError = error.localizedDescription + } + do { + _ = try xcrunChecked(simctlArgs(set: set, ["delete", udid])) + return nil + } catch { + if let stopError { + return "stop clone: \(stopError); delete clone: \(error.localizedDescription)" + } + return error.localizedDescription + } + } + + private func cloneFilesystem( + source: Device, sourceData: String, cloneUDID: String, home: String + ) throws -> CloneFilesystem { + let (clone, cloneData) = try simulatorDataDirectory(udid: cloneUDID) + if clone.set != source.set { + throw SimSlimError( + "CoreSimulator placed clone \(cloneUDID) in \(clone.set) instead of source set \(source.set)" + ) + } + let logs = ["Library", "Logs", "CoreSimulator"].reduce(home) { join($0, $1) } + func parent(_ path: String) -> String { + (cleanPath(path) as NSString).deletingLastPathComponent + } + return CloneFilesystem( + sourceUDID: source.udid, cloneUDID: cloneUDID, + sourceDeviceDirectory: parent(sourceData), cloneDeviceDirectory: parent(cloneData), + sourceDataDirectory: sourceData, cloneDataDirectory: cloneData, + sourceLogDirectory: join(logs, source.udid), cloneLogDirectory: join(logs, cloneUDID)) + } + + // MARK: - running audit + + private static let auditAttempts = 3 + private static let auditDelay: TimeInterval = 0.1 + + /// Makes the file-system checks observable at run time too: it catches a copied + /// registry or preference holding an absolute path that no symlink represents. + func verifyRunningCloneDoesNotOpenSource(_ paths: CloneFilesystem) throws { + var last = "" + for attempt in 0.. ( + complete: Bool, error: String? + ) { + let ps: CommandResult + do { ps = try exec(.ps, ["eww", "-axo", "pid=,command="]) } catch { + return (true, "enumerate cloned simulator processes: \(error.localizedDescription)") + } + guard ps.succeeded else { + return (true, "enumerate cloned simulator processes: exit status \(ps.status)") + } + let pids = Simctl.simulatorProcessIDs(fromPS: ps.stdoutText, udid: paths.cloneUDID) + if pids.isEmpty { + return ( + false, "could not identify any running processes for cloned simulator \(paths.cloneUDID)" + ) + } + let result: CommandResult + do { + result = try exec( + .lsof, ["-n", "-P", "-Fpn", "-p", pids.map(String.init).joined(separator: ",")]) + } catch { + return (false, "audit cloned simulator open files: \(error.localizedDescription)") + } + let failure = + result.succeeded ? nil : (result.timedOut ? "signal: killed" : "exit status \(result.status)") + return Simctl.evaluateCloneLsofAudit( + result.stdoutText + result.stderrText, commandFailure: failure, paths: paths) + } + + static func evaluateCloneLsofAudit( + _ output: String, commandFailure: String?, paths: CloneFilesystem + ) -> (complete: Bool, error: String?) { + let parsed = parseCloneLsofOutput(output, paths: paths) + if let first = parsed.references.first { + return ( + true, "clone process \(first.pid) still has a source simulator path open: \(first.path)" + ) + } + // lsof exits 1 when any PID from the snapshot already exited, yet still + // emits complete records for every process that is alive. + if parsed.hasRecords { return (true, nil) } + if let commandFailure { + let message = goTrimSpace(output) + if message.isEmpty { return (false, "audit cloned simulator open files: \(commandFailure)") } + return (false, "audit cloned simulator open files: \(commandFailure): \(message)") + } + return (false, "audit cloned simulator open files returned no process or path records") + } + + /// PIDs whose environment (from `ps eww`) names this simulator, ascending. + static func simulatorProcessIDs(fromPS output: String, udid: String) -> [Int] { + let marker = "SIMULATOR_UDID=" + udid + var seen = Set() + for bytes in output.utf8.split(separator: 10, omittingEmptySubsequences: false) { + let line = String(decoding: bytes, as: UTF8.self) + guard line.contains(marker) else { continue } + guard let field = line.split(whereSeparator: { $0 == " " || $0 == "\t" }).first, + let pid = Int(field), pid > 0 + else { continue } + seen.insert(pid) + } + return seen.sorted() + } + + struct SourceReference: Equatable { + var pid: Int + var path: String + } + + static func parseCloneLsofOutput(_ output: String, paths: CloneFilesystem) -> ( + references: [SourceReference], hasRecords: Bool + ) { + var references: [SourceReference] = [] + var hasRecords = false + var currentPID = 0 + for bytes in output.utf8.split(separator: 10, omittingEmptySubsequences: false) { + guard bytes.count >= 2, let tag = bytes.first else { continue } + let rest = String(decoding: bytes.dropFirst(), as: UTF8.self) + switch tag { + case UInt8(ascii: "p"): + if let pid = Int(rest), pid > 0 { currentPID = pid } else { currentPID = 0 } + case UInt8(ascii: "n"): + guard currentPID > 0 else { continue } + hasRecords = true + let inDevice = + rebasePath( + rest, sourceRoot: paths.sourceDeviceDirectory, cloneRoot: paths.cloneDeviceDirectory) + != nil + let inLogs = + rebasePath( + rest, sourceRoot: paths.sourceLogDirectory, cloneRoot: paths.cloneLogDirectory) != nil + // The roots come from simctl and lsof prints real paths, so a symlinked + // CoreSimulator directory defeats the prefix test; the UDID component + // catches that. + let named = pathContainsComponent(rest, paths.sourceUDID) + if inDevice || inLogs || named { + references.append(SourceReference(pid: currentPID, path: rest)) + } + default: break + } + } + return (references, hasRecords) + } +} diff --git a/swift/Sources/SimSlimKit/CloneFilesystem.swift b/swift/Sources/SimSlimKit/CloneFilesystem.swift new file mode 100644 index 0000000..f83dc29 --- /dev/null +++ b/swift/Sources/SimSlimKit/CloneFilesystem.swift @@ -0,0 +1,402 @@ +// Copyright (c) 2026 Pavel Akhrameev (Swift port). MIT License; see LICENSE. + +import Foundation + +// The file-system half of `clone` and `repair-clone`: everything that turns the +// raw copy CoreSimulator makes into a device that no longer points into its +// source. All of it runs while both devices are shut down. Paths are judged +// byte by byte, symlinks are never followed, and every deletion goes through the +// same containment checks the disk cleanup uses. + +/// The four directories and two log directories a clone is built from. +struct CloneFilesystem { + var sourceUDID: String + var cloneUDID: String + var sourceDeviceDirectory: String + var cloneDeviceDirectory: String + var sourceDataDirectory: String + var cloneDataDirectory: String + var sourceLogDirectory: String + var cloneLogDirectory: String +} + +// MARK: - Path logic + +private let slashByte = UInt8(ascii: "/") + +private func components(_ path: String) -> [[UInt8]] { + Array(cleanPath(path).utf8).split(separator: slashByte, omittingEmptySubsequences: true).map { + Array($0) + } +} + +/// Maps a path below `sourceRoot` to the same place below `cloneRoot`; nil when +/// the path is not at or below the source root (or either is not absolute). +func rebasePath(_ path: String, sourceRoot: String, cloneRoot: String) -> String? { + let root = cleanPath(sourceRoot) + let target = cleanPath(path) + guard root.utf8.first == slashByte, target.utf8.first == slashByte else { return nil } + if Array(root.utf8) == Array(target.utf8) { return cleanPath(cloneRoot) } + guard isStrictDescendant(root, target) else { return nil } + let skip = root == "/" ? 1 : root.utf8.count + 1 + let relative = String(decoding: Array(target.utf8).dropFirst(skip), as: UTF8.self) + return cleanPath(join(cloneRoot, relative)) +} + +/// `target` expressed relative to the directory `base` (both absolute). +func relativePath(from base: String, to target: String) -> String { + let from = components(base) + let to = components(target) + var common = 0 + while common < from.count && common < to.count && from[common] == to[common] { common += 1 } + var parts = Array(repeating: "..", count: from.count - common) + parts += to[common...].map { String(decoding: $0, as: UTF8.self) } + return parts.isEmpty ? "." : parts.joined(separator: "/") +} + +/// Whether any component of the cleaned path is exactly `component`. +func pathContainsComponent(_ path: String, _ component: String) -> Bool { + if component.isEmpty { return false } + let wanted = Array(component.utf8) + return cleanPath(path).utf8.split(separator: slashByte, omittingEmptySubsequences: false) + .contains { Array($0) == wanted } +} + +private func directoryName(_ path: String) -> String { + let bytes = Array(cleanPath(path).utf8) + guard let last = bytes.lastIndex(of: slashByte) else { return "." } + return last == 0 ? "/" : String(decoding: bytes[.. String { String(cString: strerror(errno)) } + +private func readLink(_ path: String) throws -> String { + var buffer = [CChar](repeating: 0, count: Int(PATH_MAX) + 1) + let n = readlink(path, &buffer, buffer.count - 1) + guard n >= 0 else { throw SimSlimError("readlink \(path): \(errnoText())") } + return String(decoding: buffer[0.. String { + target.utf8.first == slashByte ? cleanPath(target) : cleanPath(join(directoryName(link), target)) +} + +private func kind(_ info: stat) -> mode_t { info.st_mode & S_IFMT } + +// MARK: - Validation + +func validateCloneFilesystem(_ paths: CloneFilesystem) throws { + if paths.sourceUDID.isEmpty || paths.cloneUDID.isEmpty || paths.sourceUDID == paths.cloneUDID { + throw SimSlimError("clone source and destination UDIDs must be distinct") + } + for (label, directory) in [ + ("source device", paths.sourceDeviceDirectory), ("clone device", paths.cloneDeviceDirectory), + ("source data", paths.sourceDataDirectory), ("clone data", paths.cloneDataDirectory), + ] { + var info = stat() + guard lstat(directory, &info) == 0 else { + throw SimSlimError("locate \(label) directory: lstat \(directory): \(errnoText())") + } + if kind(info) != S_IFDIR { + throw SimSlimError("\(label) path is not a real directory: \(directory)") + } + } + // The rewrite roots come from simctl; they must look like //data + // before anything below them is rewritten. + for (udid, device, data) in [ + (paths.sourceUDID, paths.sourceDeviceDirectory, paths.sourceDataDirectory), + (paths.cloneUDID, paths.cloneDeviceDirectory, paths.cloneDataDirectory), + ] { + let deviceName = Array(cleanPath(device).utf8.split(separator: slashByte).last ?? []) + let dataName = Array(cleanPath(data).utf8.split(separator: slashByte).last ?? []) + guard String(decoding: deviceName, as: UTF8.self).uppercased() == udid.uppercased(), + String(decoding: dataName, as: UTF8.self) == "data" + else { + throw SimSlimError("simulator data path is not /\(udid)/data: \(data)") + } + } + if cleanPath(paths.sourceDeviceDirectory) == cleanPath(paths.cloneDeviceDirectory) { + throw SimSlimError("clone source and destination UDIDs must be distinct") + } + for (device, data) in [ + (paths.sourceDeviceDirectory, paths.sourceDataDirectory), + (paths.cloneDeviceDirectory, paths.cloneDataDirectory), + ] { + try requireDescendant(device, data) + try requireResolvedDescendant(device, data) + } +} + +// MARK: - Generated stores + +/// Removes the named regular files from `directory` below `dataDirectory`. A +/// missing directory is fine; anything that is not a real directory or regular +/// file stops the clone rather than being followed or guessed at. +private func removeStores( + dataDirectory: String, directory: String, what: String, matching: (String) -> Bool +) throws { + try requireDescendant(dataDirectory, directory) + var info = stat() + if lstat(directory, &info) != 0 { + if errno == ENOENT { return } + throw SimSlimError("locate cloned \(what) data: lstat \(directory): \(errnoText())") + } + if kind(info) != S_IFDIR { + throw SimSlimError("cloned \(what) path is not a real directory: \(directory)") + } + try requireResolvedDescendant(dataDirectory, directory) + for entry in try readDirectory(directory) where matching(entry.name) { + let target = join(directory, entry.name) + try requireDescendant(directory, target) + var targetInfo = stat() + if lstat(target, &targetInfo) != 0 { + if errno == ENOENT { continue } + throw SimSlimError("inspect cloned \(what) store: lstat \(target): \(errnoText())") + } + if kind(targetInfo) != S_IFREG { + throw SimSlimError("cloned \(what) store is not a regular file: \(target)") + } + if unlink(target) != 0 { + throw SimSlimError("reset cloned \(what) store: remove \(target): \(errnoText())") + } + } +} + +func resetClonedLaunchServices(dataDirectory: String) throws { + try removeStores( + dataDirectory: dataDirectory, directory: join(join(dataDirectory, "var"), "db/lsd"), + what: "LaunchServices" + ) { $0.hasPrefix("com.apple.LaunchServices-") && $0.contains(".csstore") } +} + +func resetClonedFrontBoard(dataDirectory: String) throws { + let names: Set = [ + "applicationState.db", "applicationState.db-shm", "applicationState.db-wal", + ] + try removeStores( + dataDirectory: dataDirectory, directory: join(join(dataDirectory, "Library"), "FrontBoard"), + what: "FrontBoard" + ) { names.contains($0) } +} + +/// Clears system-owned indexes, task databases and asset registries that keep +/// absolute simulator paths outside property lists. Their daemons regenerate +/// them; installed apps, app data and downloaded MobileAsset payloads are not on +/// this list. +func resetClonedGeneratedPathState(dataDirectory: String) throws { + func at(_ parts: String...) -> String { parts.reduce(dataDirectory) { join($0, $1) } } + var directories = [ + at("Library", "AppleMediaServices", "Engagement", "internal", "database"), + at("Library", "Spotlight"), + at("Library", "chronod", "replicator"), + at("Library", "com.apple.nsurlsessiond"), + at("private", "var", "MobileAsset", "AssetsV2", "locks"), + at("private", "var", "MobileAsset", "AssetsV2", "persisted"), + at("private", "var", "db", "assetsubscriptiond", "history"), + at("var", "db", "diagnostics", "Persist"), + at("var", "db", "diagnostics", "Special"), + ] + // One `replicatord` per app group. A group that is a symlink is not listed + // here but is not skipped either: its target is rejected by the cleanup check. + let groups = at("Containers", "Shared", "AppGroup") + var groupInfo = stat() + if lstat(groups, &groupInfo) == 0 { + if kind(groupInfo) == S_IFDIR { + for entry in try readDirectory(groups) { + let target = join(join(groups, entry.name), "replicatord") + var info = stat() + if lstat(target, &info) != 0 && (errno == ENOENT || errno == ENOTDIR) { continue } + directories.append(target) + } + } else { + throw SimSlimError("locate cloned replicator state: \(groups) is not a real directory") + } + } else if errno != ENOENT && errno != ENOTDIR { + throw SimSlimError("locate cloned replicator state: lstat \(groups): \(errnoText())") + } + for directory in directories { + do { + try clearDirectoryContents(dataDirectory: dataDirectory, target: directory) + } catch { + throw SimSlimError( + "reset cloned generated path state \(directory): \(error.localizedDescription)") + } + } +} + +// MARK: - Rebasing + +private func replaceAll(in data: Data, _ needle: Data, with replacement: Data) -> Data? { + guard data.range(of: needle) != nil else { return nil } + var out = Data() + var rest = data[...] + while let found = rest.range(of: needle) { + out.append(rest[rest.startIndex..= 0 else { throw SimSlimError("open \(temporary): \(errnoText())") } + var finished = false + defer { + close(fd) + if !finished { unlink(temporary) } + } + guard fchmod(fd, mode & 0o777) == 0 else { throw SimSlimError("chmod: \(errnoText())") } + var offset = 0 + try contents.withUnsafeBytes { raw in + while offset < raw.count { + let n = write(fd, raw.baseAddress! + offset, raw.count - offset) + if n < 0 { + if errno == EINTR { continue } + throw SimSlimError("write \(temporary): \(errnoText())") + } + offset += n + } + } + guard fsync(fd) == 0 else { throw SimSlimError("sync \(temporary): \(errnoText())") } + guard rename(temporary, path) == 0 else { throw SimSlimError("rename: \(errnoText())") } + finished = true +} + +/// Property lists often store simulator-local file URLs (wallpaper is the usual +/// example). The two UDIDs have the same byte length, so swapping one for the +/// other keeps both XML and binary plists valid and points the setting at the clone. +func rebaseClonePropertyLists(_ paths: CloneFilesystem) throws { + guard paths.sourceUDID.utf8.count == paths.cloneUDID.utf8.count else { + throw SimSlimError("source and clone UDIDs must have equal lengths") + } + let source = Data(paths.sourceUDID.utf8) + let clone = Data(paths.cloneUDID.utf8) + try walkTree(paths.cloneDeviceDirectory, skippingVanished: true) { path, info in + guard kind(info) == S_IFREG, path.lowercased().hasSuffix(".plist") else { return .descend } + let contents: Data + do { + contents = try Data(contentsOf: URL(fileURLWithPath: path)) + } catch { + throw SimSlimError( + "read cloned property list \(path): \(error.localizedDescription)") + } + guard let rebased = replaceAll(in: contents, source, with: clone) else { return .descend } + do { + try replaceRegularFile(path, contents: rebased, mode: info.st_mode) + } catch { + throw SimSlimError( + "rebase cloned property list \(path): \(error.localizedDescription)") + } + return .descend + } +} + +private func replaceSymlink(_ path: String, target: String) throws { + let temporary = join(directoryName(path), ".simslim-relink-\(UUID().uuidString)") + guard symlink(target, temporary) == 0 else { throw SimSlimError(errnoText()) } + guard rename(temporary, path) == 0 else { + let message = errnoText() + unlink(temporary) + throw SimSlimError(message) + } +} + +/// Points every symlink in the clone that resolves into the source device (or its +/// log directory) at the same place in the clone. Relative links stay relative. +func rebaseCloneSymlinks(_ paths: CloneFilesystem) throws { + try walkTree(paths.cloneDeviceDirectory, skippingVanished: true) { path, info in + guard kind(info) == S_IFLNK else { return .descend } + let target: String + do { target = try readLink(path) } catch { + throw SimSlimError("read cloned symlink \(path): \(error.localizedDescription)") + } + let resolved = resolvedLinkTarget(path, target) + guard + let mapped = rebasePath( + resolved, sourceRoot: paths.sourceDeviceDirectory, cloneRoot: paths.cloneDeviceDirectory) + ?? rebasePath( + resolved, sourceRoot: paths.sourceLogDirectory, cloneRoot: paths.cloneLogDirectory) + else { return .descend } + let replacement = + target.utf8.first == slashByte ? mapped : relativePath(from: directoryName(path), to: mapped) + do { + try replaceSymlink(path, target: replacement) + } catch { + throw SimSlimError("rebase cloned symlink \(path): \(error.localizedDescription)") + } + return .descend + } +} + +// MARK: - Independence check + +/// Fails if anything in the clone still reaches the source: a symlink into the +/// source device or naming its UDID, or a regular file that is the very same +/// file (a hard link) as its counterpart in the source. +func verifyCloneIndependence(_ paths: CloneFilesystem) throws { + try walkTree(paths.cloneDeviceDirectory, skippingVanished: true) { path, info in + if kind(info) == S_IFLNK { + let target: String + do { target = try readLink(path) } catch { + throw SimSlimError("read cloned symlink \(path): \(error.localizedDescription)") + } + let resolved = resolvedLinkTarget(path, target) + if rebasePath( + resolved, sourceRoot: paths.sourceDeviceDirectory, cloneRoot: paths.cloneDeviceDirectory) + != nil || pathContainsComponent(resolved, paths.sourceUDID) + || pathContainsComponent(target, paths.sourceUDID) + { + throw SimSlimError( + "cloned symlink \(path) still resolves into the source simulator: \(target)") + } + return .descend + } + guard kind(info) == S_IFREG else { return .descend } + + let prefix = cleanPath(paths.cloneDeviceDirectory) + let relative = Array(cleanPath(path).utf8).dropFirst(prefix.utf8.count + 1) + let sourcePath = join(paths.sourceDeviceDirectory, String(decoding: relative, as: UTF8.self)) + var sourceInfo = stat() + if lstat(sourcePath, &sourceInfo) != 0 { + if errno == ENOENT || errno == ENOTDIR { return .descend } + throw SimSlimError("inspect source counterpart \(sourcePath): \(errnoText())") + } + if kind(sourceInfo) == S_IFREG && sourceInfo.st_dev == info.st_dev + && sourceInfo.st_ino == info.st_ino + { + throw SimSlimError("cloned file \(path) is hard-linked to the source simulator") + } + return .descend + } +} + +/// Rebuilds a raw clone's path-bearing state so it no longer points into its +/// source, then proves it. +func sanitizeClonedDevice(_ paths: CloneFilesystem) throws { + try validateCloneFilesystem(paths) + // Regenerating only these system copies keeps app bundles, app data, settings + // and app-owned caches while dropping stale absolute paths. + try resetClonedLaunchServices(dataDirectory: paths.cloneDataDirectory) + try resetClonedFrontBoard(dataDirectory: paths.cloneDataDirectory) + try resetClonedGeneratedPathState(dataDirectory: paths.cloneDataDirectory) + for directory in [ + join(join(paths.cloneDataDirectory, "Library"), "Caches"), + join(paths.cloneDataDirectory, "tmp"), + ] { + do { + try clearDirectoryContents(dataDirectory: paths.cloneDataDirectory, target: directory) + } catch { + throw SimSlimError("reset cloned transient state: \(error.localizedDescription)") + } + } + try rebaseClonePropertyLists(paths) + try rebaseCloneSymlinks(paths) + try verifyCloneIndependence(paths) +} diff --git a/swift/Sources/SimSlimKit/Device.swift b/swift/Sources/SimSlimKit/Device.swift new file mode 100644 index 0000000..2b928ac --- /dev/null +++ b/swift/Sources/SimSlimKit/Device.swift @@ -0,0 +1,47 @@ +// Copyright (c) 2026 Pavel Akhrameev (Swift port). MIT License; see LICENSE. + +import Foundation + +/// A simulator. The JSON keys are a contract with the SwiftUI app; `dataPath` +/// and `runtimeID` are deliberately not part of it. +public struct Device: Codable, Equatable, Sendable { + public var udid: String + public var name: String + public var state: String // "Booted" or "Shutdown" + public var platform: String // "iOS", "tvOS", "watchOS", or "visionOS" + public var osVersion: String + public var set: String + public var dataPath: String = "" + public var runtimeID: String = "" + + public init( + udid: String, + name: String = "", + state: String = "", + platform: String = "", + osVersion: String = "", + set: String = "", + dataPath: String = "", + runtimeID: String = "" + ) { + self.udid = udid + self.name = name + self.state = state + self.platform = platform + self.osVersion = osVersion + self.set = set + self.dataPath = dataPath + self.runtimeID = runtimeID + } + + private enum CodingKeys: String, CodingKey { + case udid, name, state, platform, osVersion, set + } + + /// Preserves the iOS default for callers that build a Device without + /// platform metadata. + public var platformName: String { platform.isEmpty ? "iOS" : platform } + + /// The platform and version shown in human-readable output. + public var runtimeName: String { platformName + " " + osVersion } +} diff --git a/swift/Sources/SimSlimKit/DirWatcher.swift b/swift/Sources/SimSlimKit/DirWatcher.swift new file mode 100644 index 0000000..201b956 --- /dev/null +++ b/swift/Sources/SimSlimKit/DirWatcher.swift @@ -0,0 +1,92 @@ +// Copyright (c) 2026 Pavel Akhrameev (Swift port). MIT License; see LICENSE. + +import Foundation + +/// One device's directory, named by its UDID, in a scanned device set. +struct DeviceDir: Equatable, Sendable { + var path: String + var set: String +} + +/// Calls `created` for each directory that appears in one of `setDirs`, until +/// `stop` returns true. A kqueue NOTE_WRITE on each set directory wakes it within +/// a millisecond of `simctl create`, and costs nothing while idle. A set +/// directory that does not exist yet (XCTestDevices before the first +/// parallel-testing run) is attached again on every pass; its devices count as +/// new from then on. A deleted device directory is forgotten, so `known` holds +/// only the devices that exist. +/// +/// `setDirs` maps a set directory to the set's name. The first listing of each +/// directory is the baseline, taken at startup: those devices are the first +/// scan's business, not reported here. +func watchDeviceDirs( + setDirs: [String: String], pollInterval: TimeInterval = 0.25, + stop: @Sendable () -> Bool, created: (DeviceDir) -> Void +) { + let kq = kqueue() + if kq < 0 { return } // the scan still catches every device, only later + defer { close(kq) } + + var fds: [String: Int32] = [:] // attached set directory -> its fd + var dirs: [UInt: String] = [:] // fd -> attached set directory + var known: [String: Set] = [:] // set directory -> its device directories + defer { for fd in fds.values { close(fd) } } + + func list(_ dir: String, report: Bool) { + guard let entries = try? FileManager.default.contentsOfDirectory(atPath: dir) else { return } + let was = known[dir] ?? [] + var now = Set() + for name in entries.sorted() { + var isDirectory: ObjCBool = false + let path = (dir as NSString).appendingPathComponent(name) + guard FileManager.default.fileExists(atPath: path, isDirectory: &isDirectory), + isDirectory.boolValue + else { continue } + now.insert(name) + if report && !was.contains(name) { + created(DeviceDir(path: path, set: setDirs[dir] ?? "")) + } + } + known[dir] = now + } + + func attach(report: Bool) { + for dir in setDirs.keys.sorted() where fds[dir] == nil { + let fd = open(dir, O_EVTONLY | O_DIRECTORY) + if fd < 0 { continue } + var change = kevent( + ident: UInt(fd), filter: Int16(EVFILT_VNODE), flags: UInt16(EV_ADD | EV_CLEAR), + fflags: UInt32(NOTE_WRITE | NOTE_DELETE | NOTE_RENAME), data: 0, udata: nil) + if kevent(kq, &change, 1, nil, 0, nil) < 0 { + close(fd) + continue + } + fds[dir] = fd + dirs[UInt(fd)] = dir + list(dir, report: report) + } + } + + attach(report: false) + var events: [kevent] = Array(repeating: kevent(), count: max(setDirs.count, 1)) + var timeout = timespec( + tv_sec: Int(pollInterval), tv_nsec: Int((pollInterval - floor(pollInterval)) * 1e9)) + while !stop() { + let n = kevent(kq, nil, 0, &events, Int32(events.count), &timeout) + if n < 0 && errno != EINTR { return } + for event in events[0.. String { + // A UDID is one path component; a "/" in it would walk out of the store root. + let component = udid.replacingOccurrences(of: "/", with: "_") + return (root as NSString).appendingPathComponent( + "com.apple.CoreSimulator.SimDevice.\(component)") + } + + func path(udid: String) -> String { + (directory(udid: udid) as NSString).appendingPathComponent("disabled.plist") + } + + /// The labels the store marks disabled; a label absent from the result is + /// enabled. A device that never booted has no store, which is the same as + /// nothing disabled. + func readDisabled(udid: String) throws -> Set { + Set(try readEntries(udid: udid).filter { $0.value }.keys) + } + + /// Every entry verbatim, including the explicit-enable (false) entries the + /// runtime writes for itself, which a merge must preserve. + func readEntries(udid: String) throws -> [String: Bool] { + let file = path(udid: udid) + guard FileManager.default.fileExists(atPath: file) else { return [:] } + let data: Data + do { + data = try Data(contentsOf: URL(fileURLWithPath: file)) + } catch { + throw SimSlimError("read launchd disable store: \(error.localizedDescription)") + } + return try DisabledStore.parse(data) + } + + /// Entries whose value is not a boolean, kept verbatim across a write. + private func readForeign(udid: String) -> [String: Any] { + let file = path(udid: udid) + guard let data = try? Data(contentsOf: URL(fileURLWithPath: file)), + let dict = try? PropertyListSerialization.propertyList(from: data, options: [], format: nil) + as? [String: Any] + else { return [:] } + return dict.filter { entry in + guard let number = entry.value as? NSNumber else { return true } + return CFGetTypeID(number) != CFBooleanGetTypeID() + } + } + + /// Merges the transitions into the store, leaving every other entry as it + /// was. The write is atomic so launchd_sim never reads a half-written store. + func write(udid: String, toDisable: [String], toEnable: [String]) throws { + var entries = try readEntries(udid: udid) + let foreign = readForeign(udid: udid) + for label in toDisable { entries[label] = true } + for label in toEnable { entries[label] = false } + + let dir = directory(udid: udid) + do { + try FileManager.default.createDirectory( + atPath: dir, withIntermediateDirectories: true, attributes: [.posixPermissions: 0o700]) + } catch { + throw SimSlimError("create launchd disable store: \(error.localizedDescription)") + } + let temp = (dir as NSString).appendingPathComponent("disabled.plist.\(UUID().uuidString)") + defer { try? FileManager.default.removeItem(atPath: temp) } + do { + let data: Data + if foreign.isEmpty { + data = DisabledStore.encode(entries) + } else { + // Entries of another type are not ours to drop; let the plist writer + // serialize the mixed dictionary. + var merged: [String: Any] = foreign + for (label, value) in entries { merged[label] = value } + data = try PropertyListSerialization.data( + fromPropertyList: merged, format: .xml, options: 0) + } + try data.write(to: URL(fileURLWithPath: temp)) + try FileManager.default.setAttributes([.posixPermissions: 0o644], ofItemAtPath: temp) + } catch { + throw SimSlimError("write launchd disable store: \(error.localizedDescription)") + } + // rename(2) replaces the destination atomically; FileManager.replaceItem and + // moveItem would refuse or copy. + guard rename(temp, path(udid: udid)) == 0 else { + throw SimSlimError("write launchd disable store: \(String(cString: strerror(errno)))") + } + } + + /// The same XML plist shape launchd_sim writes, sorted so a rewrite that + /// changes nothing produces an identical file. + static func encode(_ entries: [String: Bool]) -> Data { + var text = "\n" + text += + "\n" + text += "\n\n" + for label in entries.keys.sorted() { + text += "\t\(escape(label))\n\t<\(entries[label]! ? "true" : "false")/>\n" + } + text += "\n\n" + return Data(text.utf8) + } + + private static func escape(_ text: String) -> String { + var out = "" + for ch in text.unicodeScalars { + switch ch { + case "&": out += "&" + case "<": out += "<" + case ">": out += ">" + case "\"": out += """ + case "'": out += "'" + default: out.unicodeScalars.append(ch) + } + } + return out + } + + /// Reads the flat `label|` dict. Values of any other + /// type are ignored rather than rejected, so an unexpected one cannot make the + /// store unreadable. + static func parse(_ data: Data) throws -> [String: Bool] { + // A zero-byte file (a launchd_sim that died mid-write) is an empty store. + if data.isEmpty { return [:] } + let object: Any + var format = PropertyListSerialization.PropertyListFormat.xml + do { + object = try PropertyListSerialization.propertyList( + from: data, options: [], format: &format) + } catch { + throw SimSlimError("parse launchd disable store: \(error.localizedDescription)") + } + // Foundation also accepts old-style text such as `garbage` as a string plist; + // only an XML or binary dictionary is a store. + guard format != .openStep, let dict = object as? [String: Any] else { + throw SimSlimError( + "parse launchd disable store: not an XML or binary property list dictionary") + } + var entries: [String: Bool] = [:] + for (label, value) in dict where !label.isEmpty { + // Only real booleans: an integer 1 is not a disable override. + if let number = value as? NSNumber, CFGetTypeID(number) == CFBooleanGetTypeID() { + entries[label] = number.boolValue + } + } + return entries + } +} diff --git a/swift/Sources/SimSlimKit/DiskCleanup.swift b/swift/Sources/SimSlimKit/DiskCleanup.swift new file mode 100644 index 0000000..423d6f7 --- /dev/null +++ b/swift/Sources/SimSlimKit/DiskCleanup.swift @@ -0,0 +1,720 @@ +// Copyright (c) 2026 Pavel Akhrameev (Swift port). MIT License; see LICENSE. + +import Foundation + +// Disk measurement and the permanent disk cleanup. Deletion is tightly confined: +// only allowlisted, name-matched directories inside a simulator's own data +// directory are ever emptied, symlinks are never followed, and the shared signed +// runtime (built-in apps, core OS resources) is out of reach by construction. + +/// One tightly allowlisted class of per-device data. Runtime files are +/// deliberately outside this model: an iOS runtime is shared by many simulators +/// and must only be managed by Xcode/simctl. +public struct DiskCleanupCategory: Codable, Equatable, Sendable { + public let id: String + public let name: String + public let description: String + public let downside: String + public let recovery: String + public let risk: String + public let defaultSelected: Bool + public let canClean: Bool +} + +public let diskCleanupCategories: [DiskCleanupCategory] = [ + DiskCleanupCategory( + id: "caches", name: "System & App Caches", + description: "Generated cache files belonging to iOS and installed apps.", + downside: "Next launches may be slower; downloaded or offline cache content can disappear.", + recovery: "Old cache contents stay deleted; apps build new caches as needed.", + risk: "Lower risk", defaultSelected: true, canClean: true), + DiskCleanupCategory( + id: "logs", name: "Logs & Diagnostics", + description: "Unified logs, signposts, symbol text, crash logs, and app log folders.", + downside: "Existing diagnostic and crash history is deleted.", + recovery: "Old history stays deleted; future runs create new logs.", + risk: "Lower risk", defaultSelected: true, canClean: true), + DiskCleanupCategory( + id: "temporary", name: "Temporary Files", + description: "Files in simulator and app temporary directories.", + downside: "Apps that misuse temporary storage may lose in-progress work.", + recovery: "Old contents stay deleted; apps create new temporary files as needed.", + risk: "Lower risk", defaultSelected: true, canClean: true), + DiskCleanupCategory( + id: "linguistic-data", name: "Downloaded Language Data", + description: "On-demand language models used by Siri, Search, and text analysis.", + downside: "Language-aware features may be limited until iOS downloads the package again.", + recovery: "iOS downloads the language package again when a feature needs it.", + risk: "Restored on demand", defaultSelected: false, canClean: true), + DiskCleanupCategory( + id: "required-siri-assets", name: "Required Siri Assets", + description: "Siri understanding, speech, voice, and accessibility downloads restored by iOS.", + downside: "Manual deletion is unsupported, and iOS promptly downloads required assets again.", + recovery: "Required assets return automatically after boot.", + risk: "System managed", defaultSelected: false, canClean: false), +] + +/// A read-only breakdown of durable per-simulator storage. These rows are +/// deliberately separate from cleanup categories so documents, app bundles, and +/// user data can never become selected for deletion. +public struct DiskStorageMeasurement: Codable, Equatable, Sendable { + public let id: String + public let name: String + public let description: String + public var bytes: Int64 +} + +let diskStorageCategories: [DiskStorageMeasurement] = [ + DiskStorageMeasurement( + id: "installed-apps", name: "Installed Apps", + description: + "Developer-installed app and test-runner bundles. Built-in apps live in the shared runtime.", + bytes: 0), + DiskStorageMeasurement( + id: "documents", name: "Documents", + description: "Files in app and app-group Documents directories.", bytes: 0), + DiskStorageMeasurement( + id: "app-data", name: "App Data", + description: + "Preferences, databases, and support files outside Documents and cleanup categories.", + bytes: 0), + DiskStorageMeasurement( + id: "user-media", name: "User Media", + description: + "Photos, videos, downloads, and other files in the simulator media library.", bytes: 0), +] + +/// A category plus what it currently holds. The category's fields are flattened +/// into the same JSON object, as in the Go output. +public struct DiskCleanupCategoryMeasurement: Codable, Equatable, Sendable { + public var category: DiskCleanupCategory + public var bytes: Int64 + public var targets: Int + + private enum ExtraKeys: String, CodingKey { case bytes, targets } + + public func encode(to encoder: Encoder) throws { + try category.encode(to: encoder) + var c = encoder.container(keyedBy: ExtraKeys.self) + try c.encode(bytes, forKey: .bytes) + try c.encode(targets, forKey: .targets) + } + + public init(category: DiskCleanupCategory, bytes: Int64, targets: Int) { + self.category = category + self.bytes = bytes + self.targets = targets + } + + public init(from decoder: Decoder) throws { + category = try DiskCleanupCategory(from: decoder) + let c = try decoder.container(keyedBy: ExtraKeys.self) + bytes = try c.decode(Int64.self, forKey: .bytes) + targets = try c.decode(Int.self, forKey: .targets) + } +} + +public struct DiskCleanupPlan: Codable, Equatable, Sendable { + public var udid: String + public var totalBytes: Int64 = 0 + public var cleanableBytes: Int64 = 0 + public var categories: [DiskCleanupCategoryMeasurement] = [] + public var storage: [DiskStorageMeasurement] = [] +} + +public struct DiskCleanupResult: Codable, Equatable, Sendable { + public var udid: String + public var categoryIds: [String] + public var beforeBytes: Int64 + public var afterBytes: Int64 + public var reclaimedBytes: Int64 + public var wasBooted: Bool = false + public var bootStateRestored: Bool = false +} + +/// The `size` command's result. +public struct DiskMeasurement: Codable, Equatable, Sendable { + public var bytes: Int64 + public init(bytes: Int64) { self.bytes = bytes } +} + +func diskCleanupCategory(id: String) -> DiskCleanupCategory? { + diskCleanupCategories.first { $0.id == id } +} + +/// Checks and normalises a selection: blanks and repeats dropped, unknown or +/// measure-only categories refused, at least one required, sorted. +public func validateDiskCleanupSelection(_ ids: [String]) throws -> [String] { + var seen = Set() + var validated: [String] = [] + for raw in ids { + let id = goTrimSpace(raw) + if id.isEmpty || seen.contains(id) { continue } + guard let category = diskCleanupCategory(id: id) else { + throw SimSlimError("unknown disk cleanup category \(goQuote(id))") + } + if !category.canClean { + throw SimSlimError( + "disk cleanup category \(goQuote(id)) is measured only and cannot be cleaned") + } + seen.insert(id) + validated.append(id) + } + if validated.isEmpty { throw SimSlimError("select at least one cleanable disk category") } + return validated.sorted() +} + +// MARK: - Paths + +/// Lexical path cleaning, like Go's `filepath.Clean`. It works on bytes: Swift's +/// Character view would merge a name that starts with a combining mark with the +/// slash before it. +func cleanPath(_ path: String) -> String { + let bytes = Array(path.utf8) + if bytes.isEmpty { return "." } + let slash = UInt8(ascii: "/") + let dot = UInt8(ascii: ".") + let rooted = bytes[0] == slash + var parts: [[UInt8]] = [] + for part in bytes.split(separator: slash, omittingEmptySubsequences: true) { + if part.elementsEqual([dot]) { continue } + if part.elementsEqual([dot, dot]) { + if let last = parts.last, !last.elementsEqual([dot, dot]) { + parts.removeLast() + } else if !rooted { + parts.append(Array(part)) + } + continue + } + parts.append(Array(part)) + } + var out: [UInt8] = rooted ? [slash] : [] + for (index, part) in parts.enumerated() { + if index > 0 { out.append(slash) } + out.append(contentsOf: part) + } + if out.isEmpty { return "." } + return String(decoding: out, as: UTF8.self) +} + +/// Whether `target` is strictly inside `root` (neither equal to it nor outside), +/// judged on the cleaned paths alone, byte by byte. +func isStrictDescendant(_ root: String, _ target: String) -> Bool { + let root = Array(cleanPath(root).utf8) + let target = Array(cleanPath(target).utf8) + if root == target { return false } + let slash = UInt8(ascii: "/") + let prefix = root == [slash] ? root : root + [slash] + return target.count > prefix.count && target.starts(with: prefix) +} + +func requireDescendant(_ root: String, _ target: String) throws { + guard isStrictDescendant(root, target) else { + throw SimSlimError("refusing cleanup path outside simulator data: \(cleanPath(target))") + } +} + +/// The real path with every symlink resolved, like Go's `filepath.EvalSymlinks`. +func resolvedPath(_ path: String) throws -> String { + guard let resolved = realpath(path, nil) else { + throw SimSlimError(String(cString: strerror(errno))) + } + defer { free(resolved) } + return String(cString: resolved) +} + +/// Rejects a target unless its real path is exactly where its own path says it +/// is, below the real root: no symlink may sit anywhere on the way down. Checking +/// only that the real path stays inside the root would let a symlink within the +/// data directory (say `var -> Media`) redirect a fixed cleanup path such as +/// `var/log` into protected user data. +func requireResolvedDescendant(_ root: String, _ target: String) throws { + let resolvedRoot: String + do { + resolvedRoot = try resolvedPath(root) + } catch { + throw SimSlimError("resolve cleanup root: \(error.localizedDescription)") + } + let resolvedTarget: String + do { + resolvedTarget = try resolvedPath(target) + } catch { + throw SimSlimError("resolve cleanup target: \(error.localizedDescription)") + } + guard isStrictDescendant(resolvedRoot, resolvedTarget) else { + throw SimSlimError( + "refusing symlinked cleanup path \(target): refusing cleanup path outside simulator data: \(cleanPath(resolvedTarget))" + ) + } + // Where the path says the target is: the real root plus the relative part. + let lexicalRoot = Array(cleanPath(root).utf8) + let lexicalTarget = Array(cleanPath(target).utf8) + let relative = lexicalTarget.dropFirst( + lexicalRoot == [UInt8(ascii: "/")] ? 1 : lexicalRoot.count + 1) + let expected = join(resolvedRoot, String(decoding: relative, as: UTF8.self)) + guard Array(cleanPath(resolvedTarget).utf8) == Array(cleanPath(expected).utf8) else { + throw SimSlimError( + "refusing symlinked cleanup path \(target): it resolves to \(cleanPath(resolvedTarget)), not inside the data directory at \(cleanPath(expected))" + ) + } +} + +func join(_ directory: String, _ name: String) -> String { + directory.hasSuffix("/") ? directory + name : directory + "/" + name +} + +private func join(_ root: String, _ names: String...) -> String { + names.reduce(root) { join($0, $1) } +} + +// MARK: - Walking + +enum WalkStep { case descend, skip } + +func lstatInfo(_ path: String) throws -> stat { + var info = stat() + guard lstat(path, &info) == 0 else { + throw SimSlimError("lstat \(path): \(String(cString: strerror(errno)))") + } + return info +} + +func isDirectory(_ info: stat) -> Bool { (info.st_mode & S_IFMT) == S_IFDIR } + +/// One directory entry as `readdir` reports it. `isDirectory` is the entry's own +/// type (a symlink to a directory is not one), or nil when the filesystem did not +/// say. +struct DirectoryEntry { + var name: String + var isDirectory: Bool? +} + +/// Lists a directory with `readdir`, sorted by name like Go's `os.ReadDir`. +/// Foundation's `contentsOfDirectory` silently omits AppleDouble `._*` files, +/// which a cleanup must not leave behind or leave unmeasured. +func readDirectory(_ path: String) throws -> [DirectoryEntry] { + guard let dir = opendir(path) else { + throw SimSlimError("read \(path): \(String(cString: strerror(errno)))") + } + defer { closedir(dir) } + var entries: [DirectoryEntry] = [] + while let entry = readdir(dir) { + let name = withUnsafePointer(to: &entry.pointee.d_name) { + $0.withMemoryRebound(to: CChar.self, capacity: Int(MAXNAMLEN) + 1) { String(cString: $0) } + } + if name == "." || name == ".." { continue } + let type: Bool? = + entry.pointee.d_type == UInt8(DT_UNKNOWN) ? nil : entry.pointee.d_type == UInt8(DT_DIR) + entries.append(DirectoryEntry(name: name, isDirectory: type)) + } + return entries.sorted { Array($0.name.utf8).lexicographicallyPrecedes(Array($1.name.utf8)) } +} + +/// Visits `root` and everything below it in lexical order, never following a +/// symlink (a symlink is an entry, not a directory). Every entry is `lstat`ed, so a +/// file that vanishes mid-walk is an error, as in Go's `filepath.WalkDir` + +/// `entry.Info()`. Used where sizes are summed. +func walkTree( + _ root: String, skippingVanished: Bool = false, _ visit: (String, stat) throws -> WalkStep +) throws { + func walk(_ path: String, _ info: stat) throws { + let step = try visit(path, info) + guard isDirectory(info), step == .descend else { return } + for entry in try readDirectory(path) { + let child = join(path, entry.name) + var childInfo = stat() + if lstat(child, &childInfo) != 0 { + // A running device's daemons delete files as they stop. + if skippingVanished && errno == ENOENT { continue } + throw SimSlimError("lstat \(child): \(String(cString: strerror(errno)))") + } + try walk(child, childInfo) + } + } + try walk(root, try lstatInfo(root)) +} + +/// Test seam: walks like discovery does and calls `visit` for each directory. +func walkDirectoriesForTest(_ root: String, _ visit: (String) throws -> Bool) throws { + try walkDirectories(root) { try visit($0) ? .descend : .skip } +} + +/// Visits the directories below `root` using only the type `readdir` reports, so +/// the churn of a running simulator (a file created and deleted between listing +/// and looking) cannot fail discovery. A subdirectory that vanishes is skipped. +private func walkDirectories(_ root: String, _ visit: (String) throws -> WalkStep) throws { + func walk(_ path: String) throws { + let entries: [DirectoryEntry] + do { + entries = try readDirectory(path) + } catch { + var info = stat() + if lstat(path, &info) != 0 && errno == ENOENT { return } + throw error + } + for entry in entries { + let child = join(path, entry.name) + var isDir = entry.isDirectory + if isDir == nil { // the filesystem did not say + var info = stat() + guard lstat(child, &info) == 0 else { continue } + isDir = (info.st_mode & S_IFMT) == S_IFDIR + } + guard isDir == true else { continue } + if try visit(child) == .descend { try walk(child) } + } + } + try walk(root) +} + +/// Allocated bytes (filesystem blocks, like `du`) of everything under `root`, +/// including `root` itself. +func allocatedSize(_ root: String) throws -> Int64 { + var total: Int64 = 0 + try walkTree(root) { _, info in + total += Int64(info.st_blocks) * 512 + return .descend + } + return total +} + +func allocatedSizeExcludingNames(_ root: String, excluded: Set) throws -> Int64 { + var total: Int64 = 0 + try walkTree(root) { path, info in + if path != root, isDirectory(info), excluded.contains((path as NSString).lastPathComponent) { + return .skip + } + total += Int64(info.st_blocks) * 512 + return .descend + } + return total +} + +/// Durable user content and system-managed assets stay out of name-based +/// discovery. An app may legitimately create a folder named Caches, Logs, or tmp +/// below Documents; its name alone does not make that content disposable. +func isProtectedCleanupSubtree(_ name: String) -> Bool { + ["Documents", "Mobile Documents", "Media", "MobileAsset"].contains(name) +} + +func findNamedDirectories(root: String, name: String, excludedAncestors: Set) throws + -> [String] +{ + var targets: [String] = [] + let bundleDirectory = join(root, "Containers", "Bundle") + try walkDirectories(root) { path in + let entryName = (path as NSString).lastPathComponent + // Packaged resources are durable even when named Caches, Logs, or tmp. + if path == bundleDirectory { return .skip } + if isProtectedCleanupSubtree(entryName) { return .skip } + if excludedAncestors.contains(entryName) { return .skip } + if entryName == name { + targets.append(path) + return .skip + } + return .descend + } + return targets +} + +/// The existing real directories among `candidates`, each confined to `root`, +/// with any that sit inside another dropped so nothing is counted or cleared twice. +func compactExistingTargets(_ root: String, _ candidates: [String]) throws -> [String] { + var unique = Set() + var targets: [String] = [] + for raw in candidates { + let candidate = cleanPath(raw) + try requireDescendant(root, candidate) + var info = stat() + if lstat(candidate, &info) != 0 { + if errno == ENOENT { continue } + throw SimSlimError("lstat \(candidate): \(String(cString: strerror(errno)))") + } + // A symlink, or anything that is not a directory, is never a target. + if !isDirectory(info) || unique.contains(candidate) { continue } + try requireResolvedDescendant(root, candidate) + unique.insert(candidate) + targets.append(candidate) + } + targets.sort { a, b in a.count != b.count ? a.count < b.count : a < b } + var compacted: [String] = [] + for target in targets where !compacted.contains(where: { isStrictDescendant($0, target) }) { + compacted.append(target) + } + return compacted +} + +func linguisticDataTargets(_ dataDirectory: String) throws -> [String] { + let target = join( + dataDirectory, "private", "var", "MobileAsset", "AssetsV2", + "com_apple_MobileAsset_LinguisticData") + return try compactExistingTargets(dataDirectory, [target]) +} + +func requiredSiriAssetTargets(_ dataDirectory: String) throws -> [String] { + let assetsRoot = join(dataDirectory, "private", "var", "MobileAsset", "AssetsV2") + let names: [String] + do { + names = try readDirectory(assetsRoot).map(\.name) + } catch { + var info = stat() + if lstat(assetsRoot, &info) != 0 && errno == ENOENT { return [] } + throw error + } + let prefixes = [ + "com_apple_MobileAsset_UAF_Siri_", "com_apple_MobileAsset_TTS", + "com_apple_MobileAsset_VoiceServices_", "com_apple_MobileAsset_VoiceTrigger", + ] + var targets: [String] = [] + for name in names { + let path = join(assetsRoot, name) + guard let info = try? lstatInfo(path), isDirectory(info) else { continue } + if prefixes.contains(where: { name.hasPrefix($0) }) { targets.append(path) } + } + return targets +} + +func diskCleanupTargets(dataDirectory: String, categoryID: String) throws -> [String] { + var targets: [String] + switch categoryID { + case "caches": + targets = try findNamedDirectories(root: dataDirectory, name: "Caches", excludedAncestors: []) + case "temporary": + targets = try findNamedDirectories( + root: dataDirectory, name: "tmp", excludedAncestors: ["Caches"]) + case "logs": + targets = [ + join(dataDirectory, "Library", "Logs"), + join(dataDirectory, "var", "log"), + join(dataDirectory, "var", "db", "diagnostics"), + join(dataDirectory, "var", "db", "uuidtext"), + ] + targets += try findNamedDirectories( + root: dataDirectory, name: "Logs", excludedAncestors: ["Caches", "tmp"]) + case "linguistic-data": + targets = try linguisticDataTargets(dataDirectory) + case "required-siri-assets": + targets = try requiredSiriAssetTargets(dataDirectory) + default: + throw SimSlimError("unknown disk cleanup category \(goQuote(categoryID))") + } + return try compactExistingTargets(dataDirectory, targets) +} + +// MARK: - Storage breakdown (read only) + +func allocatedSizeOfExistingDirectories(_ root: String, _ candidates: [String]) throws -> Int64 { + try compactExistingTargets(root, candidates).reduce(0) { try $0 + allocatedSize($1) } +} + +private func containerRoots(_ dataDirectory: String) -> [String] { + [ + join(dataDirectory, "Containers", "Data", "Application"), + join(dataDirectory, "Containers", "Shared", "AppGroup"), + ] +} + +func appDocumentTargets(_ dataDirectory: String) throws -> [String] { + var candidates: [String] = [] + for root in containerRoots(dataDirectory) { + let names: [String] + do { + names = try readDirectory(root).map(\.name) + } catch { + var info = stat() + if lstat(root, &info) != 0 && errno == ENOENT { continue } + throw error + } + for name in names { + let path = join(root, name) + if let info = try? lstatInfo(path), isDirectory(info) { + candidates.append(join(path, "Documents")) + } + } + } + return try compactExistingTargets(dataDirectory, candidates) +} + +func appDataSize(_ dataDirectory: String) throws -> Int64 { + let excluded: Set = ["Caches", "Documents", "Logs", "tmp"] + var total: Int64 = 0 + for root in containerRoots(dataDirectory) { + var info = stat() + if lstat(root, &info) != 0 { + if errno == ENOENT { continue } + throw SimSlimError("lstat \(root): \(String(cString: strerror(errno)))") + } + if !isDirectory(info) { continue } // a symlink or file is skipped, never followed + try requireResolvedDescendant(dataDirectory, root) + total += try allocatedSizeExcludingNames(root, excluded: excluded) + } + return total +} + +func diskStorageMeasurements(_ dataDirectory: String) throws -> [DiskStorageMeasurement] { + try diskStorageCategories.map { category in + var measurement = category + do { + switch category.id { + case "installed-apps": + measurement.bytes = try allocatedSizeOfExistingDirectories( + dataDirectory, [join(dataDirectory, "Containers", "Bundle", "Application")]) + case "documents": + measurement.bytes = try allocatedSizeOfExistingDirectories( + dataDirectory, try appDocumentTargets(dataDirectory)) + case "app-data": + measurement.bytes = try appDataSize(dataDirectory) + case "user-media": + measurement.bytes = try allocatedSizeOfExistingDirectories( + dataDirectory, [join(dataDirectory, "Media")]) + default: + throw SimSlimError("unknown disk storage category \(goQuote(category.id))") + } + } catch { + throw SimSlimError("measure \(category.name): \(error.localizedDescription)") + } + return measurement + } +} + +// MARK: - Plan and clean + +func diskCleanupPlan(udid: String, dataDirectory: String) throws -> DiskCleanupPlan { + var plan = DiskCleanupPlan(udid: udid) + for category in diskCleanupCategories { + let targets: [String] + do { + targets = try diskCleanupTargets(dataDirectory: dataDirectory, categoryID: category.id) + } catch { + throw SimSlimError("scan \(category.name): \(error.localizedDescription)") + } + var measurement = DiskCleanupCategoryMeasurement( + category: category, bytes: 0, targets: targets.count) + for target in targets { + do { + measurement.bytes += try allocatedSize(target) + } catch { + throw SimSlimError("measure \(target): \(error.localizedDescription)") + } + } + plan.totalBytes += measurement.bytes + if category.canClean { plan.cleanableBytes += measurement.bytes } + plan.categories.append(measurement) + } + plan.storage = try diskStorageMeasurements(dataDirectory) + return plan +} + +private func selectedCleanupBytes(_ plan: DiskCleanupPlan, _ ids: [String]) -> Int64 { + plan.categories.filter { ids.contains($0.category.id) }.reduce(0) { $0 + $1.bytes } +} + +/// Empties one allowlisted directory: every immediate child is removed, the +/// directory itself stays. The target must be a real directory (never a symlink) +/// that resolves inside the data directory, and so must every child path. +func clearDirectoryContents(dataDirectory: String, target: String) throws { + try requireDescendant(dataDirectory, target) + var info = stat() + if lstat(target, &info) != 0 { + if errno == ENOENT { return } + throw SimSlimError("lstat \(target): \(String(cString: strerror(errno)))") + } + if !isDirectory(info) { + throw SimSlimError("refusing to clear non-directory target \(target)") + } + try requireResolvedDescendant(dataDirectory, target) + let names = try readDirectory(target).map(\.name) + for name in names { + let child = join(target, name) + try requireDescendant(dataDirectory, child) + try removeIfPresent(child) + } +} + +/// Removes one entry. A symlink is unlinked, never followed, and a mount point +/// is not crossed. An entry that is already gone (a running simulator cleaning up +/// after itself) is the state we wanted, so it is not an error. +func removeIfPresent(_ path: String) throws { + do { + try FileManager.default.removeItem(atPath: path) + } catch { + var info = stat() + if lstat(path, &info) != 0 && errno == ENOENT { return } + throw SimSlimError("remove \(path): \(error.localizedDescription)") + } +} + +func cleanDisk(udid: String, dataDirectory: String, categoryIDs requested: [String]) throws + -> DiskCleanupResult +{ + let categoryIDs = try validateDiskCleanupSelection(requested) + let beforePlan = try diskCleanupPlan(udid: udid, dataDirectory: dataDirectory) + let beforeBytes = selectedCleanupBytes(beforePlan, categoryIDs) + + for id in categoryIDs { + for target in try diskCleanupTargets(dataDirectory: dataDirectory, categoryID: id) { + do { + try clearDirectoryContents(dataDirectory: dataDirectory, target: target) + } catch { + throw SimSlimError("clean \(target): \(error.localizedDescription)") + } + } + } + + let afterPlan = try diskCleanupPlan(udid: udid, dataDirectory: dataDirectory) + let afterBytes = selectedCleanupBytes(afterPlan, categoryIDs) + return DiskCleanupResult( + udid: udid, categoryIds: categoryIDs, beforeBytes: beforeBytes, afterBytes: afterBytes, + reclaimedBytes: max(0, beforeBytes - afterBytes)) +} + +extension Simctl { + /// Measures what could be cleaned and the durable storage that never will be. + /// The UDID is resolved through simctl first, so an alias such as `all` can + /// never become a filesystem path. + public func planDiskCleanup(udid: String) throws -> DiskCleanupPlan { + let (_, dataDirectory) = try simulatorDataDirectory(udid: udid) + return try diskCleanupPlan(udid: udid, dataDirectory: dataDirectory) + } + + /// Permanently deletes the contents of the selected categories' directories. A + /// booted simulator is shut down first, because its processes are using those + /// files; with `preserveBootState` it is booted again afterwards. + public func cleanDeviceDisk( + udid: String, categoryIDs: [String], preserveBootState: Bool + ) throws -> DiskCleanupResult { + let (device, dataDirectory) = try simulatorDataDirectory(udid: udid) + let categories = try validateDiskCleanupSelection(categoryIDs) + + let wasBooted = device.state == "Booted" + // Shuts a booted simulator down, and refuses one that is Booting or Shutting + // Down: its processes are using these files. (Go deletes under it.) + _ = try shutdownIfBooted(udid: udid) + + var result = DiskCleanupResult( + udid: udid, categoryIds: categories, beforeBytes: 0, afterBytes: 0, reclaimedBytes: 0) + var cleanupError: Error? + do { + result = try cleanDisk(udid: udid, dataDirectory: dataDirectory, categoryIDs: categories) + } catch { + cleanupError = error + } + result.wasBooted = wasBooted + if wasBooted && preserveBootState { + do { + try bootAndWait(set: device.set, udid: udid) + } catch { + if let cleanupError { + throw SimSlimError( + "\(cleanupError.localizedDescription); additionally could not restore boot state: \(error.localizedDescription)" + ) + } + throw SimSlimError( + "disk cleanup finished, but could not restore boot state: \(error.localizedDescription)") + } + result.bootStateRestored = true + } + if let cleanupError { throw cleanupError } + return result + } +} diff --git a/swift/Sources/SimSlimKit/Errors.swift b/swift/Sources/SimSlimKit/Errors.swift new file mode 100644 index 0000000..385e504 --- /dev/null +++ b/swift/Sources/SimSlimKit/Errors.swift @@ -0,0 +1,13 @@ +// Copyright (c) 2026 Pavel Akhrameev (Swift port). MIT License; see LICENSE. + +import Foundation + +/// An error whose message is meant to be shown to the user as-is. +public struct SimSlimError: Error, LocalizedError, CustomStringConvertible, Equatable { + public let message: String + + public init(_ message: String) { self.message = message } + + public var description: String { message } + public var errorDescription: String? { message } +} diff --git a/swift/Sources/SimSlimKit/Features.swift b/swift/Sources/SimSlimKit/Features.swift new file mode 100644 index 0000000..25122f7 --- /dev/null +++ b/swift/Sources/SimSlimKit/Features.swift @@ -0,0 +1,116 @@ +// Copyright (c) 2026 Pavel Akhrameev (Swift port). MIT License; see LICENSE. + +import Foundation + +/// A user-facing capability backed by specific launchd daemons. Every label +/// must also be managed by a Category (enforced in the tests), including +/// required services that earlier versions could have turned off. +public struct Feature: Codable, Equatable, Sendable { + public let id: String + public let name: String + public let labels: [String] + + public init(id: String, name: String, labels: [String]) { + self.id = id + self.name = name + self.labels = labels + } +} + +/// One feature's verdict: the daemons it needs that are down. +public struct FeatureStatus: Codable, Equatable, Sendable { + public let id: String + public let name: String + public let ok: Bool + public let disabled: [String] + + public init(id: String, name: String, ok: Bool, disabled: [String]) { + self.id = id + self.name = name + self.ok = ok + self.disabled = disabled + } + + private enum CodingKeys: String, CodingKey { case id, name, ok, disabled } + + public func encode(to encoder: Encoder) throws { + var c = encoder.container(keyedBy: CodingKeys.self) + try c.encode(id, forKey: .id) + try c.encode(name, forKey: .name) + try c.encode(ok, forKey: .ok) + if !disabled.isEmpty { try c.encode(disabled, forKey: .disabled) } // Go omitempty + } + + public init(from decoder: Decoder) throws { + let c = try decoder.container(keyedBy: CodingKeys.self) + id = try c.decode(String.self, forKey: .id) + name = try c.decode(String.self, forKey: .name) + ok = try c.decode(Bool.self, forKey: .ok) + disabled = try c.decodeIfPresent([String].self, forKey: .disabled) ?? [] + } +} + +/// Whether each required feature survives the device's current slimming. `ok` +/// is false when any required feature has a disabled daemon. +public struct DoctorOutput: Codable, Equatable, Sendable { + public var udid: String + public var ok: Bool + public var features: [FeatureStatus] + + public init(udid: String = "", ok: Bool, features: [FeatureStatus]) { + self.udid = udid + self.ok = ok + self.features = features + } + + private enum CodingKeys: String, CodingKey { case udid, ok, features } + + public func encode(to encoder: Encoder) throws { + var c = encoder.container(keyedBy: CodingKeys.self) + if !udid.isEmpty { try c.encode(udid, forKey: .udid) } // Go omitempty + try c.encode(ok, forKey: .ok) + try c.encode(features, forKey: .features) + } + + public init(from decoder: Decoder) throws { + let c = try decoder.container(keyedBy: CodingKeys.self) + udid = try c.decodeIfPresent(String.self, forKey: .udid) ?? "" + ok = try c.decode(Bool.self, forKey: .ok) + features = try c.decode([FeatureStatus].self, forKey: .features) + } +} + +extension Catalog { + /// Commonly required capabilities mapped to the daemons they need running. + public static let features: [Feature] = featureList + + public static func feature(id: String) -> Feature? { + features.first { $0.id == id } + } + + /// Maps requested IDs to their Features, failing on the first unknown one so + /// a typo in `--requires` fails loudly instead of passing silently. + public static func resolveFeatures(_ ids: [String]) throws -> [Feature] { + try ids.map { id in + guard let feature = feature(id: id) else { + throw SimSlimError("unknown feature \"\(id)\" (see `simslim doctor --list`)") + } + return feature + } + } + + /// Reports, for each feature, which of its daemons the device currently has + /// disabled. A feature is OK only when none of them are. + public static func diagnoseFeatures(_ features: [Feature], disabled: Set) -> DoctorOutput + { + var allOK = true + var statuses: [FeatureStatus] = [] + for feature in features { + let down = feature.labels.filter { disabled.contains($0) } + let ok = down.isEmpty + allOK = allOK && ok + statuses.append(FeatureStatus(id: feature.id, name: feature.name, ok: ok, disabled: down)) + } + return DoctorOutput(ok: allOK, features: statuses) + } +} diff --git a/swift/Sources/SimSlimKit/Fleet.swift b/swift/Sources/SimSlimKit/Fleet.swift new file mode 100644 index 0000000..2645f48 --- /dev/null +++ b/swift/Sources/SimSlimKit/Fleet.swift @@ -0,0 +1,227 @@ +// Copyright (c) 2026 Pavel Akhrameev (Swift port). MIT License; see LICENSE. + +import Foundation + +/// One process in a simulator's launchd tree, for the `top` drill-down. (Named +/// apart from Foundation's `Process`; the JSON keys are the contract.) +public struct ProcessUsage: Codable, Equatable, Sendable { + public var pid: Int + public var command: String + public var bytes: Int64 + public var cpu: Double + + public init(pid: Int, command: String, bytes: Int64, cpu: Double) { + self.pid = pid + self.command = command + self.bytes = bytes + self.cpu = cpu + } +} + +/// One booted simulator's live resource snapshot for `simslim top`. +public struct TopSim: Codable, Equatable, Sendable { + public var device: Device + public var managedDisabled: Int? + public var managedTotal: Int + public var statusError: String + public var memory: MemoryMeasurement? + public var memoryError: String + public var diskBytes: Int64? + + public init( + device: Device, managedDisabled: Int? = nil, managedTotal: Int = 0, statusError: String = "", + memory: MemoryMeasurement? = nil, memoryError: String = "", diskBytes: Int64? = nil + ) { + self.device = device + self.managedDisabled = managedDisabled + self.managedTotal = managedTotal + self.statusError = statusError + self.memory = memory + self.memoryError = memoryError + self.diskBytes = diskBytes + } + + private enum ExtraKeys: String, CodingKey { + case managedDisabled, managedTotal, statusError, memory, memoryError, diskBytes + } + + public func encode(to encoder: Encoder) throws { + try device.encode(to: encoder) // flatten the device's keys into this object + var c = encoder.container(keyedBy: ExtraKeys.self) + try c.encodeIfPresent(managedDisabled, forKey: .managedDisabled) + try c.encode(managedTotal, forKey: .managedTotal) + if !statusError.isEmpty { try c.encode(statusError, forKey: .statusError) } // Go omitempty + try c.encodeIfPresent(memory, forKey: .memory) + if !memoryError.isEmpty { try c.encode(memoryError, forKey: .memoryError) } + try c.encodeIfPresent(diskBytes, forKey: .diskBytes) + } + + public init(from decoder: Decoder) throws { + device = try Device(from: decoder) + let c = try decoder.container(keyedBy: ExtraKeys.self) + managedDisabled = try c.decodeIfPresent(Int.self, forKey: .managedDisabled) + managedTotal = try c.decode(Int.self, forKey: .managedTotal) + statusError = try c.decodeIfPresent(String.self, forKey: .statusError) ?? "" + memory = try c.decodeIfPresent(MemoryMeasurement.self, forKey: .memory) + memoryError = try c.decodeIfPresent(String.self, forKey: .memoryError) ?? "" + diskBytes = try c.decodeIfPresent(Int64.self, forKey: .diskBytes) + } +} + +/// The fleet view: every booted simulator plus the summed footprint that decides +/// how many more fit. +public struct TopOutput: Codable, Equatable, Sendable { + public var sims: [TopSim] + public var totalBytes: Int64 + + public init(sims: [TopSim] = [], totalBytes: Int64 = 0) { + self.sims = sims + self.totalBytes = totalBytes + } +} + +/// One simulator's per-daemon breakdown, the `top` drill-down. +public struct TopProcesses: Codable, Equatable, Sendable { + public var udid: String + public var name: String + public var processes: [ProcessUsage] + public var totalBytes: Int64 + + public init(udid: String, name: String = "", processes: [ProcessUsage], totalBytes: Int64 = 0) { + self.udid = udid + self.name = name + self.processes = processes + self.totalBytes = totalBytes + } + + private enum CodingKeys: String, CodingKey { case udid, name, processes, totalBytes } + + public func encode(to encoder: Encoder) throws { + var c = encoder.container(keyedBy: CodingKeys.self) + try c.encode(udid, forKey: .udid) + if !name.isEmpty { try c.encode(name, forKey: .name) } // Go omitempty + try c.encode(processes, forKey: .processes) + try c.encode(totalBytes, forKey: .totalBytes) + } + + public init(from decoder: Decoder) throws { + let c = try decoder.container(keyedBy: CodingKeys.self) + udid = try c.decode(String.self, forKey: .udid) + name = try c.decodeIfPresent(String.self, forKey: .name) ?? "" + processes = try c.decode([ProcessUsage].self, forKey: .processes) + totalBytes = try c.decode(Int64.self, forKey: .totalBytes) + } +} + +extension Simctl { + /// Every process in the device's launchd tree, largest footprint first. + public func measureProcesses(udid: String) throws -> [ProcessUsage] { + let root = try simLaunchdPID(udid: udid) + let snapshot = try processSnapshot() + let footprint = try footprintByPID() + let procs = Simctl.treePIDs(root: root, children: snapshot.children).map { pid in + ProcessUsage( + pid: pid, command: snapshot.comm[pid] ?? "", bytes: footprint[pid] ?? 0, + cpu: snapshot.cpu[pid] ?? 0) + } + return procs.sorted { a, b in + a.bytes != b.bytes ? a.bytes > b.bytes : a.pid < b.pid + } + } + + /// The live resource view of every booted simulator: slim status and memory + /// from one shared process snapshot; disk usage is optional because it runs + /// `du` per device and is comparatively slow. + public func fleetSnapshot(withDisk: Bool) throws -> TopOutput { + let booted = try listDevices().filter { $0.state == "Booted" } + let (memory, memoryErrors) = measureMany(udids: booted.map(\.udid)) + + // Each simulator's status read is a simctl spawn; run them side by side. + let slots = Slots(count: booted.count) + DispatchQueue.concurrentPerform(iterations: booted.count) { i in + let device = booted[i] + var sim = TopSim(device: device) + do { + let status = try self.readStatus(for: device).status + sim.managedDisabled = status.managedDisabled + sim.managedTotal = status.managedTotal + } catch { + sim.statusError = error.localizedDescription + } + if withDisk, let bytes = try? self.deviceDiskUsage(udid: device.udid) { + sim.diskBytes = bytes + } + slots.set(i, sim) + } + + var out = TopOutput() + for var sim in slots.values { + if let measurement = memory[sim.device.udid] { + sim.memory = measurement + out.totalBytes += measurement.bytes + } else if let message = memoryErrors[sim.device.udid] { + sim.memoryError = message + } + out.sims.append(sim) + } + // Stable, so simulators without a measurement keep their listing order. + out.sims = out.sims.enumerated().sorted { a, b in + let (x, y) = (Simctl.topBytes(a.element), Simctl.topBytes(b.element)) + return x != y ? x > y : a.offset < b.offset + }.map(\.element) + return out + } + + static func topBytes(_ sim: TopSim) -> Int64 { sim.memory?.bytes ?? -1 } + + /// Allocated filesystem blocks for one exact simulator device directory. The + /// UDID is resolved through simctl first, so an alias such as `all` can never + /// become a filesystem path. + public func deviceDiskUsage(udid: String) throws -> Int64 { + let (_, dataDirectory) = try simulatorDataDirectory(udid: udid) + let devicePath = (dataDirectory as NSString).deletingLastPathComponent + let result = try exec(.du, ["-sk", devicePath]) + guard result.succeeded else { + throw SimSlimError( + "measure simulator disk usage: exit status \(result.status): \(result.combinedText)") + } + return try Simctl.parseDUDiskUsage(result.stdoutText) + } + + static func parseDUDiskUsage(_ output: String) throws -> Int64 { + guard let field = output.split(whereSeparator: \.isWhitespace).first else { + throw SimSlimError("du returned no disk usage") + } + guard let kib = Int64(field), kib >= 0, kib <= Int64.max / 1024 else { + throw SimSlimError("parse du disk usage \"\(field)\"") + } + return kib * 1024 + } + + /// The exact device and its data directory, which must be a real directory. + func simulatorDataDirectory(udid: String) throws -> (device: Device, dataDirectory: String) { + let device = try findDevice(udid: udid) + if device.dataPath.isEmpty { throw SimSlimError("simctl reported no data path for \(udid)") } + var info = stat() + guard lstat(device.dataPath, &info) == 0 else { + throw SimSlimError("locate simulator data: \(String(cString: strerror(errno)))") + } + if (info.st_mode & S_IFMT) != S_IFDIR { + throw SimSlimError("simulator data path is not a real directory: \(device.dataPath)") + } + return (device, device.dataPath) + } +} + +/// Fixed slots written from several threads, read in order afterwards. +private final class Slots: @unchecked Sendable { + private let lock = NSLock() + private var items: [T?] + init(count: Int) { items = Array(repeating: nil, count: count) } + func set(_ index: Int, _ value: T) { + lock.lock() + items[index] = value + lock.unlock() + } + var values: [T] { items.compactMap { $0 } } +} diff --git a/swift/Sources/SimSlimKit/Generated/CatalogData.swift b/swift/Sources/SimSlimKit/Generated/CatalogData.swift new file mode 100644 index 0000000..e45f913 --- /dev/null +++ b/swift/Sources/SimSlimKit/Generated/CatalogData.swift @@ -0,0 +1,623 @@ +// swift-format-ignore-file +// Copyright (c) 2026 Pavel Akhrameev (Swift port). MIT License; see LICENSE. + +let categorySeeds: [CategorySeed] = [ + CategorySeed( + id: "widgets", + name: "Widgets & Wallpaper", + description: "Home and lock screen posters, widgets, and Live Activities.", + downside: "Home and Lock Screen widgets, wallpaper posters, and Live Activities stop updating.", + approxMemoryMB: 675, + labels: [ + "com.apple.PosterBoard", + "com.apple.chronod", + "com.apple.liveactivitiesd", + "com.apple.navd", + ], + alwaysEnabled: [] + ), + CategorySeed( + id: "siri", + name: "Siri & Intelligence", + description: "Siri, Apple Intelligence, speech, and on-device ML model services.", + downside: "Siri, speech features, and Apple Intelligence services are unavailable.", + approxMemoryMB: 265, + labels: [ + "com.apple.assistant_cdmd", + "com.apple.assistant_service", + "com.apple.siriactionsd", + "com.apple.siriinferenced", + "com.apple.siriknowledged", + "com.apple.sirittsd", + "com.apple.siri.context.service", + "com.apple.siri.acousticsignature", + "com.apple.corespeechd", + "com.apple.voiced", + "com.apple.voicebankingd", + "com.apple.speechmodeltrainingd", + "com.apple.intelligenceplatformd", + "com.apple.intelligencecontextd", + "com.apple.intelligenceflowd", + "com.apple.intelligencetasksd", + "com.apple.generativeexperiencesd", + "com.apple.knowledgeconstructiond", + "com.apple.naturallanguaged", + "com.apple.textunderstandingd", + "com.apple.modelcatalogd", + "com.apple.modelmanagerd", + "com.apple.mlhostd", + "com.apple.mlruntimed", + "com.apple.suggestd", + "com.apple.parsecd", + "com.apple.parsec-fbf", + "com.apple.proactiveeventtrackerd", + ], + alwaysEnabled: [ + AlwaysEnabledService(label: "com.apple.assistantd", reason: "Hosts the dictation service; without it the system Spotlight app leaks memory."), + ] + ), + CategorySeed( + id: "search", + name: "Spotlight & Search", + description: "On-device Spotlight and in-Settings search services.", + downside: "Spotlight and Settings search return no results, and Recents in Files and the document picker fails to load.", + approxMemoryMB: 50, + labels: [ + "com.apple.searchd", + "com.apple.searchtoold", + "com.apple.spotlightknowledged", + "com.apple.spotlightknowledged.updater", + "com.apple.corespotlightservice", + ], + alwaysEnabled: [] + ), + CategorySeed( + id: "icloud", + name: "iCloud & Apple Account", + description: "iCloud sync, Apple Account, keychain, and backup services.", + downside: "iCloud sync, Apple Account, Keychain, and backup workflows will not work.", + approxMemoryMB: 100, + labels: [ + "com.apple.appleaccountd", + "com.apple.appleaccounttransparencyd", + "com.apple.appleidsetupd", + "com.apple.akd", + "com.apple.amsaccountsd", + "com.apple.amsengagementd", + "com.apple.amsondevicestoraged", + "com.apple.cloudd", + "com.apple.cloudphotod", + "com.apple.ckdiscretionaryd", + "com.apple.cloudsettingssyncagent", + "com.apple.bird", + "com.apple.syncdefaultsd", + "com.apple.cdpd", + "com.apple.sosd", + "com.apple.SecureBackupDaemon", + "com.apple.TrustedPeersHelper", + "com.apple.protectedcloudstorage.protectedcloudkeysyncing", + "com.apple.icloudmailagent", + "com.apple.icloudsubscriptionoptimizerd", + "com.apple.communicationtrustd", + ], + alwaysEnabled: [] + ), + CategorySeed( + id: "store", + name: "App Store, Push & Media", + description: "App Store, push notification, StoreKit, and media services.", + downside: "Remote push notifications and StoreKit or App Store testing will not work.", + approxMemoryMB: 80, + labels: [ + "com.apple.appstored", + "com.apple.appstorecomponentsd", + "com.apple.apsd", + "com.apple.itunescloudd", + "com.apple.itunesstored", + "com.apple.storekitd", + "com.apple.amsaccountsd", + "com.apple.amsengagementd", + "com.apple.amsondevicestoraged", + "com.apple.passd", + "com.apple.financed", + "com.apple.videosubscriptionsd", + "com.apple.assetsubscriptiond", + "com.apple.musicd", + ], + alwaysEnabled: [] + ), + CategorySeed( + id: "pim", + name: "Mail, Calendar & Contacts", + description: "Mail, Calendar, Contacts, Reminders, and related sync services.", + downside: "Contacts, Calendar, Reminders, and Mail-backed pickers or sync may fail.", + approxMemoryMB: 80, + labels: [ + "com.apple.email.maild", + "com.apple.exchangesyncd", + "com.apple.dataaccess.dataaccessd", + "com.apple.calaccessd", + "com.apple.remindd", + "com.apple.contactsd", + "com.apple.contacts.postersyncd", + "com.apple.peopled", + ], + alwaysEnabled: [] + ), + CategorySeed( + id: "web", + name: "Safari Sync & Web Services", + description: "Safari sync, web push, privacy, and universal-link services.", + downside: "Universal links and Safari sync or background web services will not work.", + approxMemoryMB: 50, + labels: [ + "com.apple.SafariBookmarksSyncAgent", + "com.apple.Safari.History", + "com.apple.Safari.passwordbreachd", + "com.apple.Safari.SafeBrowsing.Service", + "com.apple.safarifetcherd", + "com.apple.WebBookmarks.webbookmarksd", + "com.apple.webkit.adattributiond", + "com.apple.webkit.webpushd", + "com.apple.webprivacyd", + "com.apple.swcd", + ], + alwaysEnabled: [] + ), + CategorySeed( + id: "family", + name: "Family & Screen Time", + description: "Family Sharing, Screen Time, and usage tracking.", + downside: "Family Sharing, Screen Time, and usage tracking stop working.", + approxMemoryMB: 65, + labels: [ + "com.apple.familycircled", + "com.apple.FamilyControlsAgent", + "com.apple.familynotification", + "com.apple.askpermissiond", + "com.apple.asktod", + "com.apple.ScreenTimeAgent", + "com.apple.ScreenTimeSettingsAgent", + "com.apple.UsageTrackingAgent", + ], + alwaysEnabled: [] + ), + CategorySeed( + id: "health", + name: "Health, Home & Fitness", + description: "HealthKit, HomeKit, and Fitness services.", + downside: "HealthKit, HomeKit, and Fitness integrations will not work.", + approxMemoryMB: 135, + labels: [ + "com.apple.healthd", + "com.apple.healthappd", + "com.apple.healthcontentd", + "com.apple.healtheventsd", + "com.apple.healthrecordsd", + "com.apple.finhealthd", + "com.apple.homed", + "com.apple.homeeventsd", + "com.apple.fitcore", + "com.apple.fitcore.session", + "com.apple.fitnesscoachingd", + "com.apple.fitnessintelligenced", + "com.apple.activityawardsd", + "com.apple.activitysharingd", + ], + alwaysEnabled: [] + ), + CategorySeed( + id: "photos", + name: "Photos & Media Analysis", + description: "Photos library, photo analysis, and media analysis services.", + downside: "Photo picker, Photos-library workflows, and media analysis may fail.", + approxMemoryMB: 60, + labels: [ + "com.apple.photoanalysisd", + "com.apple.photosface", + "com.apple.mediaanalysisd", + "com.apple.mediaanalysisd.service", + "com.apple.mediastream.mstreamd", + "com.apple.medialibraryd", + "com.apple.assetsd", + "com.apple.assetsd.nebulad", + ], + alwaysEnabled: [] + ), + CategorySeed( + id: "apps", + name: "News, Weather, Maps & Games", + description: "News, Weather, Maps, Tips, and game services.", + downside: "News, Weather, Maps background data, and game-controller services are unavailable.", + approxMemoryMB: 90, + labels: [ + "com.apple.newsd", + "com.apple.weatherd", + "com.apple.Maps.mapssyncd", + "com.apple.Maps.mapspushd", + "com.apple.Maps.geocorrectiond", + "com.apple.maps.destinationd", + "com.apple.MapKit.SnapshotService", + "com.apple.jetpackassetd", + "com.apple.tipsd", + "com.apple.gamesaved", + "com.apple.GameController.gamecontrollerd", + ], + alwaysEnabled: [ + AlwaysEnabledService(label: "com.apple.gamed", reason: "Required for timely XCUITest app launches (DTServiceHub / GameKit)."), + ] + ), + CategorySeed( + id: "messaging", + name: "Messaging & FaceTime", + description: "iMessage, FaceTime, call, and identity services.", + downside: "iMessage, FaceTime, and related identity services will not work.", + approxMemoryMB: 60, + labels: [ + "com.apple.identityservicesd", + "com.apple.ids_simd", + "com.apple.imautomatichistorydeletionagent", + "com.apple.imcore.imtransferagent", + "com.apple.imdpersistence.IMDPersistenceAgent", + "com.apple.facetimemessagestored", + "com.apple.telephonyutilities.callservicesd", + ], + alwaysEnabled: [] + ), + CategorySeed( + id: "connectivity", + name: "Sharing & Device Connectivity", + description: "AirDrop, Continuity, CarPlay, Watch, and Find My services.", + downside: "AirDrop, Continuity, CarPlay, Watch, and Find My connectivity will not work.", + approxMemoryMB: 65, + labels: [ + "com.apple.rapportd", + "com.apple.companiond", + "com.apple.carkitd", + "com.apple.wcd", + "com.apple.tvremoted", + "com.apple.avatarsd", + "com.apple.stickersd", + "com.apple.sociallayerd", + "com.apple.announced", + "com.apple.navd", + "com.apple.findmy.findmylocated", + ], + alwaysEnabled: [ + AlwaysEnabledService(label: "com.apple.sharingd", reason: "Required for system share sheets."), + ] + ), + CategorySeed( + id: "telemetry", + name: "Ads, Diagnostics & Telemetry", + description: "DeviceCheck, ad privacy, analytics, diagnostics, and feedback services.", + downside: "DeviceCheck plus analytics, diagnostics, and feedback services are unavailable.", + approxMemoryMB: 105, + labels: [ + "com.apple.ap.adprivacyd", + "com.apple.ap.promotedcontentd", + "com.apple.diagnosticextensionsd", + "com.apple.feedbackd", + "com.apple.rtcreportingd", + "com.apple.securityuploadd", + "com.apple.geoanalyticsd", + "com.apple.triald", + "com.apple.followupd", + "com.apple.purplebuddy.budd", + "com.apple.devicecheckd", + ], + alwaysEnabled: [] + ), + CategorySeed( + id: "mdm", + name: "Device Management", + description: "Declarative device management and managed asset services.", + downside: "Declarative device management, and MDM or configuration-profile workflows that use it, will not work.", + approxMemoryMB: 10, + labels: [ + "com.apple.remotemanagementd", + "com.apple.RemoteManagementAgent", + "com.apple.managedassetsd", + ], + alwaysEnabled: [] + ), + CategorySeed( + id: "other", + name: "Other Background Services", + description: "Wallet, App Clips, business services, assets, and miscellaneous background daemons.", + downside: "Wallet, App Clips, accessibility asset downloads, merchant, business, and miscellaneous background services are unavailable.", + approxMemoryMB: 225, + labels: [ + "com.apple.financed", + "com.apple.passd", + "com.apple.merchantd", + "com.apple.coreidvd", + "com.apple.businessservicesd", + "com.apple.deviceaccessd", + "com.apple.replicatord", + "com.apple.linkd", + "com.apple.ind", + "com.apple.storagedatad", + "com.apple.StatusKitAgent", + "com.apple.countryd", + "com.apple.mobileassetd", + "com.apple.managedconfiguration.passcodenagd", + "com.apple.accessibility.axassetsd", + "com.apple.ClipServices.clipserviced", + ], + alwaysEnabled: [] + ), +] + +let serviceDescriptionByLabel: [String: String] = [ + "com.apple.PosterBoard": "Renders Home and Lock Screen wallpaper scenes.", + "com.apple.chronod": "Refreshes widgets and complications on schedule.", + "com.apple.liveactivitiesd": "Updates Live Activities and Dynamic Island content.", + "com.apple.assistant_cdmd": "Routes commands and intents submitted to Siri.", + "com.apple.assistant_service": "Provides supporting services for Siri requests.", + "com.apple.siriactionsd": "Executes Siri actions and App Intents.", + "com.apple.siriinferenced": "Runs Siri inference and intent predictions.", + "com.apple.siriknowledged": "Maintains knowledge and context used by Siri.", + "com.apple.sirittsd": "Generates Siri's spoken responses.", + "com.apple.siri.context.service": "Builds device context for Siri requests.", + "com.apple.siri.acousticsignature": "Processes acoustic signatures for voice features.", + "com.apple.corespeechd": "Provides speech recognition and voice-trigger services.", + "com.apple.voiced": "Manages system voices and speech assets.", + "com.apple.voicebankingd": "Supports Personal Voice and voice banking.", + "com.apple.speechmodeltrainingd": "Adapts on-device speech recognition models.", + "com.apple.intelligenceplatformd": "Coordinates Apple Intelligence services.", + "com.apple.intelligencecontextd": "Collects local context for intelligence features.", + "com.apple.intelligenceflowd": "Orchestrates Apple Intelligence workflows.", + "com.apple.intelligencetasksd": "Runs background Apple Intelligence tasks.", + "com.apple.generativeexperiencesd": "Supports generative intelligence experiences.", + "com.apple.knowledgeconstructiond": "Builds on-device knowledge used by suggestions.", + "com.apple.naturallanguaged": "Performs natural-language analysis.", + "com.apple.textunderstandingd": "Extracts meaning and entities from text.", + "com.apple.modelcatalogd": "Tracks machine-learning models available to the system.", + "com.apple.modelmanagerd": "Downloads and manages on-device models.", + "com.apple.mlhostd": "Hosts system machine-learning services.", + "com.apple.mlruntimed": "Executes on-device machine-learning models.", + "com.apple.suggestd": "Generates system suggestions and predictions.", + "com.apple.parsecd": "Provides network-backed Siri and Spotlight suggestions.", + "com.apple.parsec-fbf": "Collects feedback for Siri and Spotlight suggestions.", + "com.apple.proactiveeventtrackerd": "Tracks events used by proactive suggestions.", + "com.apple.searchd": "Coordinates system search queries.", + "com.apple.searchtoold": "Runs helper tasks for system search.", + "com.apple.spotlightknowledged": "Builds knowledge used by Spotlight results.", + "com.apple.spotlightknowledged.updater": "Refreshes Spotlight's knowledge data.", + "com.apple.corespotlightservice": "Indexes and searches app-provided content.", + "com.apple.appleaccountd": "Maintains Apple Account state on the device.", + "com.apple.appleaccounttransparencyd": "Checks Apple Account security records.", + "com.apple.appleidsetupd": "Handles Apple Account setup workflows.", + "com.apple.akd": "Provides Apple Account authentication tokens.", + "com.apple.amsaccountsd": "Manages App Store and media account state.", + "com.apple.amsengagementd": "Handles App Store and media engagement messages.", + "com.apple.amsondevicestoraged": "Stores Apple media-service data on the device.", + "com.apple.cloudd": "Synchronizes CloudKit databases and records.", + "com.apple.cloudphotod": "Synchronizes the iCloud Photos library.", + "com.apple.ckdiscretionaryd": "Schedules non-urgent CloudKit transfers.", + "com.apple.cloudsettingssyncagent": "Synchronizes supported system settings through iCloud.", + "com.apple.bird": "Synchronizes iCloud Drive files.", + "com.apple.syncdefaultsd": "Synchronizes supported preferences between devices.", + "com.apple.cdpd": "Handles iCloud data-protection setup and recovery.", + "com.apple.sosd": "Synchronizes iCloud Keychain secure items.", + "com.apple.SecureBackupDaemon": "Handles secure backup and account recovery data.", + "com.apple.TrustedPeersHelper": "Maintains trusted peers for iCloud Keychain.", + "com.apple.protectedcloudstorage.protectedcloudkeysyncing": "Synchronizes protected cloud encryption keys.", + "com.apple.icloudmailagent": "Runs background services for iCloud Mail.", + "com.apple.icloudsubscriptionoptimizerd": "Evaluates iCloud storage subscription recommendations.", + "com.apple.communicationtrustd": "Maintains communication trust and safety state.", + "com.apple.appstored": "Installs and updates apps from the App Store.", + "com.apple.appstorecomponentsd": "Provides background components used by the App Store.", + "com.apple.apsd": "Receives Apple Push Notification service messages.", + "com.apple.itunescloudd": "Synchronizes purchased and cloud media libraries.", + "com.apple.itunesstored": "Handles media-store accounts and purchases.", + "com.apple.storekitd": "Processes StoreKit products and transactions.", + "com.apple.videosubscriptionsd": "Manages video subscriptions and TV providers.", + "com.apple.assetsubscriptiond": "Manages subscribed media assets and downloads.", + "com.apple.musicd": "Runs background Music library and playback services.", + "com.apple.email.maild": "Fetches, indexes, and sends Mail account data.", + "com.apple.exchangesyncd": "Synchronizes Microsoft Exchange account data.", + "com.apple.dataaccess.dataaccessd": "Synchronizes CalDAV, CardDAV, and related accounts.", + "com.apple.calaccessd": "Provides access to Calendar event data.", + "com.apple.remindd": "Stores and synchronizes reminders.", + "com.apple.contactsd": "Provides access to the Contacts database.", + "com.apple.contacts.postersyncd": "Synchronizes Contact Posters.", + "com.apple.peopled": "Builds people and relationship suggestions.", + "com.apple.SafariBookmarksSyncAgent": "Synchronizes Safari bookmarks through iCloud.", + "com.apple.Safari.History": "Maintains and synchronizes Safari history.", + "com.apple.Safari.passwordbreachd": "Checks saved passwords for known data leaks.", + "com.apple.Safari.SafeBrowsing.Service": "Checks sites against unsafe browsing data.", + "com.apple.safarifetcherd": "Fetches Safari content in the background.", + "com.apple.WebBookmarks.webbookmarksd": "Maintains web bookmarks, clips, and Reading List data.", + "com.apple.webkit.adattributiond": "Processes privacy-preserving web ad attribution.", + "com.apple.webkit.webpushd": "Receives push notifications for websites.", + "com.apple.webprivacyd": "Maintains Safari privacy-protection data.", + "com.apple.swcd": "Matches universal links with installed apps.", + "com.apple.familycircled": "Maintains Family Sharing membership and state.", + "com.apple.FamilyControlsAgent": "Applies parental and Family Controls restrictions.", + "com.apple.familynotification": "Delivers Family Sharing invitations and notices.", + "com.apple.askpermissiond": "Handles Ask to Buy permission requests.", + "com.apple.asktod": "Routes family approval prompts and responses.", + "com.apple.ScreenTimeAgent": "Enforces Screen Time limits and reports usage.", + "com.apple.ScreenTimeSettingsAgent": "Connects Screen Time data to Settings.", + "com.apple.UsageTrackingAgent": "Tracks app and website usage duration.", + "com.apple.healthd": "Stores and serves HealthKit data.", + "com.apple.healthappd": "Runs background tasks for the Health app.", + "com.apple.healthcontentd": "Provides educational and recommended health content.", + "com.apple.healtheventsd": "Processes health events and related notifications.", + "com.apple.healthrecordsd": "Synchronizes clinical health records.", + "com.apple.finhealthd": "Analyzes Wallet transactions and financial-health data.", + "com.apple.homed": "Manages HomeKit accessories, rooms, and automations. Kept enabled on watchOS.", + "com.apple.homeeventsd": "Processes HomeKit events and automation triggers.", + "com.apple.fitcore": "Runs Apple Fitness content and background services.", + "com.apple.fitcore.session": "Manages active Apple Fitness sessions.", + "com.apple.fitnesscoachingd": "Provides Fitness coaching recommendations.", + "com.apple.fitnessintelligenced": "Generates personalized Fitness insights.", + "com.apple.activityawardsd": "Tracks Activity awards and achievements.", + "com.apple.activitysharingd": "Synchronizes shared Activity and Fitness data.", + "com.apple.photoanalysisd": "Analyzes photos for scenes, people, and search.", + "com.apple.photosface": "Performs face detection for the Photos library.", + "com.apple.mediaanalysisd": "Analyzes image, video, and audio content.", + "com.apple.mediaanalysisd.service": "Runs isolated media-analysis work.", + "com.apple.mediastream.mstreamd": "Synchronizes shared and streamed photo content.", + "com.apple.medialibraryd": "Maintains the system media library database.", + "com.apple.assetsd": "Provides access to Photos library assets.", + "com.apple.assetsd.nebulad": "Handles cloud-backed Photos asset transfers.", + "com.apple.newsd": "Downloads and refreshes Apple News content.", + "com.apple.weatherd": "Fetches forecasts and weather data.", + "com.apple.Maps.mapssyncd": "Synchronizes Maps favorites, guides, and history.", + "com.apple.Maps.mapspushd": "Receives background updates for Maps.", + "com.apple.Maps.geocorrectiond": "Improves and corrects map location data.", + "com.apple.maps.destinationd": "Predicts and maintains suggested destinations.", + "com.apple.MapKit.SnapshotService": "Renders static map snapshots for apps.", + "com.apple.jetpackassetd": "Downloads assets used by Apple content apps.", + "com.apple.tipsd": "Selects and refreshes content for the Tips app.", + "com.apple.gamesaved": "Synchronizes supported game save data.", + "com.apple.GameController.gamecontrollerd": "Discovers controllers and routes their input.", + "com.apple.identityservicesd": "Maintains identities used by iMessage and FaceTime.", + "com.apple.ids_simd": "Provides simulator support for Apple identity services.", + "com.apple.imautomatichistorydeletionagent": "Removes Messages history according to retention settings.", + "com.apple.imcore.imtransferagent": "Transfers Messages attachments and media.", + "com.apple.imdpersistence.IMDPersistenceAgent": "Stores Messages conversations and metadata.", + "com.apple.facetimemessagestored": "Stores FaceTime messages and related data.", + "com.apple.telephonyutilities.callservicesd": "Coordinates FaceTime and system call state.", + "com.apple.rapportd": "Discovers nearby devices for Continuity features.", + "com.apple.companiond": "Coordinates communication with paired companion devices.", + "com.apple.carkitd": "Provides CarPlay connection and vehicle services.", + "com.apple.wcd": "Handles connectivity with a paired Apple Watch.", + "com.apple.tvremoted": "Provides Apple TV discovery and remote control.", + "com.apple.avatarsd": "Maintains avatars and Memoji assets.", + "com.apple.stickersd": "Maintains sticker packs and recently used stickers.", + "com.apple.sociallayerd": "Supports social sharing and activity features.", + "com.apple.announced": "Supports announced notifications and audio messages.", + "com.apple.navd": "Coordinates background navigation state.", + "com.apple.findmy.findmylocated": "Provides device location data to Find My.", + "com.apple.ap.adprivacyd": "Maintains advertising privacy preferences and state.", + "com.apple.ap.promotedcontentd": "Fetches and manages promoted Apple content.", + "com.apple.diagnosticextensionsd": "Runs system diagnostic data collectors.", + "com.apple.feedbackd": "Collects and submits system feedback reports.", + "com.apple.rtcreportingd": "Reports diagnostics for real-time communications.", + "com.apple.securityuploadd": "Uploads security and trust telemetry.", + "com.apple.geoanalyticsd": "Collects Maps and location-quality analytics.", + "com.apple.triald": "Manages system feature experiments and configurations.", + "com.apple.followupd": "Schedules account and setup follow-up notices.", + "com.apple.purplebuddy.budd": "Maintains Setup Assistant completion state.", + "com.apple.devicecheckd": "Provides DeviceCheck and app-attestation services.", + "com.apple.remotemanagementd": "Applies declarative device management configurations.", + "com.apple.RemoteManagementAgent": "Applies per-user declarative management configurations.", + "com.apple.managedassetsd": "Downloads assets referenced by management declarations.", + "com.apple.financed": "Provides Wallet transaction and finance services.", + "com.apple.passd": "Manages Wallet passes and Apple Pay state.", + "com.apple.merchantd": "Looks up merchant details for Wallet transactions.", + "com.apple.coreidvd": "Manages supported digital identity credentials.", + "com.apple.businessservicesd": "Supports Apple business messaging and services.", + "com.apple.deviceaccessd": "Coordinates app access to supported accessories.", + "com.apple.replicatord": "Replicates supported system data between services.", + "com.apple.linkd": "Indexes App Intents and shortcut suggestions.", + "com.apple.ind": "Receives background iCloud notifications.", + "com.apple.storagedatad": "Calculates storage usage shown by the system.", + "com.apple.StatusKitAgent": "Shares Focus, presence, and status between devices.", + "com.apple.countryd": "Determines regional availability for system features.", + "com.apple.mobileassetd": "Downloads and manages system asset packages. Kept enabled on visionOS.", + "com.apple.managedconfiguration.passcodenagd": "Enforces managed passcode requirements.", + "com.apple.accessibility.axassetsd": "Downloads accessibility assets such as speech voices.", + "com.apple.ClipServices.clipserviced": "Downloads, launches, and manages App Clips.", +] + +let featureList: [Feature] = [ + Feature(id: "push", name: "Push notifications", labels: [ + "com.apple.apsd", + ]), + Feature(id: "storekit", name: "StoreKit / in-app purchase", labels: [ + "com.apple.storekitd", + "com.apple.itunesstored", + "com.apple.amsaccountsd", + "com.apple.amsengagementd", + "com.apple.amsondevicestoraged", + "com.apple.passd", + "com.apple.financed", + ]), + Feature(id: "app-store", name: "App Store", labels: [ + "com.apple.appstored", + "com.apple.itunesstored", + ]), + Feature(id: "universal-links", name: "Universal links / associated domains", labels: [ + "com.apple.swcd", + ]), + Feature(id: "spotlight", name: "Spotlight & Settings search", labels: [ + "com.apple.searchd", + "com.apple.searchtoold", + ]), + Feature(id: "files-recents", name: "Files & document picker Recents", labels: [ + "com.apple.searchd", + ]), + Feature(id: "siri", name: "Siri & speech", labels: [ + "com.apple.assistantd", + "com.apple.corespeechd", + ]), + Feature(id: "icloud", name: "iCloud sync", labels: [ + "com.apple.cloudd", + ]), + Feature(id: "keychain-sync", name: "iCloud Keychain", labels: [ + "com.apple.akd", + ]), + Feature(id: "contacts", name: "Contacts", labels: [ + "com.apple.contactsd", + ]), + Feature(id: "calendar", name: "Calendar", labels: [ + "com.apple.calaccessd", + ]), + Feature(id: "reminders", name: "Reminders", labels: [ + "com.apple.remindd", + ]), + Feature(id: "mail", name: "Mail", labels: [ + "com.apple.email.maild", + ]), + Feature(id: "photos", name: "Photos library & analysis", labels: [ + "com.apple.assetsd", + "com.apple.photoanalysisd", + ]), + Feature(id: "health", name: "HealthKit", labels: [ + "com.apple.healthd", + ]), + Feature(id: "homekit", name: "HomeKit", labels: [ + "com.apple.homed", + ]), + Feature(id: "imessage", name: "iMessage & FaceTime", labels: [ + "com.apple.identityservicesd", + ]), + Feature(id: "widgets", name: "Widgets & Live Activities", labels: [ + "com.apple.chronod", + "com.apple.liveactivitiesd", + "com.apple.navd", + ]), + Feature(id: "wallet", name: "Wallet & passes", labels: [ + "com.apple.passd", + ]), + Feature(id: "maps", name: "Maps background services", labels: [ + "com.apple.Maps.mapssyncd", + ]), + Feature(id: "weather", name: "Weather", labels: [ + "com.apple.weatherd", + ]), + Feature(id: "news", name: "News", labels: [ + "com.apple.newsd", + ]), + Feature(id: "game-center", name: "Game Center", labels: [ + "com.apple.gamed", + ]), + Feature(id: "find-my", name: "Find My", labels: [ + "com.apple.findmy.findmylocated", + ]), + Feature(id: "mdm", name: "Declarative device management", labels: [ + "com.apple.remotemanagementd", + "com.apple.RemoteManagementAgent", + ]), + Feature(id: "app-clips", name: "App Clips", labels: [ + "com.apple.ClipServices.clipserviced", + ]), + Feature(id: "screen-time", name: "Screen Time", labels: [ + "com.apple.ScreenTimeAgent", + ]), +] diff --git a/swift/Sources/SimSlimKit/GoFormat.swift b/swift/Sources/SimSlimKit/GoFormat.swift new file mode 100644 index 0000000..fff16d1 --- /dev/null +++ b/swift/Sources/SimSlimKit/GoFormat.swift @@ -0,0 +1,54 @@ +// Copyright (c) 2026 Pavel Akhrameev (Swift port). MIT License; see LICENSE. + +import Foundation + +/// Go's `%q` (`strconv.Quote`): quote, backslash and the C escapes are +/// escaped, and so is every scalar Go does not call printable (anything outside +/// the letter, mark, number, punctuation and symbol categories and the ASCII +/// space), as `\uXXXX` or `\UXXXXXXXX`. A name such as one with a zero-width +/// joiner therefore prints visibly escaped, as it does in Go. +public func goQuote(_ text: String) -> String { + var out = "\"" + for ch in text.unicodeScalars { + switch ch { + case "\"": out += "\\\"" + case "\\": out += "\\\\" + case "\u{07}": out += "\\a" + case "\u{08}": out += "\\b" + case "\u{0C}": out += "\\f" + case "\n": out += "\\n" + case "\r": out += "\\r" + case "\t": out += "\\t" + case "\u{0B}": out += "\\v" + default: + if isGoPrintable(ch) { + out.unicodeScalars.append(ch) + } else if ch.value < 0x10000 { + out += "\\u" + hexDigits(ch.value, width: 4) + } else { + out += "\\U" + hexDigits(ch.value, width: 8) + } + } + } + return out + "\"" +} + +func hexDigits(_ value: UInt32, width: Int) -> String { + let digits = String(value, radix: 16) + return String(repeating: "0", count: max(0, width - digits.count)) + digits +} + +func isGoPrintable(_ scalar: Unicode.Scalar) -> Bool { + if scalar == " " { return true } + switch scalar.properties.generalCategory { + case .uppercaseLetter, .lowercaseLetter, .titlecaseLetter, .modifierLetter, .otherLetter, + .nonspacingMark, .spacingMark, .enclosingMark, + .decimalNumber, .letterNumber, .otherNumber, + .connectorPunctuation, .dashPunctuation, .openPunctuation, .closePunctuation, + .initialPunctuation, .finalPunctuation, .otherPunctuation, + .mathSymbol, .currencySymbol, .modifierSymbol, .otherSymbol: + return true + default: + return false + } +} diff --git a/swift/Sources/SimSlimKit/LaunchdBatch.swift b/swift/Sources/SimSlimKit/LaunchdBatch.swift new file mode 100644 index 0000000..7646869 --- /dev/null +++ b/swift/Sources/SimSlimKit/LaunchdBatch.swift @@ -0,0 +1,96 @@ +// Copyright (c) 2026 Pavel Akhrameev (Swift port). MIT License; see LICENSE. + +import Foundation + +/// The RuntimeRoot directories holding the job plists launchd_sim bootstraps +/// into the simulator's system domain. +let launchdJobDirs = ["System/Library/LaunchDaemons", "System/Library/LaunchAgents"] + +/// Bounds how many plist paths go into one `launchctl unload`, so the argument +/// list stays far below ARG_MAX however long the profile grows. +let unloadChunk = 64 + +/// Reads `launchctl list` rows: "PIDStatusLabel", with "-" as the PID +/// of a loaded job that is not running. +func parseLaunchctlList(_ output: String) -> Set { + var loaded = Set() + for line in output.split(whereSeparator: \.isNewline) { + let fields = line.split(whereSeparator: { $0 == " " || $0 == "\t" || $0 == "\r" }) + if fields.count != 3 || fields[2] == "Label" { continue } + loaded.insert(String(fields[2])) + } + return loaded +} + +/// Keeps the labels the batch did not finish: no disable override yet, or still +/// loaded. A few jobs stay listed even with their override in place, so they +/// always take the per-label bootout. +func stillToStop(_ labels: [String], disabled: Set, loaded: Set) -> [String] { + labels.filter { !disabled.contains($0) || loaded.contains($0) } +} + +extension Simctl { + /// Reads a job plist's Label with the host's plutil, which handles both XML + /// and binary plists. + func readPlistLabel(path: String) throws -> String { + let result = try exec(.plutil, ["-extract", "Label", "raw", "-o", "-", path]) + guard result.succeeded else { + throw SimSlimError("plutil: exit status \(result.status): \(result.combinedText)") + } + return result.stdoutText.trimmingCharacters(in: .whitespacesAndNewlines) + } + + /// Maps each label to the job plist that defines exactly that label. A plist + /// is used only when its own Label key matches, so a renamed or shared file + /// can never unload a daemon outside the allowlist. + func launchdJobPlists(root: String, labels: [String], plistLabel: (String) throws -> String) + -> [String: String] + { + var paths: [String: String] = [:] + for label in labels { + if deadlineExpired { break } + for dir in launchdJobDirs { + let path = ((root as NSString).appendingPathComponent(dir) as NSString) + .appendingPathComponent(label + ".plist") + guard FileManager.default.fileExists(atPath: path) else { continue } + if let got = try? plistLabel(path), got == label { + paths[label] = path + break + } + } + } + return paths + } + + /// Every label currently loaded in the simulator's launchd. + func loadedLabels(set: String, udid: String) throws -> Set { + parseLaunchctlList(try readLaunchd(set: set, udid: udid, ["list"])) + } + + /// One `launchctl -w` spawn per chunk of plists. The exit status is not + /// trusted: launchctl reports any single failure for the whole call, so the + /// caller reads the state back. A chunk that runs out of time ends the batch, + /// so a slow host keeps the rest of its budget for the per-label path. + func batchJobs(set: String, udid: String, verb: String, paths: [String]) { + var start = 0 + while start < paths.count { + let end = min(start + unloadChunk, paths.count) + let args = simctlArgs( + set: set, ["spawn", udid, "launchctl", verb, "-w"] + Array(paths[start.. [String] { + let disabled = try readDisabled(set: set, udid: udid) + let loaded = try loadedLabels(set: set, udid: udid) + return stillToStop(labels, disabled: disabled, loaded: loaded) + } +} diff --git a/swift/Sources/SimSlimKit/Lifecycle.swift b/swift/Sources/SimSlimKit/Lifecycle.swift new file mode 100644 index 0000000..f6fb751 --- /dev/null +++ b/swift/Sources/SimSlimKit/Lifecycle.swift @@ -0,0 +1,163 @@ +// Copyright (c) 2026 Pavel Akhrameev (Swift port). MIT License; see LICENSE. + +import Foundation + +/// Progress lines for operations that take minutes. The caller decides where +/// they go (the CLI sends them to stderr); a nil reporter is a no-op. +public typealias Reporter = @Sendable (String) -> Void + +func report(_ reporter: Reporter?, _ message: String) { reporter?(message) } + +extension Simctl { + /// Runs `xcrun ` and turns a failure into Go's `xcrun : exit status + /// N: `. + func xcrunChecked(_ args: [String], timeout: TimeInterval? = nil) throws -> CommandResult { + let result = try exec(.xcrun, args, timeout: timeout) + if result.succeeded { return result } + let reason = result.timedOut ? "signal: killed" : "exit status \(result.status)" + throw SimSlimError("xcrun \(args.joined(separator: " ")): \(reason): \(result.combinedText)") + } + + public static let shutdownTimeout: TimeInterval = 30 + + /// Boots the device, tolerating one that is already booted, and blocks on + /// `bootstatus -b` until its services are ready. + public func bootAndWait(set: String, udid: String) throws { + let boot = try exec(.xcrun, simctlArgs(set: set, ["boot", udid])) + if !boot.succeeded { + let message = boot.combinedText + if !message.contains("already booted") && !message.contains("current state: Booted") { + throw SimSlimError("simctl boot: exit status \(boot.status): \(message)") + } + } + _ = try xcrunChecked(simctlArgs(set: set, ["bootstatus", udid, "-b"])) + } + + /// Shuts the device down, tolerating one that is already shut down. + public func shutdown(set: String, udid: String) throws { + let result = try exec(.xcrun, simctlArgs(set: set, ["shutdown", udid])) + if result.succeeded { return } + if result.combinedText.contains("current state: Shutdown") { return } + throw SimSlimError("simctl shutdown: exit status \(result.status): \(result.combinedText)") + } + + /// Polls until the device reports Shutdown. + public func waitShutdown( + set: String, udid: String, timeout: TimeInterval = Simctl.shutdownTimeout + ) throws { + let limit = now().addingTimeInterval(timeout) + while now() < limit { + if try findDevice(udid: udid, set: set).state == "Shutdown" { return } + sleep(0.5) + } + throw SimSlimError("timed out waiting for \(udid) to shut down") + } + + /// Shuts the device down and waits for it, under the shutdown timeout. + public func shutdownAndWait(set: String, udid: String) throws { + var bounded = self + bounded.deadline = now().addingTimeInterval(Simctl.shutdownTimeout) + try bounded.shutdown(set: set, udid: udid) + try bounded.waitShutdown(set: set, udid: udid) + } + + /// The host path of a CoreSimulator runtime's RuntimeRoot. Simulator processes + /// see the host file system, so launchctl inside the simulator can read job + /// plists by these paths. Runtimes are global, never per device set. + func runtimeRoot(runtimeID: String) throws -> String { + let result = try exec(.xcrun, ["simctl", "list", "runtimes", "-j"]) + guard result.succeeded else { + throw Simctl.listError(status: result.status, stderr: result.stderrText) + } + return try Simctl.parseRuntimeRoot(result.stdout, runtimeID: runtimeID) + } + + static func parseRuntimeRoot(_ data: Data, runtimeID: String) throws -> String { + struct Runtimes: Decodable { + struct Entry: Decodable { + var identifier: String? + var runtimeRoot: String? + } + var runtimes: [Entry] + } + let parsed: Runtimes + do { + parsed = try JSONDecoder().decode(Runtimes.self, from: data) + } catch { + throw SimSlimError("parse simctl list runtimes: \(error.localizedDescription)") + } + for entry in parsed.runtimes where entry.identifier == runtimeID { + if let root = entry.runtimeRoot, !root.isEmpty { return root } + } + throw SimSlimError("runtime \(runtimeID) has no runtimeRoot") + } +} + +// MARK: - Management + +/// Go's `unicode.IsSpace` set: Foundation's `.whitespacesAndNewlines` also trims +/// U+200B, which Go does not. +private let goSpace: Set = { + var set: Set = [ + 0x09, 0x0A, 0x0B, 0x0C, 0x0D, 0x20, 0x85, 0xA0, 0x1680, 0x2028, 0x2029, 0x202F, 0x205F, + 0x3000, + ] + for value in UInt32(0x2000)...UInt32(0x200A) { set.insert(value) } + return set +}() + +func goTrimSpace(_ text: String) -> String { + var scalars = Substring(text).unicodeScalars + while let last = scalars.last, goSpace.contains(last.value) { scalars.removeLast() } + while let first = scalars.first, goSpace.contains(first.value) { scalars.removeFirst() } + return String(scalars) +} + +/// Trims a simulator name and rejects what simctl or the app could not show. +public func normalizeSimulatorName(_ name: String) throws -> String { + let trimmed = goTrimSpace(name) + if trimmed.isEmpty { throw SimSlimError("simulator name cannot be empty") } + if trimmed.unicodeScalars.count > 128 { + throw SimSlimError("simulator name cannot exceed 128 characters") + } + if trimmed.unicodeScalars.contains(where: { $0.properties.generalCategory == .control }) { + throw SimSlimError("simulator name cannot contain control characters") + } + return trimmed +} + +extension Simctl { + /// Resolves the exact device before any destructive command, so a simctl alias + /// such as `all` can never enter these code paths, and shuts it down if it is + /// booted. Returns the device's set so the caller can target its own simctl + /// call there. + func shutdownIfBooted(udid: String) throws -> String { + let device = try findDevice(udid: udid) + // Go would run erase/delete on a device that is Booting or Shutting Down. + // Both are permanent, so wait for a settled state instead. + if device.state != "Booted" && device.state != "Shutdown" { + throw SimSlimError( + "simulator \(udid) is \(device.state); wait until it is Booted or Shutdown, then try again") + } + if device.state != "Booted" { return device.set } + try shutdown(set: device.set, udid: udid) + try waitShutdown(set: device.set, udid: udid) + return device.set + } + + public func renameDevice(udid: String, name: String) throws { + let device = try findDevice(udid: udid) + let clean = try normalizeSimulatorName(name) + _ = try xcrunChecked(simctlArgs(set: device.set, ["rename", udid, clean])) + } + + public func eraseDevice(udid: String) throws { + let set = try shutdownIfBooted(udid: udid) + _ = try xcrunChecked(simctlArgs(set: set, ["erase", udid])) + } + + public func deleteDevice(udid: String) throws { + let set = try shutdownIfBooted(udid: udid) + _ = try xcrunChecked(simctlArgs(set: set, ["delete", udid])) + } +} diff --git a/swift/Sources/SimSlimKit/Live.swift b/swift/Sources/SimSlimKit/Live.swift new file mode 100644 index 0000000..dfeadf0 --- /dev/null +++ b/swift/Sources/SimSlimKit/Live.swift @@ -0,0 +1,302 @@ +// Copyright (c) 2026 Pavel Akhrameev (Swift port). MIT License; see LICENSE. + +import Foundation + +// `enable` / `disable`: change categories or daemons on a booted simulator now, +// without a reboot, keeping no state of their own. The profile file given with +// --save is the only thing that persists. + +extension Simctl { + /// Re-enables categories (IDs from `simslim profiles`) and individual managed + /// daemons on a booted simulator: each disable override is lifted and each job + /// loaded into the running boot session. With `save`, the change is also + /// written to that profile file once the live change succeeded; a simulator + /// that is not booted only gets the file, and without `save` it is an error. + public func enableServices( + udid: String, ids: [String], save: String = "", reporter: Reporter? = nil + ) throws -> ServicesOutput { + let (categories, labels) = try resolveServiceIDs(ids) + if categories.count + labels.count == 0 { + throw SimSlimError( + "name at least one category ID or managed daemon to enable (see `simslim profiles`)") + } + try checkSave(save, categories: categories, labels: labels, enable: true) + let device = try serviceTarget(udid: udid, save: save) + var out = ServicesOutput(action: "enable", udid: device.udid, live: device.state == "Booted") + if out.live { + out.labels = Catalog.covered(categories: categories, labels: labels).sorted() + report(reporter, "Starting \(out.labels.count) background services without a reboot...") + do { + out.notStarted = try startServices(device: device, labels: out.labels, reporter: reporter) + } catch { + throw unsaved(error, save: save) + } + } + try saveServices(&out, save: save, categories: categories, labels: labels, enable: true) + return out + } + + /// The inverse: stops categories and daemons at once, each one booted out of + /// the running boot session with its disable override set. A daemon named on + /// its own is always stopped, unless the platform needs it. A daemon a named + /// category covers is also kept while another category that lists it is fully + /// enabled right now. Both are reported in `stillEnabled`. + public func disableServices( + udid: String, ids: [String], save: String = "", reporter: Reporter? = nil + ) throws -> ServicesOutput { + let (categories, labels) = try resolveServiceIDs(ids) + if categories.count + labels.count == 0 { + throw SimSlimError( + "name at least one category ID or managed daemon to disable (see `simslim profiles`)") + } + for label in labels where !Catalog.slimmableSet.contains(label) { + throw SimSlimError( + "\(label) is never disabled: simslim keeps it running for compatibility (see `simslim profiles`)" + ) + } + try checkSave(save, categories: categories, labels: labels, enable: false) + let device = try serviceTarget(udid: udid, save: save) + var out = ServicesOutput(action: "disable", udid: device.udid, live: device.state == "Booted") + if out.live { + do { + try stopNamed( + device: device, out: &out, categories: categories, labels: labels, reporter: reporter) + } catch { + throw unsaved(error, save: save) + } + } + try saveServices(&out, save: save, categories: categories, labels: labels, enable: false) + return out + } + + /// Stops what `disableServices` was told to on a booted simulator, filling + /// `out.labels` with what it stops and `out.stillEnabled` with what it keeps. + private func stopNamed( + device: Device, out: inout ServicesOutput, categories: [String], labels: [String], + reporter: Reporter? + ) throws { + let disabled = try readDisabled(set: device.set, udid: device.udid) + let covered = Catalog.covered(categories: categories, labels: labels) + let allowed = desiredForDevice(device, covered) + let kept = enabledNeighbours(disabling: categories, named: labels, disabled: disabled) + for label in covered.sorted() { + if allowed.contains(label) && Catalog.slimmableSet.contains(label) && !kept.contains(label) { + out.labels.append(label) + } else { + out.stillEnabled.append(label) + } + } + if out.labels.isEmpty { return } + report(reporter, "Stopping \(out.labels.count) background services without a reboot...") + try stopServices(device: device, labels: out.labels, reporter: reporter) + } + + /// The labels the disabling categories cover that another category, one not + /// being disabled and with every label enabled right now, also lists. Only the + /// live state says which features are on, so that decides: stopping the store + /// keeps the AMS daemons iCloud shares while iCloud is fully running. A label + /// named on its own is never kept. + func enabledNeighbours(disabling: [String], named: [String], disabled: Set) + -> Set + { + var covered = Catalog.covered(categories: disabling, labels: []) + covered.subtract(named) + var kept = Set() + for category in Catalog.categories where !disabling.contains(category.id) { + let enabled = category.labels.allSatisfy { !disabled.contains($0) } + let shares = category.labels.contains { covered.contains($0) } + if !enabled || !shares { continue } + for label in category.labels where covered.contains(label) { kept.insert(label) } + } + return kept + } + + // MARK: - --save + + /// Validates the profile file --save names before anything changes, so a bad + /// file fails the command up front. + private func checkSave(_ save: String, categories: [String], labels: [String], enable: Bool) + throws + { + if save.isEmpty { return } + _ = try updatedProfile(path: save, categories: categories, labels: labels, enable: enable) + } + + private func saveServices( + _ out: inout ServicesOutput, save: String, categories: [String], labels: [String], + enable: Bool + ) throws { + if save.isEmpty { return } + do { + try SimSlimKit.saveServices( + path: save, categories: categories, labels: labels, enable: enable) + } catch { + if out.live { + throw SimSlimError( + "the simulator was changed, but profile \(save) was not: \(error.localizedDescription)") + } + throw error + } + out.saved = save + } + + /// Notes on a failed live change that --save left the profile alone. + private func unsaved(_ error: Error, save: String) -> Error { + if save.isEmpty { return error } + return SimSlimError("\(error.localizedDescription) (profile \(save) not changed)") + } + + /// Resolves the exact simulator `enable` and `disable` act on, so a simctl + /// alias such as "all" can never fan out across devices. Only a booted + /// simulator can change live; with a profile to save, any simulator is fine. + private func serviceTarget(udid: String, save: String) throws -> Device { + let device = try findDevice(udid: udid) + if device.state != "Booted" && save.isEmpty { + throw SimSlimError( + "simulator \(device.udid) is not booted (it is \(device.state)): enable and disable change a running simulator only; pass --save to record the change, then apply it with `simslim on \(device.udid) --profile `" + ) + } + return device + } + + /// Sorts the IDs `enable` and `disable` accept into category IDs and + /// individual managed labels, rejecting anything else. + func resolveServiceIDs(_ ids: [String]) throws -> (categories: [String], labels: [String]) { + var categories: [String] = [] + var labels: [String] = [] + var seen = Set() + for id in ids { + if seen.contains(id) { continue } + if Catalog.category(id: id) != nil { + categories.append(id) + } else if Catalog.managedSet.contains(id) { + labels.append(id) + } else { + throw SimSlimError( + "unknown category or managed daemon \"\(id)\" (see `simslim profiles`)") + } + seen.insert(id) + } + return (categories.sorted(), labels.sorted()) + } + + // MARK: - Live transitions + + /// Lifts the disable override of each label and loads its job into the running + /// boot session. One `launchctl load -w` per chunk handles every label whose + /// job plist is found; what is still disabled afterwards gets a per-label + /// `enable`, and what is still not loaded a per-label bootstrap. A label with + /// no plist (an XPC service, for example) only needs its override lifted. + /// Labels launchd re-enabled but would not load in this boot session are + /// returned; they start at the next boot. A label left disabled is an error. + func startServices(device: Device, labels: [String], reporter: Reporter?) throws -> [String] { + let set = device.set + let udid = device.udid + var (disabled, loaded) = try serviceState(set: set, udid: udid) + let candidates = labels.filter { disabled.contains($0) || !loaded.contains($0) } + var plists: [String: String] = [:] + var haveRoot = false + if !device.runtimeID.isEmpty && !candidates.isEmpty, + let root = try? runtimeRoot(runtimeID: device.runtimeID) + { + plists = launchdJobPlists( + root: root, labels: candidates, plistLabel: { try self.readPlistLabel(path: $0) }) + haveRoot = true + } + // Without the RuntimeRoot nothing tells a missing plist from an unknown one, + // so every unloaded label counts as one launchd should load. + let loadable: (String) -> Bool = { plists[$0] != nil || !haveRoot } + let pending = candidates.filter { disabled.contains($0) || loadable($0) } + if pending.isEmpty { + report(reporter, " all \(labels.count) services were already running") + return [] + } + let paths = pending.compactMap { plists[$0] } + if !paths.isEmpty { + batchJobs(set: set, udid: udid, verb: "load", paths: paths) + (disabled, loaded) = try serviceState(set: set, udid: udid) + let left = stillToStart(pending, disabled: disabled, loaded: loaded, loadable: loadable) + report( + reporter, " \(pending.count - left.count)/\(pending.count) services started in one batch") + } + var toEnable: [String] = [] + var unloaded: [String: String] = [:] + for label in pending { + if disabled.contains(label) { toEnable.append(label) } + if let plist = plists[label], !loaded.contains(label) { unloaded[label] = plist } + } + if !toEnable.isEmpty { + try applyDelta( + set: set, udid: udid, toDisable: [], toEnable: toEnable, disableAction: .overrideOnly, + reporter: reporter) + } + if !unloaded.isEmpty { bootstrapJobs(set: set, udid: udid, plists: unloaded) } + if toEnable.count + unloaded.count > 0 { + (disabled, loaded) = try serviceState(set: set, udid: udid) + } + var still: [String] = [] + var notStarted: [String] = [] + for label in pending { + if disabled.contains(label) { + still.append(label) + } else if !loaded.contains(label) && loadable(label) { + notStarted.append(label) + } + } + if !still.isEmpty { + throw SimSlimError( + "\(still.count) of \(pending.count) services are still disabled: \(still.joined(separator: ", "))" + ) + } + return notStarted + } + + /// The labels that are still disabled, or still not loaded although launchd + /// could load them. + func stillToStart( + _ labels: [String], disabled: Set, loaded: Set, + loadable: (String) -> Bool + ) -> [String] { + labels.filter { disabled.contains($0) || (!loaded.contains($0) && loadable($0)) } + } + + /// One `launchctl bootstrap` per job, for the few the batch load left behind. + /// The exit status is not trusted (an already-loaded job exits 37); the + /// caller reads the state back. + func bootstrapJobs(set: String, udid: String, plists: [String: String]) { + for label in plists.keys.sorted() { + if deadlineExpired { return } + _ = try? exec( + .xcrun, + simctlArgs(set: set, ["spawn", udid, "launchctl", "bootstrap", "system", plists[label]!]), + timeout: spawnTimeout) + } + } + + /// The disable overrides and the loaded jobs, read together. + func serviceState(set: String, udid: String) throws -> ( + disabled: Set, loaded: Set + ) { + ( + try readDisabled(set: set, udid: udid), + try loadedLabels(set: set, udid: udid) + ) + } + + /// Disables each label and boots its job out of the running boot session: one + /// `launchctl unload -w` per chunk first, then a per-label disable and bootout + /// for whatever the batch missed. Every override is read back. + func stopServices(device: Device, labels: [String], reporter: Reporter?) throws { + let remaining = unloadInBatch( + set: device.set, udid: device.udid, runtimeID: device.runtimeID, labels: labels, + reporter: reporter) + try applyDelta( + set: device.set, udid: device.udid, toDisable: remaining, toEnable: [], + disableAction: .liveStop, reporter: reporter) + let after = try readDisabled(set: device.set, udid: device.udid) + let missing = labels.filter { !after.contains($0) }.count + if missing > 0 { + throw SimSlimError("\(missing) of \(labels.count) disable overrides did not take") + } + } +} diff --git a/swift/Sources/SimSlimKit/Measure.swift b/swift/Sources/SimSlimKit/Measure.swift new file mode 100644 index 0000000..bce9947 --- /dev/null +++ b/swift/Sources/SimSlimKit/Measure.swift @@ -0,0 +1,194 @@ +// Copyright (c) 2026 Pavel Akhrameev (Swift port). MIT License; see LICENSE. + +import Foundation + +/// A device's real memory cost. +public struct MemoryMeasurement: Codable, Equatable, Sendable { + public var processes: Int + /// Summed phys_footprint (compressed + dirty): the number that caps how many + /// simulators fit. + public var bytes: Int64 + /// Summed %cpu across the tree (ps's decaying average; can exceed 100). + public var cpu: Double + + public init(processes: Int, bytes: Int64, cpu: Double) { + self.processes = processes + self.bytes = bytes + self.cpu = cpu + } +} + +/// One `ps` sweep of every process: parent links, cpu, and name. +struct ProcessSnapshot: Equatable { + var children: [Int: [Int]] = [:] + var cpu: [Int: Double] = [:] + var comm: [Int: String] = [:] +} + +extension Simctl { + /// Sums the phys_footprint of every process in the device's launchd tree. + /// phys_footprint (the value Activity Monitor's "Memory" column reports) + /// counts compressed and swapped pages, so it stays accurate under memory + /// pressure where resident size would read misleadingly low. + public func measure(udid: String) throws -> MemoryMeasurement { + let root = try simLaunchdPID(udid: udid) + let snapshot = try processSnapshot() + let footprint = try footprintByPID() + return Simctl.measureTree(root: root, snapshot: snapshot, footprint: footprint) + } + + /// Takes one process and footprint snapshot for every requested simulator, so + /// the RAM column stays current without running the relatively expensive `top` + /// once per booted device. Returns measurements and per-UDID error messages. + public func measureMany(udids: [String]) -> ( + measurements: [String: MemoryMeasurement], errors: [String: String] + ) { + var measurements: [String: MemoryMeasurement] = [:] + var errors: [String: String] = [:] + var roots: [String: Int] = [:] + for udid in udids { + do { + roots[udid] = try simLaunchdPID(udid: udid) + } catch { + errors[udid] = error.localizedDescription + } + } + if roots.isEmpty { return (measurements, errors) } + + do { + let snapshot = try processSnapshot() + let footprint = try footprintByPID() + for (udid, root) in roots { + measurements[udid] = Simctl.measureTree( + root: root, snapshot: snapshot, footprint: footprint) + } + } catch { + for udid in roots.keys { errors[udid] = error.localizedDescription } + } + return (measurements, errors) + } + + func simLaunchdPID(udid: String) throws -> Int { + let notBooted = SimSlimError("simulator \(udid) does not appear to be booted") + let result: CommandResult + do { + result = try runner.run(.pgrep, ["-f", udid + "/data/var/run/launchd_bootstrap"]) + } catch { + throw notBooted + } + guard result.succeeded, + let first = result.stdoutText.split(whereSeparator: \.isWhitespace).first + else { throw notBooted } + guard let pid = Int(first) else { + throw SimSlimError("unexpected pgrep output: \(first)") + } + return pid + } + + func processSnapshot() throws -> ProcessSnapshot { + // comm is the full executable path (untruncated, unlike ucomm); the basename + // is what the drill-down shows (backboardd, SpringBoard, ...). + let result = try runner.run(.ps, ["-axo", "pid,ppid,%cpu,comm"]) + guard result.succeeded else { + throw SimSlimError("ps: exit status \(result.status): \(result.combinedText)") + } + return Simctl.parsePS(result.stdoutText) + } + + func footprintByPID() throws -> [Int: Int64] { + let result = try runner.run(.top, ["-l", "1", "-stats", "pid,mem"]) + guard result.succeeded else { + throw SimSlimError("top: exit status \(result.status): \(result.combinedText)") + } + return Simctl.parseTopMemory(result.stdoutText) + } + + static func measureTree( + root: Int, snapshot: ProcessSnapshot, footprint: [Int: Int64] + ) -> MemoryMeasurement { + var measurement = MemoryMeasurement(processes: 0, bytes: 0, cpu: 0) + for pid in treePIDs(root: root, children: snapshot.children) { + measurement.processes += 1 + measurement.bytes += footprint[pid] ?? 0 + measurement.cpu += snapshot.cpu[pid] ?? 0 + } + return measurement + } + + /// Every pid reachable from `root` through the child map. + static func treePIDs(root: Int, children: [Int: [Int]]) -> Set { + var seen = Set() + var stack = [root] + while let pid = stack.popLast() { + if !seen.insert(pid).inserted { continue } + stack.append(contentsOf: children[pid] ?? []) + } + return seen + } + + static func parsePS(_ output: String) -> ProcessSnapshot { + var snapshot = ProcessSnapshot() + for line in output.split(whereSeparator: \.isNewline) { + let fields = line.split(whereSeparator: \.isWhitespace) + if fields.count < 4 { continue } + guard let pid = Int(fields[0]), let ppid = Int(fields[1]) else { continue } + snapshot.children[ppid, default: []].append(pid) + if let cpu = Double(fields[2]) { snapshot.cpu[pid] = cpu } + // Joining defends against spaces in the executable path. + snapshot.comm[pid] = commName(fields[3...].joined(separator: " ")) + } + return snapshot + } + + /// Reduces a full executable path to its basename. + static func commName(_ path: String) -> String { + guard let slash = path.lastIndex(of: "/") else { return path } + return String(path[path.index(after: slash)...]) + } + + /// Parses `top -l 1 -stats pid,mem` lines: a pid, then a size such as `45M` + /// or `1234K+`. Anything else (headers, the summary block) is skipped. + static func parseTopMemory(_ output: String) -> [Int: Int64] { + var memory: [Int: Int64] = [:] + for line in output.split(whereSeparator: \.isNewline) { + let fields = line.split(whereSeparator: \.isWhitespace) + guard fields.count >= 2, fields[0].allSatisfy(\.isASCIIDigit), let pid = Int(fields[0]) else { + continue + } + // The size must start with a digit or '.', like the Go regex's [0-9.]+. + guard let first = fields[1].first, first.isASCIIDigit || first == "." else { continue } + memory[pid] = parseBytes(String(fields[1])) + } + return memory + } + + /// Parses sizes such as `45M`, `1.5G`, `900K+` or `12B`; the suffix is + /// optional. Unparseable input is 0. + static func parseBytes(_ text: String) -> Int64 { + var s = text.trimmingCharacters(in: .whitespaces) + if s.hasSuffix("+") { s.removeLast() } + if s.hasSuffix("-") { s.removeLast() } + if s.isEmpty { return 0 } + var multiplier: Double = 1 + switch s.last { + case "K": + multiplier = 1_024 + s.removeLast() + case "M": + multiplier = 1_048_576 + s.removeLast() + case "G": + multiplier = 1_073_741_824 + s.removeLast() + case "B": s.removeLast() + default: break + } + guard let value = Double(s) else { return 0 } + // Int64(_:) traps on overflow and NaN; an unparseable size is 0. + return Int64(exactly: (value * multiplier).rounded(.towardZero)) ?? 0 + } +} + +extension Character { + fileprivate var isASCIIDigit: Bool { self >= "0" && self <= "9" } +} diff --git a/swift/Sources/SimSlimKit/Output.swift b/swift/Sources/SimSlimKit/Output.swift new file mode 100644 index 0000000..ef0b927 --- /dev/null +++ b/swift/Sources/SimSlimKit/Output.swift @@ -0,0 +1,166 @@ +// Copyright (c) 2026 Pavel Akhrameev (Swift port). MIT License; see LICENSE. + +import Foundation + +/// The stable, machine-readable shapes the macOS app and other integrations +/// decode. Changing a field breaks `gui/*.swift`; keep them in sync. + +/// A device plus its slim status and memory. The device fields are flattened +/// into the same JSON object, as in the Go output. +public struct DeviceSummary: Codable, Equatable, Sendable { + public var device: Device + public var managedDisabled: Int? // omitted for shutdown simulators + public var managedTotal: Int + public var statusError: String + public var memory: MemoryMeasurement? + public var memoryError: String + + public init( + device: Device, managedDisabled: Int? = nil, managedTotal: Int, statusError: String = "", + memory: MemoryMeasurement? = nil, memoryError: String = "" + ) { + self.device = device + self.managedDisabled = managedDisabled + self.managedTotal = managedTotal + self.statusError = statusError + self.memory = memory + self.memoryError = memoryError + } + + private enum ExtraKeys: String, CodingKey { + case managedDisabled, managedTotal, statusError, memory, memoryError + } + + public func encode(to encoder: Encoder) throws { + try device.encode(to: encoder) // flatten the device's keys into this object + var c = encoder.container(keyedBy: ExtraKeys.self) + try c.encodeIfPresent(managedDisabled, forKey: .managedDisabled) + try c.encode(managedTotal, forKey: .managedTotal) + if !statusError.isEmpty { try c.encode(statusError, forKey: .statusError) } // Go omitempty + try c.encodeIfPresent(memory, forKey: .memory) + if !memoryError.isEmpty { try c.encode(memoryError, forKey: .memoryError) } + } + + public init(from decoder: Decoder) throws { + device = try Device(from: decoder) + let c = try decoder.container(keyedBy: ExtraKeys.self) + managedDisabled = try c.decodeIfPresent(Int.self, forKey: .managedDisabled) + managedTotal = try c.decode(Int.self, forKey: .managedTotal) + statusError = try c.decodeIfPresent(String.self, forKey: .statusError) ?? "" + memory = try c.decodeIfPresent(MemoryMeasurement.self, forKey: .memory) + memoryError = try c.decodeIfPresent(String.self, forKey: .memoryError) ?? "" + } +} + +/// `simslim status --json`: the status fields flattened, plus the verdict and, +/// only with `--dropped`, the disabled daemons grouped by category. +public struct StatusOutput: Codable, Equatable, Sendable { + public var status: Status + public var verdict: String + public var dropped: [DroppedCategory] + + public init(status: Status, verdict: String, dropped: [DroppedCategory] = []) { + self.status = status + self.verdict = verdict + self.dropped = dropped + } + + private enum ExtraKeys: String, CodingKey { case verdict, dropped } + + public func encode(to encoder: Encoder) throws { + try status.encode(to: encoder) + var c = encoder.container(keyedBy: ExtraKeys.self) + try c.encode(verdict, forKey: .verdict) + if !dropped.isEmpty { try c.encode(dropped, forKey: .dropped) } // Go omitempty + } + + public init(from decoder: Decoder) throws { + status = try Status(from: decoder) + let c = try decoder.container(keyedBy: ExtraKeys.self) + verdict = try c.decode(String.self, forKey: .verdict) + dropped = try c.decodeIfPresent([DroppedCategory].self, forKey: .dropped) ?? [] + } +} + +/// The result of a simulator lifecycle command (`boot`, `shutdown`, ...). +public struct SimulatorMutationOutput: Codable, Equatable, Sendable { + public var action: String + public var udid: String + public var name: String + public var sourceUdid: String + + public init(action: String, udid: String, name: String = "", sourceUdid: String = "") { + self.action = action + self.udid = udid + self.name = name + self.sourceUdid = sourceUdid + } + + private enum CodingKeys: String, CodingKey { case action, udid, name, sourceUdid } + + public func encode(to encoder: Encoder) throws { + var c = encoder.container(keyedBy: CodingKeys.self) + try c.encode(action, forKey: .action) + try c.encode(udid, forKey: .udid) + if !name.isEmpty { try c.encode(name, forKey: .name) } // Go omitempty + if !sourceUdid.isEmpty { try c.encode(sourceUdid, forKey: .sourceUdid) } + } + + public init(from decoder: Decoder) throws { + let c = try decoder.container(keyedBy: CodingKeys.self) + action = try c.decode(String.self, forKey: .action) + udid = try c.decode(String.self, forKey: .udid) + name = try c.decodeIfPresent(String.self, forKey: .name) ?? "" + sourceUdid = try c.decodeIfPresent(String.self, forKey: .sourceUdid) ?? "" + } +} + +/// The result of `enable` and `disable`. +public struct ServicesOutput: Codable, Equatable, Sendable { + public var action: String // "enable" or "disable" + public var udid: String + public var live: Bool // false: the simulator is not booted, only the profile was saved + public var labels: [String] // daemons enabled, or stopped by disable + public var notStarted: [String] // enable: re-enabled, but launchd starts them at the next boot + public var stillEnabled: [String] // disable: kept running for another category or the platform + public var saved: String // the profile file --save created or updated + + public init( + action: String, udid: String, live: Bool, labels: [String] = [], notStarted: [String] = [], + stillEnabled: [String] = [], saved: String = "" + ) { + self.action = action + self.udid = udid + self.live = live + self.labels = labels + self.notStarted = notStarted + self.stillEnabled = stillEnabled + self.saved = saved + } + + private enum CodingKeys: String, CodingKey { + case action, udid, live, labels, notStarted, stillEnabled, saved + } + + public func encode(to encoder: Encoder) throws { + var c = encoder.container(keyedBy: CodingKeys.self) + try c.encode(action, forKey: .action) + try c.encode(udid, forKey: .udid) + try c.encode(live, forKey: .live) + try c.encode(labels, forKey: .labels) // always present, `[]` when empty + if !notStarted.isEmpty { try c.encode(notStarted, forKey: .notStarted) } // Go omitempty + if !stillEnabled.isEmpty { try c.encode(stillEnabled, forKey: .stillEnabled) } + if !saved.isEmpty { try c.encode(saved, forKey: .saved) } + } + + public init(from decoder: Decoder) throws { + let c = try decoder.container(keyedBy: CodingKeys.self) + action = try c.decode(String.self, forKey: .action) + udid = try c.decode(String.self, forKey: .udid) + live = try c.decode(Bool.self, forKey: .live) + labels = try c.decode([String].self, forKey: .labels) + notStarted = try c.decodeIfPresent([String].self, forKey: .notStarted) ?? [] + stillEnabled = try c.decodeIfPresent([String].self, forKey: .stillEnabled) ?? [] + saved = try c.decodeIfPresent(String.self, forKey: .saved) ?? "" + } +} diff --git a/swift/Sources/SimSlimKit/Profile.swift b/swift/Sources/SimSlimKit/Profile.swift new file mode 100644 index 0000000..34b781d --- /dev/null +++ b/swift/Sources/SimSlimKit/Profile.swift @@ -0,0 +1,56 @@ +// Copyright (c) 2026 Pavel Akhrameev (Swift port). MIT License; see LICENSE. + +import Foundation + +/// Selects which managed daemons a slim boot should disable. +public struct Profile: Equatable, Sendable { + public var exceptCategories: Set // category IDs to leave fully enabled + public var keep: Set // individual labels to leave enabled + + public init(exceptCategories: Set = [], keep: Set = []) { + self.exceptCategories = exceptCategories + self.keep = keep + } + + /// The labels this profile wants disabled. Categories may share labels, so a + /// label stays enabled when any excepted category lists it. + public func desired() -> Set { + var set = Catalog.slimmableSet + for category in Catalog.categories where exceptCategories.contains(category.id) { + set.subtract(category.labels) + } + set.subtract(keep) + return set + } + + /// Applies platform-specific service requirements. `desired()` remains the + /// platform-independent catalog for profile editors. + public func desired(for device: Device) -> Set { + desiredForDevice(device, desired()) + } +} + +func desiredForDevice(_ device: Device, _ desired: Set) -> Set { + desired.filter { label in + // watchOS re-enables homed after startup, even when launchd initially + // honours the override. Keep it enabled rather than report a full slim + // that drifts as soon as the Watch finishes starting up. + if device.platformName == "watchOS" && label == "com.apple.homed" { return false } + // visionOS serves the simulated surroundings as mobile assets. Without + // mobileassetd the device boots into a black space. + if device.platformName == "visionOS" && label == "com.apple.mobileassetd" { return false } + return true + } +} + +/// The launchctl transitions that move `current` to `desired`, scoped to +/// `managed`. Labels outside `managed` are never touched: an unmanaged desired +/// label is ignored, and an unmanaged label that is already disabled stays +/// disabled. Empty results mean the device is already correct. +public func delta( + current: Set, desired: Set, managed: Set +) -> (toDisable: [String], toEnable: [String]) { + let toDisable = desired.filter { managed.contains($0) && !current.contains($0) } + let toEnable = current.filter { managed.contains($0) && !desired.contains($0) } + return (toDisable.sorted(), toEnable.sorted()) +} diff --git a/swift/Sources/SimSlimKit/ProfileFile.swift b/swift/Sources/SimSlimKit/ProfileFile.swift new file mode 100644 index 0000000..0191725 --- /dev/null +++ b/swift/Sources/SimSlimKit/ProfileFile.swift @@ -0,0 +1,232 @@ +// Copyright (c) 2026 Pavel Akhrameev (Swift port). MIT License; see LICENSE. + +import Foundation + +/// The on-disk profile applied with `simslim on --profile `. `except` and +/// `keep` mirror the `--except` and `--keep` flags. +public struct SlimProfile: Equatable, Sendable { + public var name: String + public var description: String + public var except: [String] + public var keep: [String] + + public init( + name: String = "", description: String = "", except: [String] = [], keep: [String] = [] + ) { + self.name = name + self.description = description + self.except = except + self.keep = keep + } + + /// Turns a parsed SlimProfile into the validated Profile it selects. + func resolve(path: String) throws -> Profile { + var profile = Profile() + for raw in except { + let id = raw.trimmingCharacters(in: .whitespacesAndNewlines) + if id.isEmpty { continue } + guard Catalog.category(id: id) != nil else { + throw SimSlimError( + "profile \(path): unknown category \"\(id)\" (see `simslim profiles`)") + } + profile.exceptCategories.insert(id) + } + // Accept keep entries for required services too: profiles written as + // workarounds before a service became always-enabled must remain valid. + for raw in keep { + let label = raw.trimmingCharacters(in: .whitespacesAndNewlines) + if label.isEmpty { continue } + guard Catalog.managedSet.contains(label) else { + throw SimSlimError( + "profile \(path): \"\(label)\" is not a managed daemon (see `simslim profiles`)") + } + profile.keep.insert(label) + } + return profile + } +} + +/// Reads a profile file and resolves it to a validated Profile. +/// +/// Like the Go version it rejects unknown fields and matches field names +/// case-insensitively. Unlike it, a malformed document with trailing text after +/// the first JSON value is rejected rather than ignored. Foundation's parser also +/// accepts what Go's rejects (trailing commas, a UTF-8 byte-order mark) and keeps +/// the first of two identical keys where Go keeps the last; a file that relies on +/// any of these reads differently here. +public func loadSlimProfile(path: String) throws -> Profile { + let data: Data + do { + data = try Data(contentsOf: URL(fileURLWithPath: path)) + } catch { + throw SimSlimError("read profile \(path): \(readFailureReason(error))") + } + return try parseSlimProfile(data, path: path).resolve(path: path) +} + +func parseSlimProfile(_ data: Data, path: String) throws -> SlimProfile { + let trimmed = String(decoding: data, as: UTF8.self) + .trimmingCharacters(in: .whitespacesAndNewlines) + if trimmed.isEmpty { + throw SimSlimError("profile \(path) is empty; write {} for the default profile") + } + + let parsed: Any + do { + parsed = try JSONSerialization.jsonObject(with: data, options: [.fragmentsAllowed]) + } catch { + throw SimSlimError("parse profile \(path): \(error.localizedDescription)") + } + + // JSON null decodes to the zero value, as in Go. + if parsed is NSNull { return SlimProfile() } + guard let object = parsed as? [String: Any] else { + throw SimSlimError("parse profile \(path): the top level must be a JSON object") + } + + var profile = SlimProfile() + for (key, value) in object { + switch key.lowercased() { + case "name": profile.name = try stringValue(value, field: "name", path: path) + case "description": + profile.description = try stringValue(value, field: "description", path: path) + case "except": profile.except = try stringList(value, field: "except", path: path) + case "keep": profile.keep = try stringList(value, field: "keep", path: path) + default: throw SimSlimError("parse profile \(path): unknown field \"\(key)\"") + } + } + return profile +} + +private func stringValue(_ value: Any, field: String, path: String) throws -> String { + if value is NSNull { return "" } + guard let string = value as? String else { + throw SimSlimError("parse profile \(path): field \"\(field)\" must be a string") + } + return string +} + +private func stringList(_ value: Any, field: String, path: String) throws -> [String] { + if value is NSNull { return [] } + guard let array = value as? [Any] else { + throw SimSlimError("parse profile \(path): field \"\(field)\" must be an array of strings") + } + return try array.map { element in + if element is NSNull { return "" } + guard let string = element as? String else { + throw SimSlimError("parse profile \(path): field \"\(field)\" must be an array of strings") + } + return string + } +} + +private func readFailureReason(_ error: Error) -> String { + let ns = error as NSError + if let posix = ns.userInfo[NSUnderlyingErrorKey] as? NSError, posix.domain == NSPOSIXErrorDomain { + return String(cString: strerror(Int32(posix.code))).lowercased() + } + return ns.localizedDescription +} + +/// Parses the comma-separated list syntax shared by the `--except`, `--keep`, +/// `--requires` and `--categories` flags, dropping blank entries. +public func splitList(_ text: String) -> [String] { + text.split(separator: ",", omittingEmptySubsequences: false) + .map { $0.trimmingCharacters(in: .whitespacesAndNewlines) } + .filter { !$0.isEmpty } +} + +/// Selects the slim profile for an `on` invocation. A `--profile` file is the +/// single source of truth, so it cannot be combined with `--except`/`--keep`. +public func buildProfile(profilePath: String, except: String, keep: String) throws -> Profile { + if !profilePath.isEmpty { + if !except.isEmpty || !keep.isEmpty { + throw SimSlimError("--profile cannot be combined with --except or --keep") + } + return try loadSlimProfile(path: profilePath) + } + var profile = Profile() + for id in splitList(except) { + guard Catalog.category(id: id) != nil else { + throw SimSlimError("unknown category \"\(id)\" (see `simslim profiles`)") + } + profile.exceptCategories.insert(id) + } + for label in splitList(keep) { + profile.keep.insert(label) + } + return profile +} + +/// Renders a profile as indented JSON with a trailing newline, in the same +/// field order and escaping as the Go encoder (so files round-trip between the +/// two tools without churn): name, description, except, keep; empty fields are +/// omitted; `<`, `>`, `&`, U+2028 and U+2029 are escaped. +public func marshalProfile(_ profile: SlimProfile) -> Data { + var fields: [String] = [] + if !profile.name.isEmpty { fields.append(" \"name\": \(goJSONString(profile.name))") } + if !profile.description.isEmpty { + fields.append(" \"description\": \(goJSONString(profile.description))") + } + if !profile.except.isEmpty { fields.append(jsonList("except", profile.except)) } + if !profile.keep.isEmpty { fields.append(jsonList("keep", profile.keep)) } + + let body = fields.isEmpty ? "{}" : "{\n" + fields.joined(separator: ",\n") + "\n}" + return Data((body + "\n").utf8) +} + +private func jsonList(_ key: String, _ items: [String]) -> String { + let rendered = items.map { " \(goJSONString($0))" }.joined(separator: ",\n") + return " \"\(key)\": [\n\(rendered)\n ]" +} + +private func goJSONString(_ value: String) -> String { + var out = "\"" + for scalar in value.unicodeScalars { + switch scalar { + case "\"": out += "\\\"" + case "\\": out += "\\\\" + case "\n": out += "\\n" + case "\r": out += "\\r" + case "\t": out += "\\t" + case "\u{08}": out += "\\b" + case "\u{0C}": out += "\\f" + case "<": out += "\\u003c" + case ">": out += "\\u003e" + case "&": out += "\\u0026" + case "\u{2028}": out += "\\u2028" + case "\u{2029}": out += "\\u2029" + default: + if scalar.value < 0x20 { + out += String(format: "\\u%04x", scalar.value) + } else { + out.unicodeScalars.append(scalar) + } + } + } + return out + "\"" +} + +/// Derives a JSON filename from a profile name, for when the command targets a +/// directory. Runs of characters that are not filename-safe collapse to a +/// hyphen; an empty name falls back to `profile.json`. +public func profileFileName(_ name: String) -> String { + var slug = "" + var previousDash = false + for scalar in name.trimmingCharacters(in: .whitespacesAndNewlines).lowercased().unicodeScalars { + switch scalar { + case "a"..."z", "0"..."9", "_", ".": + slug.unicodeScalars.append(scalar) + previousDash = false + default: + if !previousDash { + slug += "-" + previousDash = true + } + } + } + slug = slug.trimmingCharacters(in: CharacterSet(charactersIn: "-.")) + if slug.isEmpty { return "profile.json" } + if slug.hasSuffix(".json") { return slug } + return slug + ".json" +} diff --git a/swift/Sources/SimSlimKit/ProfileSave.swift b/swift/Sources/SimSlimKit/ProfileSave.swift new file mode 100644 index 0000000..814acba --- /dev/null +++ b/swift/Sources/SimSlimKit/ProfileSave.swift @@ -0,0 +1,133 @@ +// Copyright (c) 2026 Pavel Akhrameev (Swift port). MIT License; see LICENSE. + +import Foundation + +// `enable --save` / `disable --save`: record the change in a profile file, the one +// place that describes a slim simulator, so `on`, `watch` and `verify` with that +// profile agree with it. + +extension Catalog { + /// Every managed label the categories and labels name. + static func covered(categories ids: [String], labels: [String]) -> Set { + var covered = Set() + for id in ids { + if let category = category(id: id) { covered.formUnion(category.labels) } + } + for label in labels where managedSet.contains(label) { covered.insert(label) } + return covered + } +} + +/// Reads and validates a profile file, keeping its entries as written. A missing +/// file is the default profile. +func readSlimProfile(path: String) throws -> (profile: SlimProfile, exists: Bool) { + var info = stat() + if stat(path, &info) != 0 { + // Only a missing file starts from the default profile; a loop or a + // not-a-directory component is an error, never a reason to overwrite. + if errno == ENOENT { return (SlimProfile(), false) } + throw SimSlimError("read profile \(path): \(String(cString: strerror(errno)))") + } + let data: Data + do { + data = try Data(contentsOf: URL(fileURLWithPath: path)) + } catch { + throw SimSlimError("read profile \(path): \(error.localizedDescription)") + } + let profile = try parseSlimProfile(data, path: path) + _ = try profile.resolve(path: path) + return (profile, true) +} + +/// The profile at `path` with the change applied, and whether anything changed. +/// Writes nothing. Enabling adds each category to `except` and each daemon to +/// `keep`, unless an excepted category already keeps it; disabling removes them. +func updatedProfile(path: String, categories: [String], labels: [String], enable: Bool) throws + -> (data: Data?, changed: Bool) +{ + var (profile, exists) = try readSlimProfile(path: path) + // Entries are compared as `resolve` reads them: trimmed, blanks ignored. A + // padded " search " is the category `search`, so it must be found, not added + // again or left behind. + func normalised(_ items: [String]) -> [String] { + items.map { $0.trimmingCharacters(in: .whitespacesAndNewlines) }.filter { !$0.isEmpty } + } + profile.except = normalised(profile.except) + profile.keep = normalised(profile.keep) + let beforeExcept = profile.except + let beforeKeep = profile.keep + if enable { + for id in categories where !profile.except.contains(id) { profile.except.append(id) } + let excepted = Catalog.covered(categories: profile.except, labels: []) + for label in labels where !excepted.contains(label) && !profile.keep.contains(label) { + profile.keep.append(label) + } + } else { + profile.except.removeAll { categories.contains($0) } + profile.keep.removeAll { labels.contains($0) } + // Removing a daemon from `keep` is not enough while a category the profile + // still excepts lists it. + for label in labels { + for id in profile.except where Catalog.covered(categories: [id], labels: []).contains(label) { + throw SimSlimError( + "profile \(path) keeps \(label) enabled through category \"\(id)\"; disable that category instead, or edit the file" + ) + } + } + } + if exists && beforeExcept == profile.except && beforeKeep == profile.keep { return (nil, false) } + return (marshalProfile(profile), true) +} + +/// Records an `enable` or `disable` in a profile file. An unchanged profile is +/// not rewritten; a changed one is replaced atomically. +public func saveServices(path: String, categories: [String], labels: [String], enable: Bool) throws +{ + let (data, changed) = try updatedProfile( + path: path, categories: categories, labels: labels, enable: enable) + guard changed, let data else { return } + try writeFileAtomic(path: path, data: data) +} + +/// Replaces `path` through a temporary file in the same directory, so a +/// concurrent reader sees the old file or the new one, never half of it. A +/// symlink is followed, and an existing file keeps its mode. +func writeFileAtomic(path original: String, data: Data) throws { + var path = original + var mode = 0o644 + // Absolute against the working directory: a bare file name that is itself a + // symlink must be followed too. + let resolved = URL(fileURLWithPath: original).resolvingSymlinksInPath().path + if FileManager.default.fileExists(atPath: resolved) { + path = resolved + if let attrs = try? FileManager.default.attributesOfItem(atPath: path), + let perm = attrs[.posixPermissions] as? Int + { + mode = perm & 0o777 + } + } + let dir = (path as NSString).deletingLastPathComponent + let base = (path as NSString).lastPathComponent + let temp = ((dir.isEmpty ? "." : dir) as NSString).appendingPathComponent( + ".\(base).\(UUID().uuidString)") + defer { try? FileManager.default.removeItem(atPath: temp) } + do { + // Created private, so a 0600 profile is never briefly world-readable. + guard + FileManager.default.createFile( + atPath: temp, contents: nil, attributes: [.posixPermissions: 0o600]) + else { + throw SimSlimError("cannot create \(temp)") + } + let handle = try FileHandle(forWritingTo: URL(fileURLWithPath: temp)) + defer { try? handle.close() } + try handle.write(contentsOf: data) + try handle.synchronize() + try FileManager.default.setAttributes([.posixPermissions: mode], ofItemAtPath: temp) + } catch { + throw SimSlimError("write profile \(path): \(error.localizedDescription)") + } + guard rename(temp, path) == 0 else { + throw SimSlimError("write profile \(path): \(String(cString: strerror(errno)))") + } +} diff --git a/swift/Sources/SimSlimKit/Simctl.swift b/swift/Sources/SimSlimKit/Simctl.swift new file mode 100644 index 0000000..9cc2766 --- /dev/null +++ b/swift/Sources/SimSlimKit/Simctl.swift @@ -0,0 +1,277 @@ +// Copyright (c) 2026 Pavel Akhrameev (Swift port). MIT License; see LICENSE. + +import Foundation + +/// A CoreSimulator device set: the default one, Xcode's `testing` set, or a +/// custom path named with `--set`. +public struct DeviceSet: Equatable, Sendable { + /// "" for the default set; otherwise passed to `simctl --set`. + public let token: String + public let name: String +} + +/// The only place that shells out to `xcrun simctl`. +public struct Simctl: Sendable { + public var runner: CommandRunning + /// Sets named with `--set`, beyond the always-scanned default and `testing`. + public private(set) var extraSets: [String] = [] + /// Bounds one `simctl spawn launchctl` call. A first boot can saturate the + /// simulator, so a single spawn can stall for minutes; a per-spawn bound turns + /// that into a retryable failure instead of an unbounded wait. + public var spawnTimeout: TimeInterval = 120 + /// Pauses between attempts to read a simulator's launchd state. Right after a + /// boot, and while a reboot tears the old session down, launchd_sim refuses + /// spawns for a few seconds (error 124, "Domain is tearing down"). + public var retryDelays: [TimeInterval] = [1, 2, 4, 8] + public var sleep: @Sendable (TimeInterval) -> Void = { Thread.sleep(forTimeInterval: $0) } + /// Where launchd_sim keeps each device's disable overrides (a test redirects it). + public var storeRoot = "/private/var/tmp" + /// An overall bound for the operation in progress, standing in for Go's context + /// deadline: every command is capped to what is left of it, and nothing starts + /// once it has passed. + public var deadline: Date? + /// Asked before every command and wait: true once the operation was cancelled + /// (a watched device shut down, or the user pressed Ctrl-C). A command already + /// running finishes or times out; nothing new starts. + public var cancelled: (@Sendable () -> Bool)? + /// The clock the deadline is read from (a test replaces it). + public var now: @Sendable () -> Date = { Date() } + + public init(runner: CommandRunning = SystemCommandRunner()) { + self.runner = runner + } + + // MARK: - Running commands + + /// Sleeps, but never past the deadline, so an expired operation wakes at once. + func pause(_ seconds: TimeInterval) { + var length = seconds + if let deadline { length = min(length, max(0, deadline.timeIntervalSince(now()))) } + sleep(length) + } + + /// True once the operation is over, by deadline or by cancellation. + var deadlineExpired: Bool { + cancelled?() == true || (deadline.map { now() >= $0 } ?? false) + } + + /// What Go's context reports for the reason the operation is over. + var contextError: String { + cancelled?() == true ? "context canceled" : "context deadline exceeded" + } + + /// Runs a command under the operation deadline. The per-call `timeout` is + /// capped to what is left of the deadline; a command killed by the deadline + /// (rather than by its own `timeout`) is an error. + func exec(_ executable: Executable, _ arguments: [String], timeout: TimeInterval? = nil) throws + -> CommandResult + { + var limit = timeout + if cancelled?() == true { throw SimSlimError("context canceled") } + if let deadline { + let left = deadline.timeIntervalSince(now()) + if left <= 0 { throw SimSlimError("context deadline exceeded") } + limit = min(limit ?? left, left) + } + let result = try runner.run(executable, arguments, timeout: limit) + if result.timedOut, deadlineExpired { throw SimSlimError(contextError) } + return result + } + + // MARK: - Device sets + + public var knownSets: [DeviceSet] { + [DeviceSet(token: "", name: "default"), DeviceSet(token: "testing", name: "testing")] + + extraSets.map { DeviceSet(token: $0, name: $0) } + } + + /// Adds a `--set` value to the scanned sets, ignoring one that duplicates a + /// known token. + public mutating func registerDeviceSet(_ value: String) { + if knownSets.contains(where: { $0.token == value }) { return } + extraSets.append(value) + } + + func token(forSet name: String) -> String { + knownSets.first { $0.name == name }?.token ?? "" + } + + /// `--set` must precede the subcommand. + func simctlArgs(set name: String, _ sub: [String]) -> [String] { + Simctl.simctlArgs(token: token(forSet: name), sub) + } + + static func simctlArgs(token: String, _ sub: [String]) -> [String] { + token.isEmpty ? ["simctl"] + sub : ["simctl", "--set", token] + sub + } + + // MARK: - Listing + + private struct ListOutput: Decodable { + struct Entry: Decodable { + var udid: String? + var name: String? + var state: String? + var isAvailable: Bool? + var dataPath: String? + } + var devices: [String: [Entry]] + } + + func listDevices(in set: DeviceSet) throws -> [Device] { + let args = Simctl.simctlArgs(token: set.token, ["list", "devices", "-j"]) + let result: CommandResult + do { + result = try exec(.xcrun, args) + } catch { + throw SimSlimError("simctl list: \(error.localizedDescription)") + } + guard result.succeeded else { + throw Simctl.listError(status: result.status, stderr: result.stderrText) + } + let parsed: ListOutput + do { + parsed = try JSONDecoder().decode(ListOutput.self, from: result.stdout) + } catch { + throw SimSlimError("parse simctl list: \(error.localizedDescription)") + } + + var devices: [Device] = [] + for runtime in parsed.devices.keys.sorted() { + guard let (platform, version) = Simctl.parseRuntime(runtime) else { continue } + for entry in parsed.devices[runtime] ?? [] { + // Like the Go tool, an entry without isAvailable is treated as unavailable. + guard entry.isAvailable == true, let udid = entry.udid else { continue } + devices.append( + Device( + udid: udid, name: entry.name ?? "", state: entry.state ?? "", platform: platform, + osVersion: version, set: set.name, dataPath: entry.dataPath ?? "", runtimeID: runtime)) + } + } + return devices + } + + /// Surfaces xcrun's stderr, and when xcrun cannot find simctl at all (xcode-select + /// pointing at the Command Line Tools) says how to select a full Xcode. + static func listError(status: Int32, stderr: String) -> SimSlimError { + let base = "simctl list: exit status \(status)" + let text = stderr.trimmingCharacters(in: .whitespacesAndNewlines) + if text.isEmpty { return SimSlimError(base) } + if text.contains("unable to find utility \"simctl\"") { + return SimSlimError( + "\(base): \(text) (simctl ships with full Xcode, not the Command Line Tools; " + + "select one with `sudo xcode-select -s /Applications/Xcode.app`)") + } + return SimSlimError("\(base): \(text)") + } + + /// Lists every available simulator. The default set is mandatory; a secondary + /// set that cannot be listed (for example, one that does not exist) is skipped. + public func listDevices() throws -> [Device] { + var devices: [Device] = [] + for set in knownSets { + do { + devices += try listDevices(in: set) + } catch { + if set.token.isEmpty { throw error } + } + } + return devices + } + + /// Accepts only the simulator platforms supported by slimming. + static func parseRuntime(_ runtime: String) -> (platform: String, version: String)? { + let prefix = "com.apple.CoreSimulator.SimRuntime." + guard runtime.hasPrefix(prefix) else { return nil } + let name = runtime.dropFirst(prefix.count) + guard let dash = name.firstIndex(of: "-") else { return nil } + let platform = String(name[.. Device { + for candidate in knownSets { + if !set.isEmpty && candidate.name != set { continue } + let found: [Device] + do { + found = try listDevices(in: candidate) + } catch { + if candidate.token.isEmpty { throw error } + continue + } + if let device = found.first(where: { $0.udid == udid }) { return device } + } + throw SimSlimError("no simulator with udid \(udid)") + } + + // MARK: - launchd inside a simulator + + /// The labels currently disabled in the device's system domain. A label absent + /// from the output is enabled. + public func readDisabled(set: String, udid: String) throws -> Set { + let output = try readLaunchd(set: set, udid: udid, ["print-disabled", "system"]) + return Simctl.parseDisabled(output) + } + + /// Runs a read-only launchctl command inside the simulator, each attempt bounded + /// by `spawnTimeout`. launchd_sim's transient error 124 and an attempt that ran + /// out of time are retried after each of `retryDelays`; any other failure is + /// returned at once. + func readLaunchd(set: String, udid: String, _ args: [String]) throws -> String { + let arguments = simctlArgs(set: set, ["spawn", udid, "launchctl"] + args) + var attempt = 0 + while true { + let result: CommandResult + do { + result = try exec(.xcrun, arguments, timeout: spawnTimeout) + } catch { + throw SimSlimError("launchctl \(args[0]): \(error.localizedDescription)") + } + if result.succeeded { return result.stdoutText } + + let reason = + result.timedOut + ? "timed out after \(Int(spawnTimeout))s" : "exit status \(result.status)" + let message = "launchctl \(args[0]): \(reason): \(result.combinedText)" + let settling = Simctl.launchdSettling(result) || result.timedOut + if !settling || attempt >= retryDelays.count || deadlineExpired { + throw SimSlimError(message) + } + pause(retryDelays[attempt]) + attempt += 1 + } + } + + /// Whether a spawn failed with launchd_sim's error 124, which it answers while + /// a boot session starts or tears down. + static func launchdSettling(_ result: CommandResult) -> Bool { + if result.status == 124 { return true } + let text = result.stdoutText + result.stderrText + return text.contains("code=124") || text.contains("Domain is tearing down") + } + + /// Reads `launchctl print-disabled` lines. Recent launchd prints + /// `"com.apple.x" => disabled`; older builds print `=> true` / `=> false`. + static func parseDisabled(_ output: String) -> Set { + var set = Set() + for line in output.split(omittingEmptySubsequences: false, whereSeparator: { $0.isNewline }) { + guard let open = line.firstIndex(of: "\"") else { continue } + let rest = line[line.index(after: open)...] + guard let close = rest.firstIndex(of: "\"") else { continue } + let label = String(rest[..") else { continue } + let value = rest[arrow.upperBound...].trimmingCharacters(in: .whitespacesAndNewlines) + if value.hasPrefix("disabled") || value.hasPrefix("true") { set.insert(label) } + } + return set + } +} diff --git a/swift/Sources/SimSlimKit/Slim.swift b/swift/Sources/SimSlimKit/Slim.swift new file mode 100644 index 0000000..49ce758 --- /dev/null +++ b/swift/Sources/SimSlimKit/Slim.swift @@ -0,0 +1,388 @@ +// Copyright (c) 2026 Pavel Akhrameev (Swift port). MIT License; see LICENSE. + +import Foundation + +/// The offline route wrote the store but the booted device did not come up in the +/// desired state. The store is an undocumented CoreSimulator detail, so a runtime +/// is always free to ignore it: callers treat this as "take the supported path +/// instead", never as a failure. +struct OfflineIneffective: Error { + var reason: String +} + +/// How many `simctl spawn launchctl` transitions run at once. Overrides are +/// independent launchd writes, so they parallelize, and a small pool hides most +/// of the per-spawn latency without hammering a simulator still settling after +/// its first boot. +let spawnWorkers = 8 + +/// How many times `applyDelta` walks the remaining labels. Disables are +/// persistent, so each pass only retries what earlier passes failed. +let applyPasses = 3 + +/// launchctl's exit status when the service to boot out is not loaded ("No such +/// process"), which is already the state a live disable wants. +let bootoutGone: Int32 = 3 + +/// What a disable does to the running service. +enum DisableAction: Equatable { + /// `launchctl disable` only: takes effect at the next boot. + case overrideOnly + /// `disable` then `bootout`: the daemon stops now and cannot respawn. + case liveStop +} + +/// The managed labels that differ between `after` and `desired`. +func countLost(after: Set, desired: Set, managed: Set) -> Int { + let moves = delta(current: after, desired: desired, managed: managed) + return moves.toDisable.count + moves.toEnable.count +} + +private final class PassResults: @unchecked Sendable { + struct Transition: Sendable { + var action: String // "disable", "enable" or "bootout" (live stop) + var label: String + } + + private let lock = NSLock() + private(set) var failed: [Transition] = [] + private(set) var failures: [String] = [] + private(set) var done: Int + let total: Int + private let reporter: Reporter? + + init(done: Int, total: Int, reporter: Reporter?) { + self.done = done + self.total = total + self.reporter = reporter + } + + func record(_ transition: Transition, error: String?) { + lock.lock() + defer { lock.unlock() } + if let error { + failed.append(transition) + failures.append(error) + return + } + done += 1 + if done == total || done % 20 == 0 { report(reporter, " \(done)/\(total) services updated") } + } +} + +extension Simctl { + // MARK: - Per-label transitions + + /// `disable`/`enable`/`bootout` of one label, inside the simulator. + private func launchctl(set: String, udid: String, verb: String, label: String) throws + -> CommandResult + { + try exec( + .xcrun, simctlArgs(set: set, ["spawn", udid, "launchctl", verb, "system/\(label)"]), + timeout: spawnTimeout) + } + + private func failureText(_ verb: String, _ label: String, _ result: CommandResult) -> String { + let reason = + result.timedOut ? "timed out after \(Int(spawnTimeout))s" : "exit status \(result.status)" + return "\(verb) \(label): \(reason): \(result.combinedText)" + } + + /// Runs one transition; returns nil on success or the failure text. + private func runTransition(set: String, udid: String, action: String, label: String) -> String? { + let verb = action == "bootout" ? "disable" : action + do { + let result = try launchctl(set: set, udid: udid, verb: verb, label: label) + if !result.succeeded { return failureText(verb, label, result) } + if action != "bootout" { return nil } + let out = try launchctl(set: set, udid: udid, verb: "bootout", label: label) + if !out.succeeded && !(out.status == bootoutGone && !out.timedOut) { + return failureText("bootout", label, out) + } + return nil + } catch { + return "\(verb) \(label): \(error.localizedDescription)" + } + } + + /// Disables then enables the given labels. Each transition is its own + /// `simctl spawn launchctl`, run through a pool of `spawnWorkers`. A non-zero + /// exit is a real failure; failures are collected and retried on later passes + /// rather than aborting the whole profile. + func applyDelta( + set: String, udid: String, toDisable: [String], toEnable: [String], + disableAction: DisableAction, reporter: Reporter? + ) throws { + typealias Transition = PassResults.Transition + var pending: [Transition] = [] + for label in toDisable { + pending.append( + Transition(action: disableAction == .liveStop ? "bootout" : "disable", label: label)) + } + for label in toEnable { pending.append(Transition(action: "enable", label: label)) } + let total = pending.count + var done = 0 + var failures: [String] = [] + + var pass = 1 + while pass <= applyPasses && !pending.isEmpty { + if pass > 1 { + report( + reporter, " retrying \(pending.count) failed services (pass \(pass)/\(applyPasses))...") + // Give a launchd that refused the spawns a moment before asking again. + if !retryDelays.isEmpty, !deadlineExpired { + pause(retryDelays[min(pass - 2, retryDelays.count - 1)]) + } + } + let results = PassResults(done: done, total: total, reporter: reporter) + let slots = DispatchSemaphore(value: spawnWorkers) + let group = DispatchGroup() + for transition in pending { + if deadlineExpired { break } + slots.wait() + group.enter() + DispatchQueue.global().async { + defer { + slots.signal() + group.leave() + } + let error = self.runTransition( + set: set, udid: udid, action: transition.action, label: transition.label) + results.record(transition, error: error) + } + } + group.wait() + done = results.done + failures = results.failures + if deadlineExpired { + throw SimSlimError( + "\(total - done)/\(total) launchctl transitions incomplete: \(contextError)") + } + pending = results.failed + pass += 1 + } + if !pending.isEmpty { + throw SimSlimError( + "\(pending.count)/\(total) launchctl transitions failed after \(applyPasses) passes: " + + failures.joined(separator: "; ")) + } + } + + // MARK: - ensure + + private func minimumPersistentMessage(_ device: Device) -> String { + "\(device.runtimeName) runtime cannot persist launchd disable overrides across reboot; " + + "simslim requires \(device.platformName) \(device.minimumPersistentVersion) or newer, " + + "or `simslim on --no-reboot` to slim the current boot session only" + } + + /// Brings the device to exactly the desired disabled state and boots it. A + /// non-empty profile is rejected before anything is booted or changed on + /// runtimes without persistent overrides. On a runtime that persists them the + /// device takes the far cheaper offline route, whatever state it starts in. + /// Returns whether anything changed. + @discardableResult + public func ensure( + set: String, udid: String, desired requested: Set, reporter: Reporter? = nil + ) throws -> Bool { + var device = try findDevice(udid: udid, set: set) + let desired = desiredForDevice(device, requested) + let persistent = device.supportsPersistentOverrides + if !desired.isEmpty && !persistent { throw SimSlimError(minimumPersistentMessage(device)) } + let managed = Catalog.managedSet + + // A shut-down device can be reconfigured by writing the overrides + // launchd_sim reads when it starts, which skips both the per-label + // spawns and the reboot that would apply them. + let booted = device.state == "Booted" + if booted && persistent { + // `simctl list` says Booted from the moment the boot starts, so wait for + // launchd to be up before asking it anything. + try bootAndWait(set: set, udid: udid) + // An override only takes effect at the next boot, so a booted device + // already owes a shutdown and a boot. Spending them up front makes it a + // shut-down device and lets the store replace every launchctl spawn. + let live = try readDisabled(set: set, udid: udid) + let moves = delta(current: live, desired: desired, managed: managed) + if moves.toDisable.isEmpty && moves.toEnable.isEmpty { return false } + report(reporter, "Shutting the simulator down to reconfigure it offline...") + do { + try shutdown(set: set, udid: udid) + } catch { + throw SimSlimError("shutdown before reconfigure: \(error.localizedDescription)") + } + try waitShutdown(set: set, udid: udid) + device.state = "Shutdown" + } + if device.state == "Shutdown" && persistent { + do { + let changed = try ensureOffline( + set: set, udid: udid, desired: desired, reporter: reporter) + // A device that started booted only gets here with a real delta. + return changed || booted + } catch is OfflineIneffective { + report( + reporter, + "Could not apply the changes while the simulator was off; reconfiguring it while booted instead..." + ) + } + } + + report(reporter, "Booting the simulator (a first boot can take up to a minute)...") + try bootAndWait(set: set, udid: udid) + let current = try readDisabled(set: set, udid: udid) + let moves = delta(current: current, desired: desired, managed: managed) + if moves.toDisable.isEmpty && moves.toEnable.isEmpty { return false } + if !moves.toDisable.isEmpty { + report(reporter, "Disabling \(moves.toDisable.count) background services...") + } + if !moves.toEnable.isEmpty { + report(reporter, "Re-enabling \(moves.toEnable.count) background services...") + } + try applyDelta( + set: set, udid: udid, toDisable: moves.toDisable, toEnable: moves.toEnable, + disableAction: .overrideOnly, reporter: reporter) + report(reporter, "Rebooting the simulator to apply the changes...") + do { + try shutdown(set: set, udid: udid) + } catch { + throw SimSlimError("shutdown before reboot: \(error.localizedDescription)") + } + try waitShutdown(set: set, udid: udid) + try bootAndWait(set: set, udid: udid) + let after = try readDisabled(set: set, udid: udid) + let lost = countLost(after: after, desired: desired, managed: managed) + if lost > 0 { + throw SimSlimError( + "the disable overrides did not survive the reboot (\(lost) of \(moves.toDisable.count + moves.toEnable.count) changes lost)" + ) + } + return true + } + + /// Reaches the desired state on a shut-down device by writing its launchd + /// overrides directly, then boots it once, already slim. The state is read back + /// from the booted device rather than trusted. + func ensureOffline(set: String, udid: String, desired: Set, reporter: Reporter?) throws + -> Bool + { + let store = DisabledStore(root: storeRoot) + let managed = Catalog.managedSet + let current: Set + do { + current = try store.readDisabled(udid: udid) + } catch { + throw OfflineIneffective(reason: error.localizedDescription) + } + let moves = delta(current: current, desired: desired, managed: managed) + let changed = !moves.toDisable.isEmpty || !moves.toEnable.isEmpty + if changed { + report( + reporter, + "Reconfiguring \(moves.toDisable.count + moves.toEnable.count) background services while the simulator is off..." + ) + do { + try store.write(udid: udid, toDisable: moves.toDisable, toEnable: moves.toEnable) + } catch { + throw OfflineIneffective(reason: error.localizedDescription) + } + } + report(reporter, "Booting the simulator (a first boot can take up to a minute)...") + try bootAndWait(set: set, udid: udid) + let after = try readDisabled(set: set, udid: udid) + let lost = countLost(after: after, desired: desired, managed: managed) + if lost > 0 { + throw OfflineIneffective( + reason: + "\(lost) of \(moves.toDisable.count + moves.toEnable.count) offline overrides were not honoured at boot" + ) + } + return changed + } + + /// Disables the profile's daemons and boots the device slim. + @discardableResult + public func enableSlim( + set: String, udid: String, profile: Profile, reporter: Reporter? = nil + ) throws -> Bool { + try ensure(set: set, udid: udid, desired: profile.desired(), reporter: reporter) + } + + /// Re-enables every managed daemon, returning the device to stock. + @discardableResult + public func disableSlim(set: String, udid: String, reporter: Reporter? = nil) throws -> Bool { + try ensure(set: set, udid: udid, desired: [], reporter: reporter) + } + + // MARK: - No-reboot + + /// Slims the running boot session without a reboot: each daemon the profile + /// disables is booted out of launchd, and the override keeps launchd from + /// respawning it. Works on every runtime, but without persistent overrides the + /// simulator comes back stock at its next boot. Only moves toward more-disabled: + /// managed labels disabled beyond the profile are left alone. + @discardableResult + public func enableSlimNoReboot( + set: String, udid: String, profile: Profile, reporter: Reporter? = nil + ) throws -> Bool { + let device = try findDevice(udid: udid, set: set) + let desired = profile.desired(for: device) + report(reporter, "Booting the simulator (a first boot can take up to a minute)...") + try bootAndWait(set: set, udid: udid) + let current = try readDisabled(set: set, udid: udid) + let managed = Catalog.managedSet + let moves = delta(current: current, desired: desired, managed: managed) + if !moves.toEnable.isEmpty { + report( + reporter, + "Leaving \(moves.toEnable.count) services disabled beyond this profile; only `simslim off` re-enables them." + ) + } + // Check every profiled label, not just those without an override: an + // override says nothing about whether the job is still loaded. Labels that + // are both disabled and unloaded are skipped, so the command is idempotent. + let changed = !moves.toDisable.isEmpty + let labels = desired.filter { managed.contains($0) }.sorted() + report(reporter, "Stopping \(labels.count) background services for this boot session...") + let remaining = unloadInBatch( + set: set, udid: udid, runtimeID: device.runtimeID, labels: labels, reporter: reporter) + try applyDelta( + set: set, udid: udid, toDisable: remaining, toEnable: [], disableAction: .liveStop, + reporter: reporter) + let after = try readDisabled(set: set, udid: udid) + let missing = delta(current: after, desired: desired, managed: managed).toDisable + if !missing.isEmpty { + throw SimSlimError("\(missing.count) of \(labels.count) disable overrides did not take") + } + return changed + } + + /// Disables and unloads the labels whose job plist it can find with one + /// `launchctl unload -w` per chunk, then reads the state back and returns what + /// still needs the per-label disable and bootout. Anything that goes wrong here + /// only means more labels take the per-label path. + func unloadInBatch( + set: String, udid: String, runtimeID: String, labels: [String], reporter: Reporter? + ) -> [String] { + if runtimeID.isEmpty { return labels } + guard let root = try? runtimeRoot(runtimeID: runtimeID) else { return labels } + // Only what is still enabled or loaded needs stopping, so an already-slim + // device spawns no unload and does not report work it did not do. + guard let pending = try? stopState(set: set, udid: udid, labels: labels) else { + return labels + } + if pending.isEmpty { + report(reporter, " all \(labels.count) services were already stopped") + return [] + } + let plists = launchdJobPlists( + root: root, labels: pending, plistLabel: { try self.readPlistLabel(path: $0) }) + if plists.isEmpty { return pending } + let paths = pending.compactMap { plists[$0] } + unloadJobs(set: set, udid: udid, paths: paths) + guard let rest = try? stopState(set: set, udid: udid, labels: pending) else { return pending } + report( + reporter, " \(pending.count - rest.count)/\(pending.count) services stopped in one batch") + return rest + } +} diff --git a/swift/Sources/SimSlimKit/Status.swift b/swift/Sources/SimSlimKit/Status.swift new file mode 100644 index 0000000..b22f5e6 --- /dev/null +++ b/swift/Sources/SimSlimKit/Status.swift @@ -0,0 +1,102 @@ +// Copyright (c) 2026 Pavel Akhrameev (Swift port). MIT License; see LICENSE. + +import Foundation + +/// How slim a device currently is. The JSON keys are a contract with the app. +public struct Status: Codable, Equatable, Sendable { + public var managedDisabled: Int // managed labels currently disabled + public var managedTotal: Int // size of the managed universe + public var booted: Bool + public var persistent: Bool // the runtime keeps disabled state across reboot + + public init(managedDisabled: Int, managedTotal: Int, booted: Bool, persistent: Bool) { + self.managedDisabled = managedDisabled + self.managedTotal = managedTotal + self.booted = booted + self.persistent = persistent + } + + /// The static fields of a device's status, before its launchd state is read. + public static func initial(for device: Device) -> Status { + Status( + managedDisabled: 0, + managedTotal: Profile().desired(for: device).count, + booted: device.state == "Booted", + persistent: device.supportsPersistentOverrides) + } + + /// "stock", "partially slim" or "slim". + public var verdict: String { + if managedDisabled == managedTotal { return "slim" } + return managedDisabled > 0 ? "partially slim" : "stock" + } +} + +extension Device { + var minimumPersistentVersion: String { + switch platformName { + case "watchOS": return "11.5" + case "visionOS": return "2.5" + default: return "18.5" + } + } + + /// Applies the launchd persistence version gate to the device's platform. + /// tvOS 18.5, watchOS 11.5 and visionOS 2.5 are the release generation + /// corresponding to iOS 18.5. This gate is not proof of persistence: slimming + /// always reads overrides back after boot and fails if the runtime lost them. + public var supportsPersistentOverrides: Bool { + var minimumMajor = 18 + switch platformName { + case "iOS", "tvOS": break + case "watchOS": minimumMajor = 11 + case "visionOS": minimumMajor = 2 + default: return false + } + let parts = osVersion.split(separator: ".", maxSplits: 2, omittingEmptySubsequences: false) + guard parts.count >= 2, let major = Int(parts[0]), let minor = Int(parts[1]), minor >= 0 else { + return false + } + return major > minimumMajor || (major == minimumMajor && minor >= 5) + } +} + +/// The managed launchd labels a category has disabled on a simulator, alongside +/// the feature that stops working as a result. +public struct DroppedCategory: Codable, Equatable, Sendable { + public let id: String + public let name: String + public let downside: String + public let labels: [String] +} + +extension Catalog { + /// Groups the disabled managed daemons by category, in category order, + /// omitting categories with nothing disabled. + public static func droppedCategories(disabled: Set) -> [DroppedCategory] { + categories.compactMap { category in + let labels = category.labels.filter { disabled.contains($0) }.sorted() + if labels.isEmpty { return nil } + return DroppedCategory( + id: category.id, name: category.name, downside: category.downside, labels: labels) + } + } +} + +extension Simctl { + /// Reads a booted device's status and its disabled labels. + public func readStatus(for device: Device) throws -> (status: Status, disabled: Set) { + var status = Status.initial(for: device) + guard status.booted else { + throw SimSlimError("simulator must be booted to read its state (it is \(device.state))") + } + let managed = Profile().desired(for: device) + let disabled = try readDisabled(set: device.set, udid: device.udid) + status.managedDisabled = disabled.filter { managed.contains($0) }.count + return (status, disabled) + } + + public func readStatus(udid: String) throws -> (status: Status, disabled: Set) { + try readStatus(for: try findDevice(udid: udid)) + } +} diff --git a/swift/Sources/SimSlimKit/Subprocess.swift b/swift/Sources/SimSlimKit/Subprocess.swift new file mode 100644 index 0000000..cafac5a --- /dev/null +++ b/swift/Sources/SimSlimKit/Subprocess.swift @@ -0,0 +1,195 @@ +// Copyright (c) 2026 Pavel Akhrameev (Swift port). MIT License; see LICENSE. + +import Foundation + +/// Every program simslim may start. This is a closed list of absolute paths: +/// nothing is looked up through PATH, and `Process` is used only in this file +/// (`scripts/verify-deps.sh` enforces both). +public enum Executable: String, CaseIterable, Sendable { + case xcrun = "/usr/bin/xcrun" + case plutil = "/usr/bin/plutil" + case du = "/usr/bin/du" + case pgrep = "/usr/bin/pgrep" + case ps = "/bin/ps" + case top = "/usr/bin/top" + case lsof = "/usr/sbin/lsof" +} + +public struct CommandResult: Equatable, Sendable { + /// The exit status, or the negated signal number if the process was killed. + public var status: Int32 + public var stdout: Data + public var stderr: Data + /// True when the runner killed the process for exceeding its timeout. + public var timedOut: Bool + + public init( + status: Int32, stdout: Data = Data(), stderr: Data = Data(), timedOut: Bool = false + ) { + self.status = status + self.stdout = stdout + self.stderr = stderr + self.timedOut = timedOut + } + + public var succeeded: Bool { status == 0 && !timedOut } + public var stdoutText: String { String(decoding: stdout, as: UTF8.self) } + public var stderrText: String { String(decoding: stderr, as: UTF8.self) } + + /// stdout followed by stderr, trimmed: what Go's CombinedOutput would show. + public var combinedText: String { + (stdoutText + stderrText).trimmingCharacters(in: .whitespacesAndNewlines) + } +} + +/// The seam tests use to replace real processes with a fake. +public protocol CommandRunning: Sendable { + /// Runs `executable` and returns its result. A non-zero exit is a result, not + /// an error; only a failure to start the process throws. With a `timeout` + /// the process is killed when it expires and `timedOut` is set. + func run(_ executable: Executable, _ arguments: [String], timeout: TimeInterval?) throws + -> CommandResult +} + +extension CommandRunning { + public func run(_ executable: Executable, _ arguments: [String]) throws -> CommandResult { + try run(executable, arguments, timeout: nil) + } +} + +public struct SystemCommandRunner: CommandRunning { + /// How long to keep reading a finished process's output pipes. When a timed-out + /// `xcrun` is killed, the `simctl` child it started can still hold the pipe; + /// without this bound the read would never return. + var waitDelay: TimeInterval + /// Maps an Executable to the path to start. Always the real path outside tests. + var resolve: @Sendable (Executable) -> String + + public init() { + self.init(waitDelay: 5, resolve: { $0.rawValue }) + } + + init(waitDelay: TimeInterval, resolve: @escaping @Sendable (Executable) -> String) { + self.waitDelay = waitDelay + self.resolve = resolve + } + + public func run(_ executable: Executable, _ arguments: [String], timeout: TimeInterval?) throws + -> CommandResult + { + let path = resolve(executable) + let process = Process() + process.executableURL = URL(fileURLWithPath: path) + process.arguments = arguments + process.standardInput = FileHandle.nullDevice + + let out = Pipe() + let err = Pipe() + process.standardOutput = out + process.standardError = err + + let outCollector = Collector(out) + let errCollector = Collector(err) + let exited = DispatchSemaphore(value: 0) + process.terminationHandler = { _ in exited.signal() } + + do { + try process.run() + } catch { + outCollector.abandon() + errCollector.abandon() + throw SimSlimError("cannot run \(path): \(error.localizedDescription)") + } + // The child holds its own copies; ours must close or EOF never arrives. + try? out.fileHandleForWriting.close() + try? err.fileHandleForWriting.close() + + let timeoutState = TimeoutState() + var killer: DispatchWorkItem? + if let timeout { + let pid = process.processIdentifier + let item = DispatchWorkItem { + if timeoutState.markTimedOut(ifRunning: process) { kill(pid, SIGKILL) } + } + killer = item + DispatchQueue.global().asyncAfter(deadline: .now() + timeout, execute: item) + } + + exited.wait() + killer?.cancel() + + // After exit the pipes normally reach EOF at once. If a grandchild still + // holds one open, give it `waitDelay` and then stop waiting. + let deadline = DispatchTime.now() + waitDelay + let outDone = outCollector.waitForEOF(until: deadline) + let errDone = errCollector.waitForEOF(until: deadline) + if !outDone { outCollector.abandon() } + if !errDone { errCollector.abandon() } + + var status = process.terminationStatus + if process.terminationReason == .uncaughtSignal { status = -status } + return CommandResult( + status: status, stdout: outCollector.data, stderr: errCollector.data, + timedOut: timeoutState.timedOut) + } +} + +/// Reads a pipe through its readability handler so a pipe that never closes can +/// be abandoned instead of blocking a thread forever. +private final class Collector: @unchecked Sendable { + private let lock = NSLock() + private var buffer = Data() + private let eof = DispatchSemaphore(value: 0) + private let handle: FileHandle + + init(_ pipe: Pipe) { + handle = pipe.fileHandleForReading + handle.readabilityHandler = { [weak self] h in + guard let self else { return } + let chunk = h.availableData + if chunk.isEmpty { + h.readabilityHandler = nil + self.eof.signal() + } else { + self.lock.lock() + self.buffer.append(chunk) + self.lock.unlock() + } + } + } + + var data: Data { + lock.lock() + defer { lock.unlock() } + return buffer + } + + func waitForEOF(until deadline: DispatchTime) -> Bool { + eof.wait(timeout: deadline) == .success + } + + func abandon() { + handle.readabilityHandler = nil + } +} + +private final class TimeoutState: @unchecked Sendable { + private let lock = NSLock() + private var flag = false + + var timedOut: Bool { + lock.lock() + defer { lock.unlock() } + return flag + } + + /// Records the timeout only if the process is still running, so a process + /// that exits just before the timer fires is not reported as timed out. + func markTimedOut(ifRunning process: Process) -> Bool { + lock.lock() + defer { lock.unlock() } + guard process.isRunning else { return false } + flag = true + return true + } +} diff --git a/swift/Sources/SimSlimKit/Verify.swift b/swift/Sources/SimSlimKit/Verify.swift new file mode 100644 index 0000000..a3d357e --- /dev/null +++ b/swift/Sources/SimSlimKit/Verify.swift @@ -0,0 +1,65 @@ +// Copyright (c) 2026 Pavel Akhrameev (Swift port). MIT License; see LICENSE. + +import Foundation + +/// How a booted simulator's launchd disable overrides compare to a profile's +/// desired set. Only managed labels are considered. +public struct VerifyResult: Codable, Equatable, Sendable { + public var udid: String + public var ok: Bool + public var missing: [String] // the profile wants these disabled; they are enabled + public var extra: [String] // managed labels disabled beyond the profile + + public init(udid: String = "", ok: Bool, missing: [String], extra: [String]) { + self.udid = udid + self.ok = ok + self.missing = missing + self.extra = extra + } + + private enum CodingKeys: String, CodingKey { case udid, ok, missing, extra } + + public func encode(to encoder: Encoder) throws { + var c = encoder.container(keyedBy: CodingKeys.self) + try c.encode(udid, forKey: .udid) + try c.encode(ok, forKey: .ok) + if !missing.isEmpty { try c.encode(missing, forKey: .missing) } // Go omitempty + if !extra.isEmpty { try c.encode(extra, forKey: .extra) } + } + + public init(from decoder: Decoder) throws { + let c = try decoder.container(keyedBy: CodingKeys.self) + udid = try c.decode(String.self, forKey: .udid) + ok = try c.decode(Bool.self, forKey: .ok) + missing = try c.decodeIfPresent([String].self, forKey: .missing) ?? [] + extra = try c.decodeIfPresent([String].self, forKey: .extra) ?? [] + } +} + +/// Diffs the currently disabled labels against the desired set, restricted to +/// the managed universe: unmanaged labels are never simslim's business and +/// never count as drift. +public func compareDisabled( + disabled: Set, desired: Set, managed: Set +) -> VerifyResult { + let missing = desired.filter { !disabled.contains($0) }.sorted() + let extra = disabled.filter { managed.contains($0) && !desired.contains($0) }.sorted() + return VerifyResult(ok: missing.isEmpty && extra.isEmpty, missing: missing, extra: extra) +} + +extension Simctl { + /// Checks, without mutating anything, that a booted simulator's disable + /// overrides match the profile exactly. The overrides are per-simulator state + /// that is easy to lose silently when a device is erased or recreated. + public func verifyProfile(udid: String, profile: Profile) throws -> VerifyResult { + let device = try findDevice(udid: udid) + guard device.state == "Booted" else { + throw SimSlimError("simulator must be booted to read its state (it is \(device.state))") + } + let disabled = try readDisabled(set: device.set, udid: device.udid) + var result = compareDisabled( + disabled: disabled, desired: profile.desired(for: device), managed: Catalog.managedSet) + result.udid = udid + return result + } +} diff --git a/swift/Sources/SimSlimKit/Version.swift b/swift/Sources/SimSlimKit/Version.swift new file mode 100644 index 0000000..7eac196 --- /dev/null +++ b/swift/Sources/SimSlimKit/Version.swift @@ -0,0 +1,4 @@ +// Copyright (c) 2026 Pavel Akhrameev (Swift port). MIT License; see LICENSE. + +/// Overridden at build time by the release script; "dev" for local builds. +public let simslimVersion = "dev" diff --git a/swift/Sources/SimSlimKit/Watch.swift b/swift/Sources/SimSlimKit/Watch.swift new file mode 100644 index 0000000..bf01343 --- /dev/null +++ b/swift/Sources/SimSlimKit/Watch.swift @@ -0,0 +1,433 @@ +// Copyright (c) 2026 Pavel Akhrameev (Swift port). MIT License; see LICENSE. + +import Foundation + +/// How often `watch` rescans the device sets. +public let defaultWatchInterval: TimeInterval = 3 + +/// How long `watch` waits for a new device directory's device.plist, which +/// `simctl create` writes just after the directory. +let newDevicePlistWait: TimeInterval = 2 + +/// The WatchEvent kinds. A wrapper that boots a device and then changes its +/// services waits for `slimmed` (or `failed`): after it, the watcher does not +/// touch that device again until the device shuts down. +public enum WatchEventKind { + public static let slimming = "slimming" // an after-boot pass started + public static let slimmed = "slimmed" // the pass for the current boot finished + public static let failed = "failed" // the pass failed; the next scan retries it + public static let stopped = "stopped" // the device shut down, so its pass was cancelled + public static let slimmedBeforeBoot = "slimmed_before_boot" // disables written to a store +} + +/// The stable, machine-readable form of a watcher log line. +public struct WatchEvent: Equatable, Sendable { + public var event: String + public var udid: String + public var set: String + public var services: Int // disables written, for slimmed_before_boot + public var error: String // for failed + + public init(event: String, udid: String, set: String, services: Int = 0, error: String = "") { + self.event = event + self.udid = udid + self.set = set + self.services = services + self.error = error + } + + /// One compact JSON object, keys in the Go struct's order, empty `services` + /// and `error` omitted. + public var jsonLine: String { + var fields = [ + "\"event\":\(WatchEvent.quote(event))", "\"udid\":\(WatchEvent.quote(udid))", + "\"set\":\(WatchEvent.quote(set))", + ] + if services != 0 { fields.append("\"services\":\(services)") } + if !error.isEmpty { fields.append("\"error\":\(WatchEvent.quote(error))") } + return "{" + fields.joined(separator: ",") + "}" + } + + private static func quote(_ text: String) -> String { + let data = (try? JSONEncoder().encode(text)) ?? Data("\"\"".utf8) + return String(decoding: data, as: UTF8.self).replacingOccurrences(of: "\\/", with: "/") + } +} + +/// The device sets' on-disk directories, mapped to each set's name: the default +/// set, Xcode's parallel-testing set, and any `--set` path. +func deviceSetDirs(_ simctl: Simctl, home: String) -> [String: String] { + var dirs: [String: String] = [:] + let developer = ((home as NSString).appendingPathComponent("Library") as NSString) + .appendingPathComponent("Developer") + for set in simctl.knownSets { + switch set.token { + case "": + dirs[ + ((developer as NSString).appendingPathComponent("CoreSimulator") as NSString) + .appendingPathComponent("Devices")] = set.name + case "testing": dirs[(developer as NSString).appendingPathComponent("XCTestDevices")] = set.name + default: dirs[set.token] = set.name + } + } + return dirs +} + +/// Reads the device CoreSimulator describes in a device directory's +/// device.plist: its UDID, runtime and state (1 is Shutdown). +func readDevicePlist(_ dir: DeviceDir) throws -> Device { + let file = (dir.path as NSString).appendingPathComponent("device.plist") + let data = try Data(contentsOf: URL(fileURLWithPath: file)) + let object: Any + do { + object = try PropertyListSerialization.propertyList(from: data, options: [], format: nil) + } catch { + throw SimSlimError("parse device.plist: \(error.localizedDescription)") + } + let dict = object as? [String: Any] ?? [:] + // Strings and integers both read as text, as in Go. + func text(_ key: String) -> String { + if let value = dict[key] as? String { return value } + if let value = dict[key] as? NSNumber { return value.stringValue } + return "" + } + let runtime = text("runtime") + // device.plist is read from a directory anyone with write access to the set can + // create, and the UDID names the store path, so it must be a real UDID and + // must be the one the directory is named for. + let udid = text("UDID") + guard isUDID(udid), + udid.caseInsensitiveCompare((dir.path as NSString).lastPathComponent) == .orderedSame + else { + throw SimSlimError("device.plist UDID does not match its directory") + } + guard let parsed = Simctl.parseRuntime(runtime), !text("UDID").isEmpty else { + throw SimSlimError("device.plist names no UDID or supported runtime") + } + return Device( + udid: text("UDID"), state: text("state") == "1" ? "Shutdown" : "Booted", + platform: parsed.platform, osVersion: parsed.version, set: dir.set, + dataPath: (dir.path as NSString).appendingPathComponent("data"), runtimeID: runtime) +} + +/// Writes the profile's missing disable overrides into a shut-down device's +/// launchd store and reports how many it added. Like the no-reboot slim `watch` +/// applies after boot, it only ever adds disables: a service someone disabled +/// beyond the profile stays disabled, and nothing is re-enabled. A device that is +/// not shut down, or whose runtime does not persist overrides, is left alone; the +/// after-boot slim covers it. +func preslimDevice(_ device: Device, profile: Profile, storeRoot: String) throws -> Int { + if device.state != "Shutdown" || !device.supportsPersistentOverrides { return 0 } + let store = DisabledStore(root: storeRoot) + let current = try store.readDisabled(udid: device.udid) + let toDisable = delta( + current: current, desired: profile.desired(for: device), managed: Catalog.managedSet + ).toDisable + if toDisable.isEmpty { return 0 } + try store.write(udid: device.udid, toDisable: toDisable, toEnable: []) + return toDisable.count +} + +/// Slims every simulator so that none starts the profile's daemons, then leaves +/// it alone until it boots again. A shut-down simulator on a runtime that +/// persists overrides is slimmed before it boots: the profile's disable +/// overrides are written into its launchd store, so its next boot, its very +/// first included, starts none of those daemons. New devices are caught by a +/// kqueue watch on the device-set directories, ahead of a tool that creates and +/// boots at once. Every simulator is still slimmed no-reboot as it boots: that +/// reads the device back, and it is the only hook for a device that booted before +/// its store was seeded, on an older runtime, or as an xcodebuild +/// parallel-testing clone (cloned stock, since overrides do not survive +/// `simctl clone`, and booted at once). +public final class Watcher: @unchecked Sendable { + /// One boot's after-boot slim. Cancelling it stops it once that boot ends, so + /// it cannot keep retrying into the device's next boot. + final class Pass: @unchecked Sendable { + private let lock = NSLock() + private var flag = false + var isCancelled: Bool { + lock.lock() + defer { lock.unlock() } + return flag + } + func cancel() { + lock.lock() + flag = true + lock.unlock() + } + } + + public typealias Slimmer = @Sendable (Simctl, String, String, Profile, Reporter?) throws -> Bool + public typealias Preslimmer = @Sendable (Device, Profile) throws -> Int + + let profile: Profile + var simctl: Simctl + let report: Reporter? + let events: (@Sendable (WatchEvent) -> Void)? + let home: String + /// The per-device slim; a field so tests can substitute a fake. + var slim: Slimmer + /// Seeds a shut-down device before it boots; a field so tests can substitute + /// a fake. + var preslim: Preslimmer? + + private let lock = NSLock() + private var passes: [String: Pass] = [:] + private var seeded = Set() + private let group = DispatchGroup() + private var stopRequested: @Sendable () -> Bool = { false } + private var wakeFlag = false + private let wakeup = DispatchSemaphore(value: 0) + + public init( + simctl: Simctl, profile: Profile, home: String = NSHomeDirectory(), + report: Reporter? = nil, events: (@Sendable (WatchEvent) -> Void)? = nil + ) { + self.simctl = simctl + self.profile = profile + self.home = home + self.report = report + self.events = events + self.slim = { ctl, set, udid, profile, reporter in + try ctl.enableSlimNoReboot(set: set, udid: udid, profile: profile, reporter: reporter) + } + let root = simctl.storeRoot + self.preslim = { device, profile in + try preslimDevice(device, profile: profile, storeRoot: root) + } + } + + /// Watches until `stop` returns true, scanning the default, testing and any + /// `--set` device sets every `interval`. Each booted device is slimmed in its + /// own thread so one slow reconfigure does not delay catching the next clone, + /// and `run` returns once those are done. + public func run( + interval: TimeInterval = defaultWatchInterval, stop: @escaping @Sendable () -> Bool + ) { + let interval = interval > 0 ? interval : defaultWatchInterval + stopRequested = stop + simctl.cancelled = stop + let dirs = deviceSetDirs(simctl, home: home) + group.enter() + Thread.detachNewThread { [self] in + defer { group.leave() } + watchDeviceDirs(setDirs: dirs, stop: stop) { dir in + // seedNew waits for device.plist, so each new device gets its own + // thread: a batch of parallel-testing clones seeds at once. + group.enter() + Thread.detachNewThread { [self] in + defer { group.leave() } + seedNew(dir) + signalScan() + } + } + } + while !stop() { + scan() + var waited = 0.0 + while waited < interval && !stop() { + if wakeup.wait(timeout: .now() + 0.2) == .success { + lock.lock() + wakeFlag = false + lock.unlock() + break + } + waited += 0.2 + } + } + // No slim may outlive the call; a stopped run aborts an in-flight slim at + // its next command, which keeps the wait short. + if group.wait(timeout: .now() + 20) == .timedOut { + report?("watch: a slim was still running at exit") + } + } + + /// Asks the loop to scan now; coalesces while one is already due. + private func signalScan() { + lock.lock() + let already = wakeFlag + wakeFlag = true + lock.unlock() + if !already { wakeup.signal() } + } + + /// Blocks until every slim and seed thread started so far has finished. + func waitForWork() { group.wait() } + + private func emit(_ event: WatchEvent) { events?(event) } + + /// Slims a just-created device before its first boot, straight from its + /// directory and without a `simctl list`, which on a loaded host would still be + /// running when a script that boots right after creating has started launchd_sim. + func seedNew(_ dir: DeviceDir) { + let limit = Date().addingTimeInterval(newDevicePlistWait) + var device: Device? + while device == nil && Date() < limit { + device = try? readDevicePlist(dir) + if device == nil { + if stopRequested() { return } + Thread.sleep(forTimeInterval: 0.01) + } + } + // Not a device, or not one simslim slims; the scan decides. + guard let device else { return } + seed(device) + } + + func scan() { + let devices: [Device] + do { + devices = try simctl.listDevices().sorted { $0.udid < $1.udid } + } catch { + report?("watch: list devices: \(error.localizedDescription)") + return + } + prune(devices) + for device in devices { + if device.state != "Booted" { + // On iOS below 18.5 the no-reboot slim dies with the boot session, so a + // device that shut down comes back stock and needs slimming again. + // Re-slimming an already-slim device is a cheap no-op. + forget(device.udid) + seed(device) + continue + } + // A booted device may change its own store (and `simslim off` may clear + // it), so check it again the next time it is shut down. + lock.lock() + seeded.remove(device.udid) + lock.unlock() + guard let pass = claim(device.udid) else { continue } + group.enter() + let stop = stopRequested + var ctl = simctl + ctl.cancelled = { pass.isCancelled || stop() } + Thread.detachNewThread { [self] in + defer { group.leave() } + report?("watch: slimming \(device.udid) (set \(device.set))") + emit(WatchEvent(event: WatchEventKind.slimming, udid: device.udid, set: device.set)) + var failure: Error? + do { + _ = try slim(ctl, device.set, device.udid, profile, prefixed(device.udid)) + } catch { + failure = error + } + finish(device, pass, failure) + } + } + } + + /// Slims a shut-down device ahead of its next boot, once per shutdown. A + /// failure is retried on the next scan, and the after-boot slim still covers + /// the device if it boots first. + func seed(_ device: Device) { + guard let preslim else { return } + // A device caught Shutting Down or Booting is seeded once it reads Shutdown. + if device.state != "Shutdown" { return } + lock.lock() + defer { lock.unlock() } // serializes the store writes of seedNew and scan + if seeded.contains(device.udid) { return } + let count: Int + do { + count = try preslim(device, profile) + } catch { + report?("watch: \(device.udid): slim before boot: \(error.localizedDescription)") + return + } + seeded.insert(device.udid) + if count == 0 { return } + // launchd_sim reads the store once, when it starts: a seed that lands after + // the boot began only counts from the next boot. + if !device.dataPath.isEmpty, + let now = try? readDevicePlist( + DeviceDir(path: (device.dataPath as NSString).deletingLastPathComponent, set: device.set)), + now.state != "Shutdown" + { + report?( + "watch: \(device.udid) booted before its slim (\(count) services) landed; slimming it as it boots" + ) + return + } + report?( + "watch: slimmed \(device.udid) before boot (\(count) services disabled, set \(device.set))") + emit( + WatchEvent( + event: WatchEventKind.slimmedBeforeBoot, udid: device.udid, set: device.set, + services: count)) + } + + /// Reports a pass's outcome. It holds the lock so a superseded pass, whose boot + /// ended, can never announce slimmed after a newer boot's pass has started. + func finish(_ device: Device, _ pass: Pass, _ failure: Error?) { + lock.lock() + defer { lock.unlock() } + if passes[device.udid] !== pass { + report?("watch: \(device.udid) shut down; stopped its slim") + emit(WatchEvent(event: WatchEventKind.stopped, udid: device.udid, set: device.set)) + } else if let failure { + // A transient launchctl failure would otherwise leave this clone stock for + // the whole test run. The next scan retries it, and a torn-down clone drops + // out of simctl list, so this does not loop. + passes[device.udid] = nil + report?("watch: \(device.udid): \(failure.localizedDescription)") + emit( + WatchEvent( + event: WatchEventKind.failed, udid: device.udid, set: device.set, + error: failure.localizedDescription)) + } else { + report?("watch: slimmed \(device.udid)") + emit(WatchEvent(event: WatchEventKind.slimmed, udid: device.udid, set: device.set)) + } + } + + /// Starts a pass for a booted UDID, returning nil when one is already done or + /// in flight for this boot. + func claim(_ udid: String) -> Pass? { + lock.lock() + defer { lock.unlock() } + if passes[udid] != nil { return nil } + let pass = Pass() + passes[udid] = pass + return pass + } + + /// Drops the UDIDs of deleted devices, such as finished parallel-testing + /// clones, so `passes` and `seeded` do not grow by one entry per clone. A + /// device created after the listing started is only seeded again, which is a + /// no-op. + func prune(_ devices: [Device]) { + let listed = Set(devices.map(\.udid)) + lock.lock() + defer { lock.unlock() } + for (udid, pass) in passes where !listed.contains(udid) { + pass.cancel() + passes[udid] = nil + } + seeded = seeded.intersection(listed) + } + + /// Ends a device's boot: its pass, if still running, is cancelled, and its next + /// boot gets a pass of its own. + func forget(_ udid: String) { + lock.lock() + if let pass = passes[udid] { + pass.cancel() + passes[udid] = nil + } + lock.unlock() + } + + /// Tags a device's own progress lines with its UDID, so the interleaved output + /// of concurrent slims stays attributable. + private func prefixed(_ udid: String) -> Reporter? { + guard let report else { return nil } + return { report("watch: \(udid): \($0)") } + } +} + +/// Whether `text` has the 8-4-4-4-12 hexadecimal form of a simulator UDID. +func isUDID(_ text: String) -> Bool { + let groups = text.split(separator: "-", omittingEmptySubsequences: false) + guard groups.map(\.count) == [8, 4, 4, 4, 12] else { return false } + return groups.allSatisfy { $0.allSatisfy { $0.isASCII && $0.isHexDigit } } +} diff --git a/swift/Sources/simslim/main.swift b/swift/Sources/simslim/main.swift new file mode 100644 index 0000000..6a80264 --- /dev/null +++ b/swift/Sources/simslim/main.swift @@ -0,0 +1,13 @@ +// Copyright (c) 2026 Pavel Akhrameev (Swift port). MIT License; see LICENSE. + +import Foundation +import SimSlimCLI + +// Output goes through unbuffered writes so progress and results interleave +// correctly when stdout and stderr are the same pipe. +func write(_ handle: FileHandle) -> CLI.Sink { + { text in handle.write(Data(text.utf8)) } +} + +let cli = CLI(stdout: write(.standardOutput), stderr: write(.standardError)) +exit(cli.run(Array(CommandLine.arguments.dropFirst()))) diff --git a/swift/Tests/SimSlimCLITests/ArgumentsTests.swift b/swift/Tests/SimSlimCLITests/ArgumentsTests.swift new file mode 100644 index 0000000..797c768 --- /dev/null +++ b/swift/Tests/SimSlimCLITests/ArgumentsTests.swift @@ -0,0 +1,133 @@ +// Copyright (c) 2026 Pavel Akhrameev (Swift port). MIT License; see LICENSE. + +import SimSlimKit +import XCTest + +@testable import SimSlimCLI + +final class ArgumentsTests: XCTestCase { + private let specs: [FlagSpec] = [ + .bool("json", onlyOnce: true), .bool("booted"), .string("except"), .string("set"), + ] + + func testFlagsMayComeBeforeOrAfterPositionals() throws { + let a = try parseArguments(["udid", "--except", "search", "--json"], specs: specs) + let b = try parseArguments(["--json", "--except", "search", "udid"], specs: specs) + for parsed in [a, b] { + XCTAssertEqual(parsed.positionals, ["udid"]) + XCTAssertEqual(parsed.string("except"), "search") + XCTAssertTrue(parsed.bool("json")) + } + } + + func testFlagForms() throws { + let parsed = try parseArguments(["-json", "--except=a,b", "--set", "/x y"], specs: specs) + XCTAssertTrue(parsed.bool("json")) + XCTAssertEqual(parsed.string("except"), "a,b") + XCTAssertEqual(parsed.string("set"), "/x y") + } + + func testEmptyInlineValueIsKeptNotDropped() throws { + let parsed = try parseArguments(["--except="], specs: specs) + XCTAssertTrue(parsed.has("except")) + XCTAssertEqual(parsed.string("except"), "") + } + + func testBoolFlagNeverConsumesTheNextToken() throws { + let parsed = try parseArguments(["--booted", "udid"], specs: specs) + XCTAssertEqual(parsed.positionals, ["udid"]) + XCTAssertTrue(parsed.bool("booted")) + } + + func testBoolFlagValues() throws { + XCTAssertFalse(try parseArguments(["--booted=false"], specs: specs).bool("booted")) + XCTAssertTrue(try parseArguments(["--booted=true"], specs: specs).bool("booted")) + XCTAssertThrowsError(try parseArguments(["--booted=maybe"], specs: specs)) + } + + func testDoubleDashEndsFlagParsing() throws { + let parsed = try parseArguments(["--json", "--", "--except", "-x"], specs: specs) + XCTAssertEqual(parsed.positionals, ["--except", "-x"]) + XCTAssertTrue(parsed.bool("json")) + XCTAssertFalse(parsed.has("except")) + } + + func testLoneDashIsAPositional() throws { + XCTAssertEqual(try parseArguments(["-"], specs: specs).positionals, ["-"]) + } + + func testStringFlagConsumesTheNextTokenEvenIfItLooksLikeAFlag() throws { + XCTAssertEqual( + try parseArguments(["--except", "--json"], specs: specs).string("except"), "--json") + } + + func testErrors() { + func message(_ tokens: [String]) -> String? { + do { + _ = try parseArguments(tokens, specs: specs) + return nil + } catch { return (error as? SimSlimError)?.message } + } + XCTAssertEqual(message(["--nope"]), "flag provided but not defined: -nope") + XCTAssertEqual(message(["--except"]), "flag needs an argument: --except") + XCTAssertEqual(message(["--json", "--json"]), "flag --json can only be used once") + XCTAssertNil(message(["--booted", "--booted"]), "only json is once-only") + } + + func testLastStringValueWins() throws { + XCTAssertEqual( + try parseArguments(["--except", "a", "--except", "b"], specs: specs).string("except"), "b") + } +} + +final class DurationTests: XCTestCase { + func testValidDurations() throws { + let cases: [(String, TimeInterval)] = [ + ("10m", 600), ("90s", 90), ("1h", 3600), ("1h30m", 5400), ("1.5h", 5400), ("500ms", 0.5), + ("2m30s", 150), ("0", 0), ("+5s", 5), ("-5s", -5), ("1us", 1e-6), ("1µs", 1e-6), + ("1ns", 1e-9), + ] + for (text, seconds) in cases { + XCTAssertEqual(try parseGoDuration(text), seconds, accuracy: 1e-9, text) + } + } + + func testInvalidDurations() { + for text in [ + "", "abc", "10", "10x", "m10", "1h 30m", ".", "--5s", "5s5", + "9999999999999999999s", String(repeating: "9", count: 400) + "s", + ] { + XCTAssertThrowsError(try parseGoDuration(text), "\"\(text)\"") + } + XCTAssertThrowsError(try parseGoDuration("10")) { error in + XCTAssertEqual((error as? SimSlimError)?.message, "time: missing unit in duration \"10\"") + } + XCTAssertThrowsError(try parseGoDuration("10x")) { error in + XCTAssertEqual( + (error as? SimSlimError)?.message, "time: unknown unit \"x\" in duration \"10x\"") + } + } +} + +final class FormatTests: XCTestCase { + func testPadRightCountsScalarsLikeGo() { + XCTAssertEqual(padRight("ab", 5), "ab ") + XCTAssertEqual(padRight("abcdef", 3), "abcdef", "never truncates") + XCTAssertEqual(padRight("é", 3), "é ") + } + + func testTruncate() { + XCTAssertEqual(truncate("short", 22), "short") + XCTAssertEqual(truncate("abcdefghij", 5), "abcd…") + XCTAssertEqual(truncate("abcdefghij", 1), "…") + XCTAssertEqual(truncate("abcde", 5), "abcde") + } + + func testHumanBytes() { + XCTAssertEqual(humanBytes(0), "0 B") + XCTAssertEqual(humanBytes(1023), "1023 B") + XCTAssertEqual(humanBytes(1024), "1 KB") + XCTAssertEqual(humanBytes(5 * 1_048_576), "5 MB") + XCTAssertEqual(humanBytes(1_610_612_736), "1.50 GB") + } +} diff --git a/swift/Tests/SimSlimCLITests/CloneCommandTests.swift b/swift/Tests/SimSlimCLITests/CloneCommandTests.swift new file mode 100644 index 0000000..b9350c7 --- /dev/null +++ b/swift/Tests/SimSlimCLITests/CloneCommandTests.swift @@ -0,0 +1,137 @@ +// Copyright (c) 2026 Pavel Akhrameev (Swift port). MIT License; see LICENSE. + +import Foundation +import SimSlimKit +import TestSupport +import XCTest + +@testable import SimSlimCLI + +final class CloneCommandTests: XCTestCase { + private let src = "AAAAAAAA-0000-0000-0000-000000000001" + private let dst = "BBBBBBBB-0000-0000-0000-000000000002" + private var root = "" + private let fm = FileManager.default + + override func setUpWithError() throws { + root = + try { + var buffer = [CChar](repeating: 0, count: Int(PATH_MAX) + 1) + guard realpath(NSTemporaryDirectory(), &buffer) != nil else { + throw CocoaError(.fileNoSuchFile) + } + return String(cString: buffer) + }() + "/simslim-clonecli-\(UUID().uuidString)" + try fm.createDirectory(atPath: root + "/store", withIntermediateDirectories: true) + try fm.createDirectory(atPath: "\(root)/devices/\(src)/data", withIntermediateDirectories: true) + } + + override func tearDown() { try? fm.removeItem(atPath: root) } + + private func host(clone: Bool = false) throws -> FakeHost { + var devices: [FakeHost.FakeDevice] = [.init(udid: src, name: "Source")] + if clone { + devices.append(.init(udid: dst, name: "Legacy")) + try fm.createDirectory( + atPath: "\(root)/devices/\(dst)/data", withIntermediateDirectories: true) + } + let host = FakeHost(devices: devices) + host.dataRoot = root + "/devices" + host.storeRoot = root + "/store" + host.disabled[src] = [] + host.cloneUDIDs = [dst] + host.psOutput = "10 /x SIMULATOR_UDID=\(dst)\n" + return host + } + + private func run(_ args: [String], _ host: FakeHost) -> CLIResult { + runCLI(args, host: host, storeRoot: root + "/store", home: root + "/home") + } + + func testCloneArgumentCountIsChecked() throws { + let host = try host() + for args in [["clone"], ["clone", src], ["clone", src, "a", "b"]] { + let r = run(args, host) + XCTAssertEqual(r.status, 1) + XCTAssertEqual(r.stderr, "simslim: clone expects a simulator UDID and a new name\n") + } + XCTAssertTrue(host.calls.isEmpty) + } + + func testRepairArgumentCountIsChecked() throws { + let host = try host(clone: true) + for args in [["repair-clone"], ["repair-clone", src], ["repair-clone", src, dst, "x"]] { + let r = run(args, host) + XCTAssertEqual(r.status, 1) + XCTAssertEqual( + r.stderr, "simslim: repair-clone expects the source UDID and cloned simulator UDID\n") + } + XCTAssertTrue(host.calls.isEmpty) + } + + func testAnInvalidNameFailsBeforeAnyCommand() throws { + let host = try host() + let r = run(["clone", src, " "], host) + XCTAssertEqual(r.status, 1) + XCTAssertEqual(r.stderr, "simslim: simulator name cannot be empty\n") + XCTAssertTrue(host.calls.isEmpty) + } + + func testCloneReportsTheNewSimulatorAndProgress() throws { + let host = try host() + let r = run(["clone", src, " Fast \"Phone\" "], host) + XCTAssertEqual(r.status, 0, r.stderr) + XCTAssertEqual(r.stdout, "Cloned \(src) as \"Fast \\\"Phone\\\"\" (\(dst)).\n") + XCTAssertTrue(r.stderr.contains("Cloning \(src)..."), r.stderr) + XCTAssertEqual(host.devices.first { $0.udid == dst }?.name, "Fast \"Phone\"") + } + + func testCloneJSONIsCleanAndMatchesTheContract() throws { + let host = try host() + let r = run(["clone", src, "Fast", "--json"], host) + XCTAssertEqual(r.status, 0, r.stderr) + XCTAssertEqual(r.stderr, "", "no progress chatter under --json") + let object = try JSONSerialization.jsonObject(with: Data(r.stdout.utf8)) as? [String: String] + XCTAssertEqual(object, ["action": "clone", "udid": dst, "name": "Fast", "sourceUdid": src]) + } + + func testRepairReportsAndPrintsJSON() throws { + let host = try host(clone: true) + host.disabled[dst] = [] + let r = run(["repair-clone", src, dst], host) + XCTAssertEqual(r.status, 0, r.stderr) + XCTAssertEqual( + r.stdout, + "Repaired clone \(dst) and verified no links or open files into specified source \(src).\n") + + let json = run(["repair-clone", src, dst, "--json"], try self.host(clone: true)) + XCTAssertEqual(json.status, 0, json.stderr) + XCTAssertEqual(json.stderr, "") + let object = try JSONSerialization.jsonObject(with: Data(json.stdout.utf8)) as? [String: String] + XCTAssertEqual(object, ["action": "repair-clone", "udid": dst, "sourceUdid": src]) + } + + func testAFailedCloneExitsOneWithTheMessage() throws { + let host = try host() + host.cloneFailure = "no space" + let r = run(["clone", src, "x"], host) + XCTAssertEqual(r.status, 1) + XCTAssertTrue(r.stderr.contains("simslim: xcrun simctl clone"), r.stderr) + XCTAssertTrue(r.stderr.contains("no space")) + XCTAssertEqual(r.stdout, "") + } + + func testAFailedRepairExitsOneAndPrintsNothingOnStdout() throws { + let host = try host(clone: true) + try fm.createSymbolicLink( + atPath: "\(root)/devices/\(dst)/data/bad", withDestinationPath: "/elsewhere/\(src)/f") + host.disabled[dst] = [] + let r = run(["repair-clone", src, dst], host) + XCTAssertEqual(r.status, 1) + XCTAssertEqual(r.stdout, "") + XCTAssertTrue(r.stderr.contains("still resolves into the source simulator"), r.stderr) + let quiet = run(["repair-clone", src, dst, "--json"], host) + XCTAssertEqual(quiet.status, 1) + XCTAssertFalse(quiet.stderr.contains("Shutting both"), "no progress under --json") + } +} diff --git a/swift/Tests/SimSlimCLITests/CommandTests.swift b/swift/Tests/SimSlimCLITests/CommandTests.swift new file mode 100644 index 0000000..6b76454 --- /dev/null +++ b/swift/Tests/SimSlimCLITests/CommandTests.swift @@ -0,0 +1,517 @@ +// Copyright (c) 2026 Pavel Akhrameev (Swift port). MIT License; see LICENSE. + +import SimSlimKit +import TestSupport +import XCTest + +@testable import SimSlimCLI + +final class DispatchTests: XCTestCase { + func testVersion() { + for arguments in [["version"], ["--version"], ["-v"]] { + let result = runCLI(arguments) + XCTAssertEqual(result.stdout, "simslim test-version\n") + XCTAssertEqual(result.status, 0) + } + } + + func testHelpAndNoArguments() { + for arguments in [["help"], ["--help"], ["-h"]] { + let result = runCLI(arguments) + XCTAssertEqual(result.status, 0) + XCTAssertTrue(result.stdout.hasPrefix("simslim runs more iOS")) + } + let none = runCLI([]) + XCTAssertEqual(none.status, 2) + XCTAssertTrue(none.stdout.hasPrefix("simslim runs more iOS")) + } + + func testUnknownCommandPrintsUsageAndExitsTwo() { + let result = runCLI(["bogus"]) + XCTAssertEqual(result.status, 2) + XCTAssertEqual(result.stderr, "unknown command \"bogus\"\n\n") + XCTAssertTrue(result.stdout.contains("COMMANDS")) + } + + func testEveryDispatchedCommandIsInTheUsageText() { + XCTAssertFalse(usageText.contains("†"), "no command is left unported") + for command in CLI.commandSpecs.keys { + XCTAssertTrue(usageText.contains(" \(command)"), "\(command) is missing from the usage text") + } + } + + func testGlobalOptionsMayPrecedeOrFollowTheCommand() { + let host = FakeHost(devices: [.init(udid: "A", name: "d")]) + host.sets["/custom"] = [.init(udid: "C", name: "custom one")] + for arguments in [ + ["--set", "/custom", "list"], ["list", "--set", "/custom"], ["list", "--set=/custom"], + ] { + let result = runCLI(arguments, host: host) + XCTAssertEqual(result.status, 0, "\(arguments)") + XCTAssertTrue(result.stdout.contains("custom one"), "\(arguments)") + XCTAssertTrue(result.stdout.contains("(/custom)"), "the set is shown for non-default sets") + } + } + + func testSetNeedsAValue() { + for arguments in [["list", "--set"], ["list", "--set", ""], ["list", "--set", " , "]] { + let result = runCLI(arguments) + XCTAssertEqual( + result.stderr, "simslim: --set requires a device set name (such as `testing`) or a path\n", + "\(arguments)") + XCTAssertEqual(result.status, 1) + } + } + + func testTimeoutOptions() { + let host = standardHost() + _ = runCLI(["status", bootedUDID, "--spawn-timeout", "5m"], host: host) + XCTAssertEqual(host.calls.last { $0.arguments.contains("print-disabled") }?.timeout, 300) + + let envHost = standardHost() + _ = runCLI( + ["status", bootedUDID], host: envHost, environment: ["SIMSLIM_SPAWN_TIMEOUT": "90s"]) + XCTAssertEqual(envHost.calls.last { $0.arguments.contains("print-disabled") }?.timeout, 90) + + let defaultHost = standardHost() + _ = runCLI(["status", bootedUDID], host: defaultHost) + XCTAssertEqual(defaultHost.calls.last { $0.arguments.contains("print-disabled") }?.timeout, 120) + + let flagWins = standardHost() + _ = runCLI( + ["status", bootedUDID, "--spawn-timeout", "10s"], host: flagWins, + environment: ["SIMSLIM_SPAWN_TIMEOUT": "90s"]) + XCTAssertEqual(flagWins.calls.last { $0.arguments.contains("print-disabled") }?.timeout, 10) + } + + func testInvalidTimeouts() { + var result = runCLI(["profiles", "--boot-timeout", "0"]) + XCTAssertEqual( + result.stderr, "simslim: --boot-timeout must be a positive duration (such as `15m`)\n") + result = runCLI(["profiles", "--spawn-timeout", "-1m"]) + XCTAssertEqual( + result.stderr, "simslim: --spawn-timeout must be a positive duration (such as `2m`)\n") + result = runCLI(["profiles", "--boot-timeout", "soon"]) + XCTAssertEqual( + result.stderr, + "simslim: invalid value \"soon\" for flag -boot-timeout: time: invalid duration \"soon\"\n") + result = runCLI(["profiles"], environment: ["SIMSLIM_BOOT_TIMEOUT": "nope"]) + XCTAssertEqual(result.status, 1, "a bad environment value is an error too") + } + + func testUnknownFlagAndArgumentCountErrors() { + XCTAssertEqual( + runCLI(["list", "--nope"]).stderr, "simslim: flag provided but not defined: -nope\n") + XCTAssertEqual(runCLI(["list", "x"]).stderr, "simslim: list takes no arguments\n") + XCTAssertEqual( + runCLI(["status"]).stderr, + "simslim: expected exactly one simulator UDID (see `simslim list`)\n") + XCTAssertEqual( + runCLI(["status", "a", "b"]).stderr, + "simslim: expected exactly one simulator UDID (see `simslim list`)\n") + XCTAssertEqual( + runCLI(["profiles", "a", "b"]).stderr, + "simslim: profiles takes at most one category ID (see `simslim profiles`)\n") + } +} + +final class ListCommandTests: XCTestCase { + func testHumanOutputIsSortedAndShowsSlimStatus() { + let result = runCLI(["list"], host: standardHost()) + XCTAssertEqual(result.status, 0) + let lines = result.stdout.split(separator: "\n").map(String.init) + XCTAssertEqual(lines.count, 3) + // iOS first, newest version first: 27.2 (iPad Air, iPhone 17 by name) then 18.4. + XCTAssertEqual( + lines[0], "\(shutdownUDID) \(padRight("iPad Air", 22)) \(padRight("iOS 27.2", 14)) shutdown") + XCTAssertEqual( + lines[1], + "\(bootedUDID) \(padRight("iPhone 17", 22)) \(padRight("iOS 27.2", 14)) booted · 100/173 slim" + ) + XCTAssertEqual( + lines[2], + "\(oldUDID) \(padRight("iPhone 16", 22)) \(padRight("iOS 18.4", 14)) booted · 0/173 slim") + } + + func testBootedFilter() { + let result = runCLI(["list", "--booted"], host: standardHost()) + XCTAssertEqual(result.stdout.split(separator: "\n").count, 2) + XCTAssertFalse(result.stdout.contains(shutdownUDID)) + } + + func testShutdownDevicesAreNeverSpawnedInto() { + let host = standardHost() + _ = runCLI(["list"], host: host) + let spawned = host.calls.filter { $0.arguments.contains("spawn") }.compactMap { + $0.arguments[safe: 2] + } + XCTAssertFalse(spawned.contains(shutdownUDID)) + XCTAssertEqual(Set(spawned), [bootedUDID, oldUDID]) + } + + func testLongNamesAreTruncatedInHumanOutput() { + let host = FakeHost(devices: [.init(udid: "A", name: String(repeating: "x", count: 40))]) + let result = runCLI(["list"], host: host) + XCTAssertTrue(result.stdout.contains(String(repeating: "x", count: 21) + "…")) + XCTAssertFalse(result.stdout.contains(String(repeating: "x", count: 22))) + } + + func testAStatusFailureDoesNotFailTheListing() throws { + let host = standardHost() + host.queueSpawnResults( + udid: bootedUDID, + Array(repeating: CommandResult(status: 2, stderr: Data("denied".utf8)), count: 1)) + let human = runCLI(["list"], host: host) + XCTAssertEqual(human.status, 0) + XCTAssertTrue( + human.stdout.contains("\(padRight("iOS 27.2", 14)) booted\n"), + "tag falls back to plain booted") + + let jsonHost = standardHost() + jsonHost.queueSpawnResults( + udid: bootedUDID, [CommandResult(status: 2, stderr: Data("denied".utf8))]) + let json = runCLI(["list", "--json"], host: jsonHost) + let rows = try XCTUnwrap( + JSONSerialization.jsonObject(with: Data(json.stdout.utf8)) as? [[String: Any]]) + let row = try XCTUnwrap(rows.first { $0["udid"] as? String == bootedUDID }) + XCTAssertTrue((row["statusError"] as? String ?? "").contains("denied")) + XCTAssertNil(row["managedDisabled"]) + } + + func testJSONShape() throws { + let result = runCLI(["list", "--json"], host: standardHost()) + XCTAssertEqual(result.status, 0) + XCTAssertTrue(result.stdout.hasSuffix("\n")) + let rows = try XCTUnwrap( + JSONSerialization.jsonObject(with: Data(result.stdout.utf8)) as? [[String: Any]]) + XCTAssertEqual(rows.count, 3) + + let booted = try XCTUnwrap(rows.first { $0["udid"] as? String == bootedUDID }) + XCTAssertEqual(booted["managedDisabled"] as? Int, 100) + XCTAssertEqual(booted["managedTotal"] as? Int, 173) + XCTAssertEqual(booted["platform"] as? String, "iOS") + XCTAssertEqual(booted["osVersion"] as? String, "27.2") + XCTAssertEqual(booted["set"] as? String, "default") + let memory = try XCTUnwrap(booted["memory"] as? [String: Any]) + XCTAssertEqual(memory["processes"] as? Int, 2) + XCTAssertEqual(memory["bytes"] as? Int, 30 * 1_048_576) + XCTAssertNil(booted["dataPath"], "internal fields never leak") + XCTAssertNil(booted["runtimeID"]) + + let shutdown = try XCTUnwrap(rows.first { $0["udid"] as? String == shutdownUDID }) + XCTAssertNil(shutdown["managedDisabled"], "unknown while shut down") + XCTAssertNil(shutdown["memory"]) + XCTAssertEqual(shutdown["managedTotal"] as? Int, 173) + } + + func testJSONOfAnEmptyListIsAnEmptyArray() { + XCTAssertEqual(runCLI(["list", "--json"], host: FakeHost()).stdout, "[\n\n]\n") + } + + func testJSONMeasuresAllBootedDevicesWithOneSnapshot() { + let host = standardHost() + _ = runCLI(["list", "--json"], host: host) + XCTAssertEqual(host.calls.filter { $0.executable == .ps }.count, 1) + XCTAssertEqual(host.calls.filter { $0.executable == .top }.count, 1) + } + + func testHumanListDoesNotMeasureMemory() { + let host = standardHost() + _ = runCLI(["list"], host: host) + XCTAssertFalse(host.calls.contains { $0.executable == .ps || $0.executable == .top }) + } + + func testListFailureIsReported() { + let host = FakeHost() + host.listFailure = "CoreSimulator is down" + let result = runCLI(["list"], host: host) + XCTAssertEqual(result.status, 1) + XCTAssertEqual(result.stderr, "simslim: simctl list: exit status 1: CoreSimulator is down\n") + } +} + +final class ProfilesCommandTests: XCTestCase { + func testOverview() { + let result = runCLI(["profiles"]) + XCTAssertEqual(result.status, 0) + XCTAssertTrue(result.stdout.hasPrefix("widgets Widgets & Wallpaper\n")) + XCTAssertTrue( + result.stdout.contains(" 4 daemons · ~675 MB idle footprint when enabled\n")) + XCTAssertTrue( + result.stdout.contains( + " Always on: com.apple.assistantd — Hosts the dictation service; without it the system Spotlight app leaks memory.\n" + )) + XCTAssertTrue( + result.stdout.contains( + "\n173 daemons across 16 categories. Core workflow and deadlock-prone daemons are never disabled.\n" + )) + } + + func testOneCategory() { + let result = runCLI(["profiles", "search"]) + XCTAssertEqual(result.status, 0) + XCTAssertTrue(result.stdout.contains("search Spotlight & Search\n")) + XCTAssertTrue( + result.stdout.contains(" 5 daemons · ~50 MB idle footprint when enabled\n")) + XCTAssertTrue(result.stdout.contains("\nDaemons:\n")) + XCTAssertTrue(result.stdout.contains(" \(padRight("com.apple.searchd", 44)) ")) + } + + func testAlwaysEnabledLinesAppearInACategoryListing() { + XCTAssertTrue( + runCLI(["profiles", "siri"]).stdout.contains( + " \(padRight("com.apple.assistantd", 44)) Always on — Hosts the dictation service")) + } + + func testUnknownCategory() { + let result = runCLI(["profiles", "nope"]) + XCTAssertEqual(result.status, 1) + XCTAssertEqual(result.stderr, "simslim: unknown category \"nope\" (see `simslim profiles`)\n") + } + + func testJSON() throws { + let all = try XCTUnwrap( + JSONSerialization.jsonObject(with: Data(runCLI(["profiles", "--json"]).stdout.utf8)) + as? [[String: Any]]) + XCTAssertEqual(all.count, 16) + XCTAssertEqual(all.compactMap { $0["id"] as? String }.first, "widgets") + + let one = try XCTUnwrap( + JSONSerialization.jsonObject(with: Data(runCLI(["profiles", "siri", "--json"]).stdout.utf8)) + as? [String: Any]) + XCTAssertEqual(one["id"] as? String, "siri") + XCTAssertNotNil(one["alwaysEnabled"]) + } +} + +final class StatusCommandTests: XCTestCase { + func testHumanStatus() { + let result = runCLI(["status", bootedUDID], host: standardHost()) + XCTAssertEqual(result.status, 0) + XCTAssertEqual( + result.stdout, "\(bootedUDID): 100/173 managed launchd labels disabled (partially slim)\n") + } + + func testStockStatus() { + let result = runCLI(["status", oldUDID], host: standardHost()) + XCTAssertEqual(result.stdout, "\(oldUDID): 0/173 managed launchd labels disabled (stock)\n") + } + + func testSlimStatusOnANonPersistentRuntimeWarns() { + let host = standardHost() + host.disabled[oldUDID] = Profile().desired() // iOS 18.4 cannot persist overrides + let result = runCLI(["status", oldUDID], host: host) + XCTAssertTrue(result.stdout.contains("(slim)\n")) + XCTAssertTrue( + result.stdout.contains( + " This runtime cannot persist launchd overrides: the state reverts to stock at the next reboot.\n" + )) + } + + func testStatusOfAShutdownSimulatorFails() { + let result = runCLI(["status", shutdownUDID], host: standardHost()) + XCTAssertEqual(result.status, 1) + XCTAssertEqual( + result.stderr, "simslim: simulator must be booted to read its state (it is Shutdown)\n") + } + + func testUnknownUDID() { + let result = runCLI(["status", "nope"], host: standardHost()) + XCTAssertEqual(result.stderr, "simslim: no simulator with udid nope\n") + } + + func testDropped() { + let host = standardHost() + host.disabled[bootedUDID] = ["com.apple.searchd", "com.apple.PosterBoard"] + let result = runCLI(["status", bootedUDID, "--dropped"], host: host) + XCTAssertTrue( + result.stdout.contains(" widgets Widgets & Wallpaper — Home and Lock Screen widgets")) + XCTAssertTrue(result.stdout.contains(" com.apple.PosterBoard\n")) + XCTAssertTrue(result.stdout.contains(" search Spotlight & Search — ")) + + host.disabled[bootedUDID] = [] + XCTAssertTrue( + runCLI(["status", bootedUDID, "--dropped"], host: host).stdout.contains( + " Nothing dropped; every managed launchd label is enabled.\n")) + } + + func testJSON() throws { + let result = runCLI(["status", bootedUDID, "--json"], host: standardHost()) + let object = try XCTUnwrap( + JSONSerialization.jsonObject(with: Data(result.stdout.utf8)) as? [String: Any]) + XCTAssertEqual( + Set(object.keys), ["managedDisabled", "managedTotal", "booted", "persistent", "verdict"]) + XCTAssertEqual(object["verdict"] as? String, "partially slim") + XCTAssertEqual(object["managedDisabled"] as? Int, 100) + + let dropped = runCLI(["status", bootedUDID, "--json", "--dropped"], host: standardHost()) + let withDropped = try XCTUnwrap( + JSONSerialization.jsonObject(with: Data(dropped.stdout.utf8)) as? [String: Any]) + XCTAssertNotNil(withDropped["dropped"]) + } +} + +final class VerifyCommandTests: XCTestCase { + private func host(disabled: Set) -> FakeHost { + let host = standardHost() + host.disabled[bootedUDID] = disabled + return host + } + + func testMatchExitsZero() { + let result = runCLI(["verify", bootedUDID], host: host(disabled: Profile().desired())) + XCTAssertEqual(result.status, 0) + XCTAssertEqual( + result.stdout, + "\(bootedUDID) matches the profile: all expected disable overrides are applied.\n") + } + + func testDriftExitsOneAndListsIt() { + var disabled = Profile().desired() + disabled.remove("com.apple.apsd") + disabled.insert("com.apple.sharingd") // managed, disabled beyond the profile + disabled.insert("com.apple.unmanaged") // never drift + let result = runCLI(["verify", bootedUDID], host: host(disabled: disabled)) + XCTAssertEqual(result.status, 1) + XCTAssertEqual(result.stderr, "") + XCTAssertTrue( + result.stdout.hasPrefix("\(bootedUDID) does not match the profile (1 missing, 1 extra):\n")) + XCTAssertTrue( + result.stdout.contains(" missing com.apple.apsd (should be disabled, is enabled)\n")) + XCTAssertTrue( + result.stdout.contains(" extra com.apple.sharingd (disabled beyond the profile)\n")) + XCTAssertFalse(result.stdout.contains("unmanaged")) + XCTAssertTrue(result.stdout.hasSuffix("Re-run `simslim on` with the same profile to repair.\n")) + } + + func testExceptAndKeepFlagsDefineTheProfile() { + let profile = Profile(exceptCategories: ["search"], keep: ["com.apple.apsd"]) + let ok = runCLI( + ["verify", bootedUDID, "--except", "search", "--keep", "com.apple.apsd"], + host: host(disabled: profile.desired())) + XCTAssertEqual(ok.status, 0) + + // The same device no longer matches the default (full) profile. + XCTAssertEqual( + runCLI(["verify", bootedUDID], host: host(disabled: profile.desired())).status, 1) + } + + func testProfileFileCannotBeCombinedWithFlags() { + let result = runCLI( + ["verify", bootedUDID, "--profile", "x.json", "--except", "search"], host: standardHost()) + XCTAssertEqual(result.stderr, "simslim: --profile cannot be combined with --except or --keep\n") + XCTAssertEqual(result.status, 1) + } + + func testUnknownCategoryIsRejectedBeforeAnythingRuns() { + let host = standardHost() + let result = runCLI(["verify", bootedUDID, "--except", "nope"], host: host) + XCTAssertEqual(result.status, 1) + XCTAssertTrue(result.stderr.contains("unknown category \"nope\"")) + XCTAssertTrue(host.calls.isEmpty || !host.calls.contains { $0.arguments.contains("spawn") }) + } + + func testJSON() throws { + var disabled = Profile().desired() + disabled.remove("com.apple.apsd") + let result = runCLI(["verify", bootedUDID, "--json"], host: host(disabled: disabled)) + XCTAssertEqual(result.status, 1, "JSON output still signals drift through the exit status") + let object = try XCTUnwrap( + JSONSerialization.jsonObject(with: Data(result.stdout.utf8)) as? [String: Any]) + XCTAssertEqual(object["ok"] as? Bool, false) + XCTAssertEqual(object["missing"] as? [String], ["com.apple.apsd"]) + XCTAssertNil(object["extra"]) + } +} + +final class DoctorCommandTests: XCTestCase { + func testList() { + let result = runCLI(["doctor", "--list"]) + XCTAssertEqual(result.status, 0) + XCTAssertTrue( + result.stdout.hasPrefix( + "\(padRight("push", 16)) \(padRight("Push notifications", 38)) com.apple.apsd\n")) + XCTAssertEqual(result.stdout.split(separator: "\n").count, Catalog.features.count) + XCTAssertEqual( + runCLI(["doctor", "--list", "x"]).stderr, "simslim: doctor --list takes no arguments\n") + } + + func testRequiresIsMandatory() { + let result = runCLI(["doctor", bootedUDID], host: standardHost()) + XCTAssertEqual( + result.stderr, + "simslim: doctor needs at least one feature via --requires (see `simslim doctor --list`)\n") + XCTAssertEqual(result.status, 1) + } + + func testUnknownFeatureFailsLoudly() { + let result = runCLI(["doctor", bootedUDID, "--requires", "push,nope"], host: standardHost()) + XCTAssertEqual( + result.stderr, "simslim: unknown feature \"nope\" (see `simslim doctor --list`)\n") + } + + func testHealthyAndBroken() { + let healthy = standardHost() + healthy.disabled[bootedUDID] = [] + let ok = runCLI(["doctor", bootedUDID, "--requires", "push,storekit"], host: healthy) + XCTAssertEqual(ok.status, 0) + XCTAssertEqual( + ok.stdout, "\(bootedUDID): 2/2 required features OK\n ok push\n ok storekit\n") + + let broken = standardHost() + broken.disabled[bootedUDID] = ["com.apple.storekitd", "com.apple.passd"] + let bad = runCLI(["doctor", bootedUDID, "--requires", "push,storekit"], host: broken) + XCTAssertEqual(bad.status, 1) + XCTAssertTrue(bad.stdout.hasPrefix("\(bootedUDID): 1/2 required features OK\n ok push\n")) + XCTAssertTrue( + bad.stdout.contains(" BROKEN storekit — com.apple.storekitd, com.apple.passd disabled\n")) + } + + func testAFullSlimProfileBreaksPushWhichIsWhyDoctorExists() { + let host = standardHost() + host.disabled[bootedUDID] = Profile().desired() + XCTAssertEqual(runCLI(["doctor", bootedUDID, "--requires", "push"], host: host).status, 1) + host.disabled[bootedUDID] = Profile(exceptCategories: ["store"]).desired() + XCTAssertEqual(runCLI(["doctor", bootedUDID, "--requires", "push"], host: host).status, 0) + } + + func testJSON() throws { + let host = standardHost() + host.disabled[bootedUDID] = ["com.apple.apsd"] + let result = runCLI(["doctor", bootedUDID, "--requires", "push", "--json"], host: host) + XCTAssertEqual(result.status, 1) + let object = try XCTUnwrap( + JSONSerialization.jsonObject(with: Data(result.stdout.utf8)) as? [String: Any]) + XCTAssertEqual(object["udid"] as? String, bootedUDID) + XCTAssertEqual(object["ok"] as? Bool, false) + } +} + +final class MeasureCommandTests: XCTestCase { + func testHuman() { + let result = runCLI(["measure", bootedUDID], host: standardHost()) + XCTAssertEqual(result.status, 0) + XCTAssertEqual( + result.stdout, "\(bootedUDID): 2 processes, 30 MB memory footprint (phys_footprint)\n") + } + + func testJSON() throws { + let result = runCLI(["measure", bootedUDID, "--json"], host: standardHost()) + let object = try XCTUnwrap( + JSONSerialization.jsonObject(with: Data(result.stdout.utf8)) as? [String: Any]) + XCTAssertEqual(object["processes"] as? Int, 2) + XCTAssertEqual(object["bytes"] as? Int, 30 * 1_048_576) + XCTAssertEqual(object["cpu"] as? Double, 3.0) + } + + func testNotBooted() { + let result = runCLI(["measure", shutdownUDID], host: standardHost()) + XCTAssertEqual(result.status, 1) + XCTAssertEqual( + result.stderr, "simslim: simulator \(shutdownUDID) does not appear to be booted\n") + } +} + +extension Array { + fileprivate subscript(safe index: Int) -> Element? { indices.contains(index) ? self[index] : nil } +} diff --git a/swift/Tests/SimSlimCLITests/DiskCommandTests.swift b/swift/Tests/SimSlimCLITests/DiskCommandTests.swift new file mode 100644 index 0000000..9153c39 --- /dev/null +++ b/swift/Tests/SimSlimCLITests/DiskCommandTests.swift @@ -0,0 +1,298 @@ +// Copyright (c) 2026 Pavel Akhrameev (Swift port). MIT License; see LICENSE. + +import SimSlimKit +import TestSupport +import XCTest + +@testable import SimSlimCLI + +final class DiskCommandTests: XCTestCase { + private let udid = "AAAAAAAA-0000-0000-0000-000000000001" + private var root = "" + + override func setUpWithError() throws { + root = NSTemporaryDirectory() + "simslim-diskcli-\(UUID().uuidString)" + try FileManager.default.createDirectory(atPath: root, withIntermediateDirectories: true) + } + + override func tearDown() { + try? FileManager.default.removeItem(atPath: root) + } + + private var dataPath: String { "\(root)/\(udid)/data" } + + private func write(_ relative: String, size: Int = 8192) throws { + let path = "\(dataPath)/\(relative)" + try FileManager.default.createDirectory( + atPath: (path as NSString).deletingLastPathComponent, withIntermediateDirectories: true) + try Data(count: size).write(to: URL(fileURLWithPath: path)) + } + + private func exists(_ relative: String) -> Bool { + var info = stat() + return lstat("\(dataPath)/\(relative)", &info) == 0 + } + + private func host(state: String = "Shutdown") -> FakeHost { + let host = FakeHost(devices: [.init(udid: udid, name: "iPhone", state: state)]) + host.dataRoot = root + host.duKiB["\(root)/\(udid)"] = 100 + if state == "Booted" { host.disabled[udid] = [] } + return host + } + + private func subcommands(_ host: FakeHost) -> [String] { + host.calls.compactMap { $0.executable == .xcrun ? $0.arguments.dropFirst().first : nil } + } + + // MARK: - size + + func testSize() throws { + let host = host() + try FileManager.default.createDirectory( + atPath: dataPath, withIntermediateDirectories: true) + host.duKiB["\(root)/\(udid)"] = 6_710_886 // 6.40 GB + let r = runCLI(["size", udid], host: host) + XCTAssertEqual(r.status, 0, r.stderr) + XCTAssertEqual(r.stdout, "\(udid): 6.40 GB on disk\n") + let json = runCLI(["size", udid, "--json"], host: host) + let decoded = try JSONDecoder().decode( + SimulatorDiskMeasurement.self, from: Data(json.stdout.utf8)) + XCTAssertEqual(decoded.bytes, 6_710_886 * 1024) + } + + func testSizeNeedsAnExactUDID() { + XCTAssertEqual(runCLI(["size"], host: host()).status, 1) + let host = host() + let r = runCLI(["size", "all"], host: host) + XCTAssertEqual(r.stderr, "simslim: no simulator with udid all\n") + XCTAssertFalse(host.calls.contains { $0.executable == .du }) + } + + // MARK: - disk-categories + + func testCategoriesText() { + let r = runCLI(["disk-categories"], host: FakeHost()) + XCTAssertEqual(r.status, 0) + let lines = r.stdout.split(separator: "\n").map(String.init) + XCTAssertEqual(lines.count, 10) + XCTAssertEqual( + lines[0], "caches System & App Caches Lower risk · cleanable") + XCTAssertEqual( + lines[1], + " Next launches may be slower; downloaded or offline cache content can disappear." + ) + XCTAssertTrue(lines[8].hasPrefix("required-siri-assets Required Siri Assets")) + XCTAssertTrue(lines[8].hasSuffix("System managed · measured only")) + XCTAssertEqual( + runCLI(["disk-categories", "x"], host: FakeHost()).stderr, + "simslim: disk-categories takes no arguments\n") + } + + func testCategoriesDecodeAsTheAppsModel() throws { + let r = runCLI(["disk-categories", "--json"], host: FakeHost()) + let categories = try JSONDecoder().decode([DiskCleanupCategory].self, from: Data(r.stdout.utf8)) + XCTAssertEqual( + categories.map(\.id), + [ + "caches", "logs", "temporary", "linguistic-data", "required-siri-assets", + ]) + XCTAssertEqual(categories.filter(\.defaultSelected).map(\.id), ["caches", "logs", "temporary"]) + XCTAssertEqual(categories.filter { !$0.canClean }.map(\.id), ["required-siri-assets"]) + } + + // MARK: - disk-plan + + func testPlanDecodesAsTheAppsModelAndPrintsATable() throws { + try write("Library/Caches/c.bin", size: 100_000) + try write("Containers/Bundle/Application/APP/Example.app/Example", size: 50_000) + try write("Containers/Data/Application/D/Documents/d.bin", size: 30_000) + let host = host() + let json = runCLI(["disk-plan", "--json", udid], host: host) + XCTAssertEqual(json.status, 0, json.stderr) + let plan = try JSONDecoder().decode(SimulatorDiskCleanupPlan.self, from: Data(json.stdout.utf8)) + XCTAssertEqual(plan.udid, udid) + XCTAssertGreaterThan(plan.bytes(for: "caches"), 100_000 - 1) + XCTAssertGreaterThan(plan.storageBytes(for: "installed-apps"), 50_000 - 1) + XCTAssertGreaterThan(plan.storageBytes(for: "documents"), 30_000 - 1) + XCTAssertEqual(plan.cleanableBytes, plan.bytes(for: "caches")) + + let text = runCLI(["disk-plan", udid], host: host) + XCTAssertTrue(text.stdout.hasPrefix("\(udid): ")) + XCTAssertTrue(text.stdout.contains(" currently cleanable\n")) + XCTAssertTrue(text.stdout.contains(" caches ")) + XCTAssertTrue(text.stdout.contains("(iOS-managed; measured only)")) + XCTAssertTrue(text.stdout.contains(" Stored data (read only)\n")) + XCTAssertTrue(text.stdout.contains(" installed-apps ")) + XCTAssertTrue(plan.categories.count == 5 && plan.storage.count == 4) + } + + func testPlanChangesNothing() throws { + try write("Library/Caches/c.bin") + let host = host() + XCTAssertEqual(runCLI(["disk-plan", udid], host: host).status, 0) + XCTAssertTrue(exists("Library/Caches/c.bin")) + XCTAssertFalse(subcommands(host).contains("shutdown")) + } + + // MARK: - disk-clean + + func testCleanNeedsConfirmBeforeAnything() throws { + try write("Library/Caches/c.bin") + let host = host(state: "Booted") + let r = runCLI(["disk-clean", udid, "--categories", "caches"], host: host) + XCTAssertEqual(r.status, 1) + XCTAssertEqual( + r.stderr, + "simslim: disk-clean permanently deletes data; pass --confirm after reviewing `simslim disk-plan \(udid)`\n" + ) + XCTAssertTrue(host.calls.isEmpty, "not even a lookup") + XCTAssertTrue(exists("Library/Caches/c.bin")) + } + + func testCleanValidatesTheSelectionBeforeShuttingDownAnything() throws { + try write("Library/Caches/c.bin") + for (args, message) in [ + ([], "select at least one cleanable disk category"), + (["--categories", "nope"], "unknown disk cleanup category \"nope\""), + (["--categories", "required-siri-assets"], "measured only and cannot be cleaned"), + (["--categories", "caches,required-siri-assets"], "measured only"), + ] as [([String], String)] { + let host = host(state: "Booted") + let r = runCLI(["disk-clean", udid, "--confirm"] + args, host: host) + XCTAssertEqual(r.status, 1, "\(args)") + XCTAssertTrue(r.stderr.contains(message), r.stderr) + XCTAssertFalse(subcommands(host).contains("shutdown"), "\(args)") + XCTAssertTrue(exists("Library/Caches/c.bin")) + } + } + + func testCleanShutsTheSimulatorDownBeforeDeletingAndLeavesItOff() throws { + try write("Library/Caches/c.bin") + let host = host(state: "Booted") + let atShutdown = Box() + host.onCall = { _, args in + if args.contains("shutdown") { atShutdown.set(self.exists("Library/Caches/c.bin")) } + } + let r = runCLI( + ["disk-clean", udid, "--confirm", "--categories", "caches", "--json"], host: host) + XCTAssertEqual(r.status, 0, r.stderr) + XCTAssertEqual(atShutdown.value, true, "nothing was deleted before the shutdown") + XCTAssertFalse(exists("Library/Caches/c.bin")) + XCTAssertEqual(host.devices[0].state, "Shutdown") + let result = try JSONDecoder().decode( + SimulatorDiskCleanupResult.self, from: Data(r.stdout.utf8)) + XCTAssertEqual(result.categoryIds, ["caches"]) + XCTAssertTrue(result.wasBooted) + XCTAssertFalse(result.bootStateRestored) + XCTAssertGreaterThan(result.reclaimedBytes, 0) + XCTAssertEqual(result.reclaimedBytes, result.beforeBytes - result.afterBytes) + } + + func testPreserveBootStateBootsItAgain() throws { + try write("Library/Caches/c.bin") + let host = host(state: "Booted") + let r = runCLI( + [ + "disk-clean", udid, "--confirm", "--categories", "caches", "--preserve-boot-state", + "--json", + ], + host: host) + XCTAssertEqual(r.status, 0, r.stderr) + XCTAssertEqual(host.devices[0].state, "Booted") + let result = try JSONDecoder().decode( + SimulatorDiskCleanupResult.self, from: Data(r.stdout.utf8)) + XCTAssertTrue(result.wasBooted) + XCTAssertTrue(result.bootStateRestored) + } + + func testAShutdownSimulatorIsNotBootedByPreserveBootState() throws { + try write("Library/Caches/c.bin") + let host = host(state: "Shutdown") + let r = runCLI( + ["disk-clean", udid, "--confirm", "--categories", "caches", "--preserve-boot-state"], + host: host) + XCTAssertEqual(r.status, 0, r.stderr) + XCTAssertEqual(host.devices[0].state, "Shutdown") + XCTAssertFalse(subcommands(host).contains("boot")) + XCTAssertTrue(r.stdout.hasPrefix("Cleaned \(udid) and reclaimed ")) + XCTAssertTrue(r.stdout.hasSuffix("on-demand assets may download again when needed.\n")) + } + + func testNothingIsDeletedWhenTheShutdownFails() throws { + try write("Library/Caches/c.bin") + let host = host(state: "Booted") + host.shutdownFailure = "cannot shut down" + let r = runCLI(["disk-clean", udid, "--confirm", "--categories", "caches"], host: host) + XCTAssertEqual(r.status, 1) + XCTAssertTrue(r.stderr.contains("cannot shut down")) + XCTAssertTrue(exists("Library/Caches/c.bin"), "the simulator is still running on these files") + } + + func testAFailedRebootIsReportedButTheCleanupStands() throws { + try write("Library/Caches/c.bin") + let host = host(state: "Booted") + host.bootFailure = "boot refused" + let r = runCLI( + ["disk-clean", udid, "--confirm", "--categories", "caches", "--preserve-boot-state"], + host: host) + XCTAssertEqual(r.status, 1) + XCTAssertTrue( + r.stderr.contains("disk cleanup finished, but could not restore boot state: "), r.stderr) + XCTAssertFalse(exists("Library/Caches/c.bin")) + } + + func testCleanNeverReachesAnAliasOrAnyPath() throws { + try write("Library/Caches/c.bin") + for target in ["all", "booted", "..", "/", "\(udid)/.."] { + let host = host(state: "Booted") + let r = runCLI(["disk-clean", target, "--confirm", "--categories", "caches"], host: host) + XCTAssertEqual(r.status, 1, target) + XCTAssertFalse(subcommands(host).contains("shutdown"), target) + } + XCTAssertTrue(exists("Library/Caches/c.bin")) + } + + func testCleanRefusesADataDirectoryThatIsASymlink() throws { + try FileManager.default.createDirectory( + atPath: root + "/elsewhere/Library/Caches", withIntermediateDirectories: true) + try Data(count: 4096).write(to: URL(fileURLWithPath: root + "/elsewhere/Library/Caches/x.bin")) + try FileManager.default.createDirectory( + atPath: "\(root)/\(udid)", withIntermediateDirectories: true) + try FileManager.default.createSymbolicLink( + atPath: dataPath, withDestinationPath: root + "/elsewhere") + let host = host(state: "Booted") + let r = runCLI(["disk-clean", udid, "--confirm", "--categories", "caches"], host: host) + XCTAssertEqual(r.status, 1) + XCTAssertTrue(r.stderr.contains("simulator data path is not a real directory"), r.stderr) + XCTAssertFalse(subcommands(host).contains("shutdown")) + XCTAssertTrue(FileManager.default.fileExists(atPath: root + "/elsewhere/Library/Caches/x.bin")) + } + + func testCleanOnlyTouchesTheRequestedCategories() throws { + try write("Library/Caches/c.bin") + try write("Library/Logs/l.log") + try write("Containers/Data/Application/A/tmp/t.bin") + let r = runCLI( + ["disk-clean", udid, "--confirm", "--categories", "logs"], host: host(state: "Shutdown")) + XCTAssertEqual(r.status, 0, r.stderr) + XCTAssertFalse(exists("Library/Logs/l.log")) + XCTAssertTrue(exists("Library/Caches/c.bin")) + XCTAssertTrue(exists("Containers/Data/Application/A/tmp/t.bin")) + } +} + +private final class Box: @unchecked Sendable { + private let lock = NSLock() + private var stored: Bool? + func set(_ value: Bool) { + lock.lock() + stored = value + lock.unlock() + } + var value: Bool? { + lock.lock() + defer { lock.unlock() } + return stored + } +} diff --git a/swift/Tests/SimSlimCLITests/GUIContract/Models.swift b/swift/Tests/SimSlimCLITests/GUIContract/Models.swift new file mode 120000 index 0000000..1d09b67 --- /dev/null +++ b/swift/Tests/SimSlimCLITests/GUIContract/Models.swift @@ -0,0 +1 @@ +../../../../gui/Models.swift \ No newline at end of file diff --git a/swift/Tests/SimSlimCLITests/GUIContractTests.swift b/swift/Tests/SimSlimCLITests/GUIContractTests.swift new file mode 100644 index 0000000..81433e4 --- /dev/null +++ b/swift/Tests/SimSlimCLITests/GUIContractTests.swift @@ -0,0 +1,100 @@ +// Copyright (c) 2026 Pavel Akhrameev (Swift port). MIT License; see LICENSE. + +import SimSlimKit +import TestSupport +import XCTest + +@testable import SimSlimCLI + +/// `Models.swift` is the macOS app's own file (symlinked from gui/). Decoding the +/// Swift CLI's JSON with those exact types is the contract check: if an output +/// field is renamed, dropped or retyped, this fails instead of the app at runtime. +final class GUIContractTests: XCTestCase { + private func decode( + _ type: T.Type, _ arguments: [String], host: FakeHostFactory = .standard + ) throws -> T { + let result = runCLI(arguments, host: host.make()) + XCTAssertEqual(result.status, 0, result.stderr) + return try JSONDecoder().decode(type, from: Data(result.stdout.utf8)) + } + + func testListDecodesAsTheAppsSimulatorDevice() throws { + let devices = try decode([SimulatorDevice].self, ["list", "--json"]) + XCTAssertEqual(devices.count, 3) + + let booted = try XCTUnwrap(devices.first { $0.udid == bootedUDID }) + XCTAssertTrue(booted.isBooted) + XCTAssertEqual(booted.name, "iPhone 17") + XCTAssertEqual(booted.runtimeName, "iOS 27.2") + XCTAssertEqual(booted.managedDisabled, 100) + XCTAssertEqual(booted.managedTotal, 173) + XCTAssertEqual(booted.memory?.processes, 2) + XCTAssertEqual(booted.memory?.bytes, 30 * 1_048_576) + XCTAssertNil(booted.statusError) + + let shutdown = try XCTUnwrap(devices.first { $0.udid == shutdownUDID }) + XCTAssertFalse(shutdown.isBooted) + XCTAssertNil(shutdown.managedDisabled) + XCTAssertNil(shutdown.memory) + } + + func testProfilesDecodeAsTheAppsSlimCategory() throws { + let categories = try decode([SlimCategory].self, ["profiles", "--json"]) + XCTAssertEqual(categories.count, 16) + for category in categories { + XCTAssertFalse(category.labels.isEmpty, category.id) + XCTAssertGreaterThan(category.approxMemoryMB, 0, category.id) + for label in category.labels { + XCTAssertNotEqual( + category.serviceDescription(for: label), "Apple background service.", + "\(category.id): \(label) has no description, so the app would show its placeholder") + } + } + let siri = try XCTUnwrap(categories.first { $0.id == "siri" }) + XCTAssertEqual(siri.alwaysEnabledServices.map(\.label), ["com.apple.assistantd"]) + XCTAssertEqual(categories.first { $0.id == "search" }?.alwaysEnabledServices.count, 0) + } + + func testOneCategoryDecodes() throws { + let category = try decode(SlimCategory.self, ["profiles", "apps", "--json"]) + XCTAssertEqual(category.id, "apps") + XCTAssertEqual(category.alwaysEnabledServices.first?.label, "com.apple.gamed") + } + + func testMeasureDecodesAsTheAppsMeasurement() throws { + let measurement = try decode(SimulatorMeasurement.self, ["measure", bootedUDID, "--json"]) + XCTAssertEqual(measurement.processes, 2) + XCTAssertEqual(measurement.bytes, 30 * 1_048_576) + } + + func testBootAndShutdownDecodeAsTheAppsMutationResult() throws { + let boot = try decode(SimulatorMutationResult.self, ["boot", "--json", shutdownUDID]) + XCTAssertEqual(boot.action, "boot") + XCTAssertEqual(boot.udid, shutdownUDID) + + let down = try decode(SimulatorMutationResult.self, ["shutdown", "--json", bootedUDID]) + XCTAssertEqual(down.action, "shutdown") + XCTAssertEqual(down.udid, bootedUDID) + } + + /// The app reads stdout and stderr through one pipe, so anything on stderr + /// under --json would corrupt the JSON it decodes. + func testJSONCommandsTheAppCallsKeepStderrEmpty() { + let calls: [[String]] = [ + ["list", "--json"], ["profiles", "--json"], ["measure", "--json", bootedUDID], + ["boot", "--json", shutdownUDID], ["shutdown", "--json", bootedUDID], + ["disk-categories", "--json"], + ] + for arguments in calls { + let result = runCLI(arguments, host: FakeHostFactory.standard.make()) + XCTAssertEqual(result.status, 0, "\(arguments): \(result.stderr)") + XCTAssertEqual(result.stderr, "", "\(arguments) wrote to stderr under --json") + } + } +} + +/// Builds a fresh standard host per call (FakeHost is stateful). +struct FakeHostFactory { + var make: () -> FakeHost + static let standard = FakeHostFactory(make: standardHost) +} diff --git a/swift/Tests/SimSlimCLITests/LiveCommandTests.swift b/swift/Tests/SimSlimCLITests/LiveCommandTests.swift new file mode 100644 index 0000000..d99d927 --- /dev/null +++ b/swift/Tests/SimSlimCLITests/LiveCommandTests.swift @@ -0,0 +1,162 @@ +// Copyright (c) 2026 Pavel Akhrameev (Swift port). MIT License; see LICENSE. + +import SimSlimKit +import TestSupport +import XCTest + +@testable import SimSlimCLI + +final class LiveCommandTests: XCTestCase { + private let udid = "AAAAAAAA-0000-0000-0000-000000000001" + private var root = "" + + override func setUpWithError() throws { + root = NSTemporaryDirectory() + "simslim-livecli-\(UUID().uuidString)" + try FileManager.default.createDirectory(atPath: root, withIntermediateDirectories: true) + } + + override func tearDown() { + try? FileManager.default.removeItem(atPath: root) + } + + private var search: [String] { Catalog.category(id: "search")!.labels } + + private func host(state: String = "Booted", disabled: Set = []) -> FakeHost { + let host = FakeHost(devices: [.init(udid: udid, name: "iPhone", state: state)]) + if state == "Booted" { + host.disabled[udid] = disabled + host.loaded[udid] = Set(search) // loaded but disabled: only the override is lifted + } + return host + } + + func testEnableWithNoUDIDOrNoIDs() { + let none = runCLI(["enable"], host: host()) + XCTAssertEqual(none.status, 1) + XCTAssertEqual( + none.stderr, + "simslim: expected a simulator UDID (see `simslim list`), then category IDs or launchd labels (see `simslim profiles`)\n" + ) + let noIDs = runCLI(["enable", udid], host: host()) + XCTAssertEqual(noIDs.status, 1) + XCTAssertTrue( + noIDs.stderr.contains("name at least one category ID or managed daemon to enable")) + } + + func testEnableTextOutput() { + let host = host(disabled: Set(search)) + let r = runCLI(["enable", udid, "search"], host: host) + XCTAssertEqual(r.status, 0, r.stderr) + XCTAssertEqual( + r.stdout, + "Enabled \(search.count) services on \(udid) without a reboot.\n" + + "This lasts until the next `on` or `watch` pass; pass --save to keep it in a profile.\n" + ) + XCTAssertTrue(r.stderr.contains("Starting \(search.count) background services")) + } + + func testIDsMayBeCommaSeparatedOrRepeated() { + let host = host(disabled: Set(search)) + let r = runCLI(["enable", udid, "search,siri", "search"], host: host, storeRoot: root) + XCTAssertEqual(r.status, 0, r.stderr) + let siri = Catalog.category(id: "siri")!.labels + XCTAssertTrue(r.stdout.hasPrefix("Enabled \(Set(search + siri).count) services"), r.stdout) + } + + func testEnableJSONIsCleanAndQuiet() throws { + let host = host(disabled: Set(search)) + let r = runCLI(["enable", udid, "search", "--json"], host: host) + XCTAssertEqual(r.status, 0, r.stderr) + XCTAssertEqual(r.stderr, "") + let out = try JSONDecoder().decode(ServicesOutput.self, from: Data(r.stdout.utf8)) + XCTAssertEqual(out.action, "enable") + XCTAssertTrue(out.live) + XCTAssertEqual(out.labels, search.sorted()) + XCTAssertFalse(r.stdout.contains("notStarted"), "omitted when empty") + XCTAssertFalse(r.stdout.contains("saved")) + } + + func testDisableJSONKeepsLabelsAsAnEmptyArray() { + let host = host() + let label = Catalog.managedSet.subtracting(Catalog.slimmableSet).sorted()[0] + XCTAssertEqual(runCLI(["disable", udid, label, "--json"], host: host).status, 1) + // A shutdown simulator with --save: nothing live, labels is still `[]`. + let shut = self.host(state: "Shutdown") + let r = runCLI( + ["disable", udid, "search", "--json", "--save", root + "/p.json"], host: shut) + XCTAssertEqual(r.status, 0, r.stderr) + XCTAssertTrue( + r.stdout.contains("\"labels\" : [\n\n ]") || r.stdout.contains("\"labels\" : [ ]") + || r.stdout.contains("\"labels\" : []"), r.stdout) + XCTAssertTrue(r.stdout.contains("\"live\" : false")) + } + + func testDisableTextOutputAndNothingToStop() { + let host = host() + host.loaded[udid] = Set(search) + let r = runCLI(["disable", udid, "search"], host: host) + XCTAssertEqual(r.status, 0, r.stderr) + XCTAssertTrue( + r.stdout.hasPrefix("Stopped \(search.count) services on \(udid) without a reboot.\n")) + } + + func testSaveMessages() { + let live = runCLI( + ["enable", udid, "search", "--save", root + "/a.json"], + host: host(disabled: Set(search))) + XCTAssertEqual(live.status, 0, live.stderr) + XCTAssertTrue( + live.stdout.hasSuffix( + "Saved to \(root)/a.json. Apply it later with `simslim on \(udid) --profile \(root)/a.json`.\n" + ), live.stdout) + let off = runCLI( + ["enable", udid, "search", "--save", root + "/b.json"], host: host(state: "Shutdown")) + XCTAssertEqual(off.status, 0, off.stderr) + XCTAssertEqual( + off.stdout, + "Saved to \(root)/b.json; nothing was applied, the simulator is not booted. Apply it with `simslim on \(udid) --profile \(root)/b.json`.\n" + ) + } + + func testAliasAndExtraFlagsAreRejected() { + XCTAssertEqual(runCLI(["enable", "all", "search"], host: host()).status, 1) + XCTAssertEqual(runCLI(["disable", "booted", "search"], host: host()).status, 1) + XCTAssertEqual(runCLI(["enable", udid, "search", "--no-such"], host: host()).status, 1) + } + + func testDisableNothingToStopAndStillEnabledLines() { + let watch = FakeHost(devices: [ + .init( + udid: udid, name: "Watch", runtime: "com.apple.CoreSimulator.SimRuntime.watchOS-11-5", + state: "Booted") + ]) + watch.disabled[udid] = [] + watch.loaded[udid] = ["com.apple.homed"] + let r = runCLI(["disable", udid, "com.apple.homed"], host: watch) + XCTAssertEqual(r.status, 0, r.stderr) + XCTAssertEqual( + r.stdout, + "Nothing to stop on \(udid).\n" + + " 1 stay enabled for another fully enabled category or the platform: com.apple.homed\n" + + "This lasts until the next `on` or `watch` pass; pass --save to keep it in a profile.\n" + ) + } + + func testDisableSaveMessages() { + let host = host() + host.loaded[udid] = Set(search) + let live = runCLI(["disable", udid, "search", "--save", root + "/a.json"], host: host) + XCTAssertEqual(live.status, 0, live.stderr) + XCTAssertTrue( + live.stdout.hasSuffix( + "Saved to \(root)/a.json. Apply it later with `simslim on \(udid) --profile \(root)/a.json`.\n" + ), live.stdout) + } + + func testAnAliasSpawnsNothing() { + let host = host() + _ = runCLI(["enable", "all", "search"], host: host) + _ = runCLI(["disable", "booted", "search"], host: host) + XCTAssertFalse(host.calls.contains { $0.arguments.contains("spawn") }) + } +} diff --git a/swift/Tests/SimSlimCLITests/ManagementCommandTests.swift b/swift/Tests/SimSlimCLITests/ManagementCommandTests.swift new file mode 100644 index 0000000..75431e1 --- /dev/null +++ b/swift/Tests/SimSlimCLITests/ManagementCommandTests.swift @@ -0,0 +1,215 @@ +// Copyright (c) 2026 Pavel Akhrameev (Swift port). MIT License; see LICENSE. + +import SimSlimKit +import TestSupport +import XCTest + +@testable import SimSlimCLI + +final class ManagementCommandTests: XCTestCase { + fileprivate let udid = "AAAAAAAA-0000-0000-0000-000000000001" + + fileprivate func host(state: String = "Shutdown") -> FakeHost { + FakeHost(devices: [.init(udid: udid, name: "Old name", state: state)]) + } + + fileprivate func subcommands(_ host: FakeHost) -> [String] { + host.calls.compactMap { $0.executable == .xcrun ? $0.arguments.dropFirst().first : nil } + } + + // MARK: - rename + + func testRenameTrimsAndReports() { + let host = host() + let r = runCLI(["rename", udid, " Test \"Phone\" "], host: host) + XCTAssertEqual(r.status, 0, r.stderr) + XCTAssertEqual(r.stdout, "Renamed \(udid) to \"Test \\\"Phone\\\"\".\n") + XCTAssertEqual(host.devices[0].name, "Test \"Phone\"") + } + + func testRenameJSON() throws { + let r = runCLI(["rename", udid, "New", "--json"], host: host()) + XCTAssertEqual(r.status, 0, r.stderr) + let out = try JSONDecoder().decode(SimulatorMutationOutput.self, from: Data(r.stdout.utf8)) + XCTAssertEqual(out, SimulatorMutationOutput(action: "rename", udid: udid, name: "New")) + } + + func testRenameRejectsBadNamesBeforeAnyCommand() { + let tooLong = String(repeating: "x", count: 129) + for (name, message) in [ + (" ", "simulator name cannot be empty"), + (tooLong, "simulator name cannot exceed 128 characters"), + ("a\u{0007}b", "simulator name cannot contain control characters"), + ("a\nb", "simulator name cannot contain control characters"), + ] { + let host = host() + let r = runCLI(["rename", udid, name], host: host) + XCTAssertEqual(r.status, 1, name) + XCTAssertEqual(r.stderr, "simslim: \(message)\n", name) + XCTAssertFalse(subcommands(host).contains("rename"), name) + } + let ok = String(repeating: "é", count: 128) + XCTAssertEqual(runCLI(["rename", udid, ok], host: host()).status, 0, "128 characters is fine") + } + + func testRenameNeedsExactlyTwoArgumentsAndAnExactUDID() { + XCTAssertEqual( + runCLI(["rename", udid], host: host()).stderr, + "simslim: rename expects a simulator UDID and a new name\n") + XCTAssertEqual(runCLI(["rename", udid, "a", "b"], host: host()).status, 1) + let host = host() + XCTAssertEqual(runCLI(["rename", "all", "X"], host: host).status, 1) + XCTAssertFalse(subcommands(host).contains("rename")) + } + + // MARK: - erase / delete + + func testEraseShutsDownABootedSimulatorFirst() { + let host = host(state: "Booted") + let r = runCLI(["erase", udid], host: host) + XCTAssertEqual(r.status, 0, r.stderr) + XCTAssertEqual(r.stdout, "Erased simulator \(udid).\n") + let verbs = subcommands(host) + let shutdown = verbs.firstIndex(of: "shutdown") + let erase = verbs.firstIndex(of: "erase") + XCTAssertNotNil(shutdown) + XCTAssertNotNil(erase) + XCTAssertLessThan(shutdown!, erase!) + } + + func testEraseOfAShutdownSimulatorDoesNotShutDown() { + let host = host() + XCTAssertEqual(runCLI(["erase", udid, "--json"], host: host).status, 0) + XCTAssertFalse(subcommands(host).contains("shutdown")) + XCTAssertTrue(subcommands(host).contains("erase")) + } + + func testNothingIsErasedOrDeletedWhenTheShutdownFails() { + for command in ["erase", "delete"] { + let host = host(state: "Booted") + host.shutdownFailure = "cannot shut down" + let r = runCLI([command, udid], host: host) + XCTAssertEqual(r.status, 1, command) + XCTAssertTrue(r.stderr.contains("cannot shut down"), r.stderr) + XCTAssertFalse(subcommands(host).contains(command), "\(command) must not run") + XCTAssertEqual(host.devices.count, 1) + } + } + + func testNothingIsErasedOrDeletedWhenTheDeviceNeverReachesShutdown() { + for command in ["erase", "delete"] { + let host = host(state: "Booted") + host.stuckBooted = true + // The 30s wait is real time at the CLI, so use the library with a fake clock. + var ctl = Simctl(runner: host) + let clock = TestClock() + ctl.now = { clock.now } + ctl.sleep = { clock.advance($0) } + XCTAssertThrowsError( + try command == "erase" ? ctl.eraseDevice(udid: udid) : ctl.deleteDevice(udid: udid) + ) { + XCTAssertEqual("\($0)", "timed out waiting for \(udid) to shut down") + } + XCTAssertFalse(subcommands(host).contains(command)) + } + } + + func testEraseAndDeleteNeverReachAnAlias() { + for command in ["erase", "delete"] { + for target in ["all", "booted", "00000000-0000-0000-0000-000000000000"] { + let host = host(state: "Booted") + let r = runCLI([command, target], host: host) + XCTAssertEqual(r.status, 1, "\(command) \(target)") + XCTAssertEqual(r.stderr, "simslim: no simulator with udid \(target)\n") + XCTAssertFalse(subcommands(host).contains("shutdown"), "\(command) \(target)") + XCTAssertFalse(subcommands(host).contains(command), "\(command) \(target)") + } + } + } + + func testDeleteRemovesTheDevice() throws { + let host = host(state: "Booted") + let r = runCLI(["delete", udid, "--json"], host: host) + XCTAssertEqual(r.status, 0, r.stderr) + XCTAssertEqual( + try JSONDecoder().decode(SimulatorMutationOutput.self, from: Data(r.stdout.utf8)), + SimulatorMutationOutput(action: "delete", udid: udid)) + XCTAssertEqual(host.devices.count, 0) + XCTAssertEqual( + runCLI(["delete", udid], host: self.host()).stdout, "Deleted simulator \(udid).\n") + } + + func testManagementStaysInTheDevicesOwnSet() { + for token in ["testing", "/custom/set"] { + let extra: [String] = token == "testing" ? [] : ["--set", token] + for command in [["rename", udid, "N"], ["erase", udid], ["delete", udid]] { + let host = FakeHost(devices: []) + host.sets[token] = [.init(udid: udid, name: "d", state: "Booted")] + let r = runCLI(extra + command, host: host) + XCTAssertEqual(r.status, 0, "\(token) \(command): \(r.stderr)") + } + } + } + + func testAFailedSimctlCommandIsReportedWithItsOutput() { + let host = host() + host.managementFailure = "Unable to delete: in use" + let r = runCLI(["delete", udid], host: host) + XCTAssertEqual(r.status, 1) + XCTAssertEqual( + r.stderr, "simslim: xcrun simctl delete \(udid): exit status 1: Unable to delete: in use\n") + } +} + +extension ManagementCommandTests { + func testErasingOrDeletingADeviceThatIsNotSettledIsRefused() { + for command in ["erase", "delete"] { + for state in ["Booting", "Shutting Down", "Creating"] { + let host = FakeHost(devices: [.init(udid: udid, name: "d", state: state)]) + let r = runCLI([command, udid], host: host) + XCTAssertEqual(r.status, 1, "\(command) \(state)") + XCTAssertTrue(r.stderr.contains("wait until it is Booted or Shutdown"), r.stderr) + XCTAssertFalse(subcommands(host).contains(command)) + XCTAssertFalse(subcommands(host).contains("shutdown")) + } + } + } + + func testNamesTrimLikeGoAndDoNotTrimAZeroWidthSpace() { + let host = host() + XCTAssertEqual(runCLI(["rename", udid, "\u{3000}x\u{00A0}"], host: host).status, 0) + XCTAssertEqual(host.devices[0].name, "x") + // U+200B is not space to Go: it is a name. + XCTAssertEqual(runCLI(["rename", udid, "\u{200B}"], host: host).status, 0) + XCTAssertEqual(host.devices[0].name, "\u{200B}") + } + + func testGoQuoteMatchesStrconvQuote() { + XCTAssertEqual(goQuote("plain"), "\"plain\"") + XCTAssertEqual(goQuote("a\"b\\c"), "\"a\\\"b\\\\c\"") + XCTAssertEqual(goQuote("é 日本 👍"), "\"é 日本 👍\"") + XCTAssertEqual(goQuote("a\u{200D}b"), "\"a\\u200db\"") // zero-width joiner + XCTAssertEqual(goQuote("A\u{00A0}B"), "\"A\\u00a0B\"") // no-break space + XCTAssertEqual(goQuote("x\u{2028}"), "\"x\\u2028\"") + XCTAssertEqual(goQuote("\u{E000}"), "\"\\ue000\"") // private use + XCTAssertEqual(goQuote("\u{FEFF}"), "\"\\ufeff\"") + XCTAssertEqual(goQuote("\u{E0001}"), "\"\\U000e0001\"") // tag character, above U+FFFF + XCTAssertEqual(goQuote("\n\t\u{07}"), "\"\\n\\t\\a\"") + XCTAssertEqual(goQuote("👨\u{200D}👩"), "\"👨\\u200d👩\"") + } +} + +private final class TestClock: @unchecked Sendable { + private let lock = NSLock() + private var t = Date(timeIntervalSince1970: 2_000_000) + var now: Date { + lock.lock() + defer { lock.unlock() } + return t + } + func advance(_ s: TimeInterval) { + lock.lock() + t = t.addingTimeInterval(s) + lock.unlock() + } +} diff --git a/swift/Tests/SimSlimCLITests/MutationCommandTests.swift b/swift/Tests/SimSlimCLITests/MutationCommandTests.swift new file mode 100644 index 0000000..b15f0e2 --- /dev/null +++ b/swift/Tests/SimSlimCLITests/MutationCommandTests.swift @@ -0,0 +1,297 @@ +// Copyright (c) 2026 Pavel Akhrameev (Swift port). MIT License; see LICENSE. + +import SimSlimKit +import TestSupport +import XCTest + +@testable import SimSlimCLI + +final class MutationCommandTests: XCTestCase { + private let udid = "AAAAAAAA-0000-0000-0000-000000000001" + private var root = "" + + override func setUpWithError() throws { + root = NSTemporaryDirectory() + "simslim-cli-\(UUID().uuidString)" + try FileManager.default.createDirectory(atPath: root, withIntermediateDirectories: true) + } + + override func tearDown() { + try? FileManager.default.removeItem(atPath: root) + } + + private func host(state: String, runtime: String = "com.apple.CoreSimulator.SimRuntime.iOS-27-2") + -> FakeHost + { + let host = FakeHost(devices: [.init(udid: udid, name: "iPhone", runtime: runtime, state: state)] + ) + host.storeRoot = root + if state == "Booted" { host.disabled[udid] = [] } + return host + } + + private func run(_ args: [String], _ host: FakeHost) -> CLIResult { + runCLI(args, host: host, storeRoot: root) + } + + private func subcommands(_ host: FakeHost) -> [String] { + host.calls.compactMap { $0.executable == .xcrun ? $0.arguments.dropFirst().first : nil } + } + + // MARK: - boot / shutdown + + func testBootAnAlreadyBootedSimulatorDoesNothing() { + let host = host(state: "Booted") + let r = run(["boot", udid], host) + XCTAssertEqual(r.status, 0) + XCTAssertEqual(r.stdout, "Simulator \(udid) is already booted.\n") + XCTAssertFalse(subcommands(host).contains("boot")) + } + + func testBootJSONIsCleanAndQuiet() throws { + let host = host(state: "Shutdown") + let r = run(["boot", udid, "--json"], host) + XCTAssertEqual(r.status, 0) + XCTAssertEqual(r.stderr, "", "no progress chatter under --json") + let result = try JSONDecoder().decode( + SimulatorMutationOutput.self, from: Data(r.stdout.utf8)) + XCTAssertEqual(result, SimulatorMutationOutput(action: "boot", udid: udid)) + XCTAssertEqual(host.devices[0].state, "Booted") + } + + func testBootAnUnknownUDIDOrAliasNeverReachesSimctlBoot() { + for target in ["all", "booted", "00000000-0000-0000-0000-000000000000"] { + let host = host(state: "Shutdown") + let r = run(["boot", target], host) + XCTAssertEqual(r.status, 1, target) + XCTAssertEqual(r.stderr, "simslim: no simulator with udid \(target)\n") + XCTAssertFalse(subcommands(host).contains("boot"), target) + XCTAssertFalse(subcommands(host).contains("shutdown"), target) + } + } + + func testBootFailureIsReported() { + let host = host(state: "Shutdown") + host.bootFailure = "Unable to boot: no runtime" + let r = run(["boot", udid], host) + XCTAssertEqual(r.status, 1) + XCTAssertTrue(r.stderr.contains("simctl boot: exit status 1: Unable to boot: no runtime")) + } + + func testShutdownWaitsUntilShutdown() { + let host = host(state: "Booted") + let r = run(["shutdown", udid], host) + XCTAssertEqual(r.status, 0) + XCTAssertEqual(r.stdout, "Shut down \(udid).\n") + XCTAssertEqual(host.devices[0].state, "Shutdown") + } + + func testShutdownOfAShutdownSimulatorDoesNothing() { + let host = host(state: "Shutdown") + let r = run(["shutdown", udid, "--json"], host) + XCTAssertEqual(r.status, 0) + XCTAssertTrue(r.stdout.contains("\"action\" : \"shutdown\"")) + XCTAssertFalse(subcommands(host).contains("shutdown")) + } + + func testShutdownAliasNeverReachesSimctl() { + let host = host(state: "Booted") + XCTAssertEqual(run(["shutdown", "all"], host).status, 1) + XCTAssertFalse(subcommands(host).contains("shutdown")) + } + + // MARK: - on + + func testOnRejectsNoRebootWithPreserveBootStateBeforeAnyWork() { + let host = host(state: "Shutdown") + let r = run(["on", udid, "--no-reboot", "--preserve-boot-state"], host) + XCTAssertEqual(r.status, 1) + XCTAssertTrue(r.stderr.contains("--no-reboot cannot be combined with --preserve-boot-state")) + XCTAssertTrue(host.calls.isEmpty) + } + + func testOnValidatesTheProfileBeforeTouchingTheSimulator() { + let host = host(state: "Shutdown") + let r = run(["on", udid, "--except", "no-such-category"], host) + XCTAssertEqual(r.status, 1) + XCTAssertTrue(r.stderr.contains("unknown category \"no-such-category\"")) + XCTAssertTrue(host.calls.isEmpty) + XCTAssertEqual(run(["on", udid, "--profile", "x.json", "--keep", "a"], host).status, 1) + XCTAssertTrue(host.calls.isEmpty) + } + + func testOnSlimsAShutdownSimulatorAndBootsIt() { + let host = host(state: "Shutdown") + let r = run(["on", udid], host) + XCTAssertEqual(r.status, 0, r.stderr) + XCTAssertEqual(r.stdout, "Done. Simulator reconfigured slim and booted.\n") + XCTAssertTrue(r.stderr.hasPrefix("Slimming \(udid): disabling ")) + XCTAssertEqual(host.devices[0].state, "Booted") + XCTAssertEqual(host.disabled[udid]?.intersection(Catalog.managedSet), Profile().desired()) + } + + func testOnPreserveBootStateReturnsToShutdown() { + let host = host(state: "Shutdown") + let r = run(["on", udid, "--preserve-boot-state"], host) + XCTAssertEqual(r.status, 0, r.stderr) + XCTAssertEqual(r.stdout, "Done. Simulator reconfigured slim and returned to shutdown.\n") + XCTAssertEqual(host.devices[0].state, "Shutdown") + // The next boot comes up slim from the stored overrides. + XCTAssertEqual(run(["boot", udid], host).status, 0) + XCTAssertEqual(host.disabled[udid]?.intersection(Catalog.managedSet), Profile().desired()) + } + + func testOnPreserveBootStateStillShutsDownWhenTheOperationFails() { + let host = host(state: "Shutdown") + // The boot starts and the device stays Booted, but never becomes ready. + host.bootstatusFailure = "Unable to wait for boot" + let r = run(["on", udid, "--preserve-boot-state"], host) + XCTAssertEqual(r.status, 1) + XCTAssertTrue(r.stderr.contains("Unable to wait for boot"), r.stderr) + XCTAssertEqual(host.devices[0].state, "Shutdown", "the restore ran despite the failure") + XCTAssertTrue(subcommands(host).contains("shutdown")) + } + + func testOnReportsBothFailuresWhenTheShutdownRestoreFailsToo() { + let host = host(state: "Shutdown") + host.bootstatusFailure = "boot never ready" + host.shutdownFailure = "shutdown refused" + let r = run(["on", udid, "--preserve-boot-state"], host) + XCTAssertEqual(r.status, 1) + XCTAssertTrue( + r.stderr.hasSuffix( + "simslim: xcrun simctl bootstatus \(udid) -b: exit status 1: boot never ready; additionally could not " + + "restore original shutdown state: restore original shutdown state: " + + "simctl shutdown: exit status 1: shutdown refused\n"), r.stderr) + } + + func testOnlyTheRestoreFailingIsReportedOnItsOwn() { + let host = host(state: "Shutdown") + host.shutdownFailure = "shutdown refused" + let r = run(["on", udid, "--preserve-boot-state"], host) + XCTAssertEqual(r.status, 1) + XCTAssertTrue( + r.stderr.hasSuffix( + "simslim: restore original shutdown state: simctl shutdown: exit status 1: shutdown refused\n" + ), r.stderr) + } + + func testEveryMutationStaysInTheDeviceSetItLivesIn() { + // The fake only shows a device through its own --set, like simctl, so a + // command that lost the set would fail with "Invalid device". + for token in ["testing", "/custom/set"] { + let extra: [String] = token == "testing" ? [] : ["--set", token] + for state in ["Shutdown", "Booted"] { + let host = FakeHost(devices: []) + host.sets[token] = [.init(udid: udid, name: "iPhone", state: state)] + host.storeRoot = root + if state == "Booted" { host.disabled[udid] = [] } + for command in [["on"], ["on", "--no-reboot"], ["off"], ["boot"], ["shutdown"]] { + let r = runCLI( + extra + [command[0], udid] + command.dropFirst(), host: host, storeRoot: root) + XCTAssertEqual(r.status, 0, "\(token) \(state) \(command): \(r.stderr)") + } + } + } + } + + func testOnAlreadySlimChangesNothing() { + let host = host(state: "Booted") + host.disabled[udid] = Profile().desired() + let r = run(["on", udid], host) + XCTAssertEqual(r.status, 0, r.stderr) + XCTAssertEqual(r.stdout, "Already slim. Nothing to change.\n") + XCTAssertFalse(subcommands(host).contains("shutdown")) + } + + func testOnRefusesAnOldRuntimeAndSuggestsNoReboot() { + let host = host( + state: "Booted", runtime: "com.apple.CoreSimulator.SimRuntime.iOS-17-0") + let r = run(["on", udid], host) + XCTAssertEqual(r.status, 1) + XCTAssertTrue(r.stderr.contains("iOS 17.0 runtime cannot persist"), r.stderr) + XCTAssertTrue(r.stderr.contains("--no-reboot")) + XCTAssertFalse(subcommands(host).contains("shutdown")) + XCTAssertFalse(subcommands(host).contains("spawn")) + } + + func testOnNoRebootOnAnOldRuntimeSaysTheSlimIsLostAtReboot() { + let host = host( + state: "Booted", runtime: "com.apple.CoreSimulator.SimRuntime.iOS-17-0") + host.loaded[udid] = [] + let r = run(["on", udid, "--no-reboot"], host) + XCTAssertEqual(r.status, 0, r.stderr) + XCTAssertTrue( + r.stdout.contains("Done. Simulator slimmed for this boot session without a reboot.")) + XCTAssertTrue(r.stdout.contains("iOS 17.0 cannot persist overrides"), r.stdout) + XCTAssertFalse(subcommands(host).contains("shutdown")) + } + + func testOnExceptKeepsThatCategoryEnabled() { + let host = host(state: "Shutdown") + let r = run(["on", udid, "--except", "siri"], host) + XCTAssertEqual(r.status, 0, r.stderr) + let siri = Set(Catalog.category(id: "siri")!.labels) + let slim = host.disabled[udid]!.intersection(Catalog.managedSet) + XCTAssertTrue(slim.isDisjoint(with: siri.subtracting(Catalog.category(id: "store")!.labels))) + XCTAssertEqual(slim, Profile(exceptCategories: ["siri"]).desired()) + } + + // MARK: - off + + func testOffRestoresStockAndReboots() { + let host = host(state: "Booted") + host.disabled[udid] = Profile().desired() + let r = run(["off", udid], host) + XCTAssertEqual(r.status, 0, r.stderr) + XCTAssertEqual(r.stdout, "Done. All daemons re-enabled and simulator rebooted.\n") + XCTAssertEqual(host.disabled[udid]?.intersection(Catalog.managedSet), []) + XCTAssertEqual(host.devices[0].state, "Booted") + } + + func testOffAlreadyStock() { + let host = host(state: "Booted") + let r = run(["off", udid], host) + XCTAssertEqual(r.status, 0) + XCTAssertEqual(r.stdout, "Already stock. Nothing to change.\n") + XCTAssertFalse(subcommands(host).contains("shutdown")) + } + + func testOffWorksOnARuntimeWithoutPersistence() { + // Restoring stock is always allowed, even where slimming is refused. + let host = host( + state: "Booted", runtime: "com.apple.CoreSimulator.SimRuntime.iOS-17-0") + host.persistsOverrides = false + host.disabled[udid] = ["com.apple.unmanaged"] + let r = run(["off", udid], host) + XCTAssertEqual(r.status, 0, r.stderr) + XCTAssertEqual(r.stdout, "Already stock. Nothing to change.\n") + } + + func testOffPreserveBootStateOfAShutdownSimulator() { + let host = host(state: "Shutdown") + try? writeStoreLikeLaunchd(host, root: root, udid: udid, labels: Array(Profile().desired())) + let r = run(["off", udid, "--preserve-boot-state"], host) + XCTAssertEqual(r.status, 0, r.stderr) + XCTAssertEqual(r.stdout, "Done. All daemons re-enabled and simulator returned to shutdown.\n") + XCTAssertEqual(host.devices[0].state, "Shutdown") + } + + func testNoCommandAcceptsTwoUDIDs() { + for command in ["boot", "shutdown", "on", "off"] { + let r = run([command, udid, "other"], host(state: "Booted")) + XCTAssertEqual(r.status, 1, command) + XCTAssertTrue(r.stderr.contains("expected exactly one simulator UDID"), command) + } + } +} + +/// Writes a store the way launchd_sim would, independently of the code under test. +private func writeStoreLikeLaunchd(_ host: FakeHost, root: String, udid: String, labels: [String]) + throws +{ + let dir = root + "/com.apple.CoreSimulator.SimDevice.\(udid)" + try FileManager.default.createDirectory(atPath: dir, withIntermediateDirectories: true) + let dict = Dictionary(uniqueKeysWithValues: labels.map { ($0, true) }) + let data = try PropertyListSerialization.data(fromPropertyList: dict, format: .xml, options: 0) + try data.write(to: URL(fileURLWithPath: dir + "/disabled.plist")) +} diff --git a/swift/Tests/SimSlimCLITests/ProfileCommandTests.swift b/swift/Tests/SimSlimCLITests/ProfileCommandTests.swift new file mode 100644 index 0000000..4007f90 --- /dev/null +++ b/swift/Tests/SimSlimCLITests/ProfileCommandTests.swift @@ -0,0 +1,248 @@ +// Copyright (c) 2026 Pavel Akhrameev (Swift port). MIT License; see LICENSE. + +import Foundation +import SimSlimKit +import TestSupport +import XCTest + +@testable import SimSlimCLI + +private final class Script: @unchecked Sendable { + var lines: [String] + var keys: [TopKey] + var rawEntered = 0 + var restored = 0 + init(lines: [String], keys: [TopKey]) { + self.lines = lines + self.keys = keys + } + var input: WizardInput { + WizardInput( + readLine: { _ in self.lines.isEmpty ? nil : self.lines.removeFirst() }, + enterRaw: { + self.rawEntered += 1 + return (24, { self.restored += 1 }) + }, + nextKey: { self.keys.isEmpty ? nil : self.keys.removeFirst() }) + } +} + +private func runProfile( + _ arguments: [String], lines: [String] = ["", ""], keys: [TopKey], interactive: Bool = true +) -> (CLIResult, Script) { + let script = Script(lines: lines, keys: keys) + let out = Buffer() + let err = Buffer() + var cli = CLI( + version: "t", runner: FakeHost(), isInteractive: { interactive }, + stdout: { out.append($0) }, stderr: { err.append($0) }) + cli.wizardInput = script.input + let status = cli.run(["profile"] + arguments) + return (CLIResult(status: status, stdout: out.value, stderr: err.value), script) +} + +private func scratch() -> String { + let dir = NSTemporaryDirectory() + "simslim-profile-\(UUID().uuidString)" + try? FileManager.default.createDirectory(atPath: dir, withIntermediateDirectories: true) + return dir +} + +final class ProfileCommandTests: XCTestCase { + private let first = Catalog.categories[0] + + func testKeepingAFeatureAndADaemonPrintsTheProfile() { + let second = Catalog.categories[1] + let (r, script) = runProfile( + [], lines: [" Team ", " for CI "], + keys: [.character(" "), .down, .right, .character(" "), .left, .enter]) + XCTAssertEqual(r.status, 0, r.stderr) + XCTAssertEqual( + r.stdout, + "{\n \"name\": \"Team\",\n \"description\": \"for CI\",\n \"except\": [\n \"\(first.id)\"\n ],\n \"keep\": [\n \"\(second.labels[0])\"\n ]\n}\n" + ) + XCTAssertTrue( + r.stderr.contains( + "Keeping 1 feature(s) fully enabled and 1 individual daemon(s); slimming the rest.")) + XCTAssertEqual(script.rawEntered, 1) + XCTAssertEqual(script.restored, 1, "the terminal is always restored") + } + + func testCancelWritesNothingAndSucceeds() { + for key in [TopKey.ctrlC, .character("q"), .character("Q")] { + let (r, script) = runProfile([], keys: [.character(" "), key]) + XCTAssertEqual(r.status, 0) + XCTAssertEqual(r.stdout, "") + XCTAssertTrue(r.stderr.hasSuffix("Cancelled; no profile written.\n")) + XCTAssertEqual(script.restored, 1) + } + } + + func testEndOfInputCancels() { + let (r, script) = runProfile([], keys: [.character("a")]) + XCTAssertEqual(r.status, 0) + XCTAssertEqual(r.stdout, "") + XCTAssertTrue(r.stderr.hasSuffix("Cancelled; no profile written.\n")) + XCTAssertEqual(script.restored, 1) + } + + func testCtrlCInsideTheDaemonListCancelsEverything() { + let (r, _) = runProfile([], keys: [.right, .character(" "), .ctrlC, .left, .enter]) + XCTAssertEqual(r.stdout, "") + XCTAssertTrue(r.stderr.hasSuffix("Cancelled; no profile written.\n")) + } + + func testAllThenNone() { + let (all, _) = runProfile([], keys: [.character("a"), .enter]) + XCTAssertTrue(all.stdout.contains("\"\(Catalog.categories.last!.id)\"")) + let (none, _) = runProfile([], keys: [.character("a"), .character("n"), .enter]) + XCTAssertEqual(none.stdout, "{}\n") + } + + func testKeptDaemonsInsideAKeptFeatureAreDropped() { + // Keep one daemon of the first feature, then keep the whole feature. + let (r, _) = runProfile( + [], keys: [.right, .character(" "), .left, .character(" "), .enter]) + XCTAssertTrue(r.stdout.contains("\"except\"")) + XCTAssertFalse(r.stdout.contains("\"keep\""), r.stdout) + } + + func testADaemonAnotherKeptFeatureCoversIsDropped() throws { + // A label that lives in two categories is redundant once either is kept whole. + let cats = Catalog.categories + var shared: (Int, Int, String)? + outer: for (i, a) in cats.enumerated() { + for (j, b) in cats.enumerated() where j > i { + if let l = a.labels.first(where: { b.labels.contains($0) }) { + shared = (i, j, l) + break outer + } + } + } + let (_, j, label) = try XCTUnwrap(shared) + var model = WizardModel() + model.keep.insert(label) + model.except.insert(cats[j].id) + XCTAssertFalse(model.selection().keep.contains(label)) + model.except = [] + let kept = model.selection().keep + XCTAssertEqual(kept.filter { $0 == label }.count, 1, "listed once even when shared") + } + + func testScrollingKeepsTheCursorVisible() { + var model = WizardModel(termRows: 8) + for _ in 0..<(Catalog.categories.count - 1) { model.key(.down) } + XCTAssertEqual(model.cursor, Catalog.categories.count - 1) + XCTAssertTrue(model.frame().contains("❯ ")) + XCTAssertTrue(model.frame().contains("↑more")) + XCTAssertFalse(model.frame().contains("↓more")) + model.key(.down) + XCTAssertEqual(model.cursor, Catalog.categories.count - 1, "the cursor stops at the end") + for _ in 0..<(Catalog.categories.count + 3) { model.key(.up) } + XCTAssertEqual(model.cursor, 0) + XCTAssertEqual(model.top, 0) + XCTAssertTrue(model.frame().contains("↓more")) + } + + func testMarkersShowKeptAndPartlyKept() { + var model = WizardModel() + model.key(.character(" ")) + model.key(.down) + model.key(.right) + model.key(.character(" ")) + model.key(.left) + let rows = model.rows() + XCTAssertTrue(rows[0].hasPrefix("[x] ")) + XCTAssertTrue(rows[1].hasPrefix("[~] ")) + XCTAssertTrue(rows[1].hasSuffix("(1 kept)")) + XCTAssertTrue(rows[2].hasPrefix("[ ] ")) + XCTAssertEqual(model.cursor, 1, "going back lands on the feature that was open") + } + + func testDaemonAllAndNoneStayInsideTheFeature() { + var model = WizardModel() + model.key(.right) + model.key(.character("a")) + XCTAssertEqual(model.keep, Set(Catalog.categories[0].labels)) + model.key(.character("n")) + XCTAssertTrue(model.keep.isEmpty) + } + + func testDaemonRowsFitTheScreenWidth() { + var model = WizardModel() + for index in Catalog.categories.indices { + model.screen = .daemons(index) + for row in model.rows() { XCTAssertLessThanOrEqual(row.unicodeScalars.count, 76) } + } + } + + func testWritesAFileAndRefusesToOverwriteIt() throws { + let dir = scratch() + defer { try? FileManager.default.removeItem(atPath: dir) } + let path = dir + "/mine.json" + let (r, _) = runProfile([path], keys: [.character(" "), .enter]) + XCTAssertEqual(r.status, 0, r.stderr) + XCTAssertEqual(r.stdout, "") + XCTAssertTrue( + r.stderr.hasSuffix("Wrote \(path). Apply it with `simslim on --profile \(path)`.\n")) + let text = try String(contentsOfFile: path, encoding: .utf8) + XCTAssertTrue(text.contains("\"except\"")) + let mode = try FileManager.default.attributesOfItem(atPath: path)[.posixPermissions] as? Int + XCTAssertEqual(mode, 0o644) + + let (again, script) = runProfile([path], keys: [.enter]) + XCTAssertEqual(again.status, 1) + XCTAssertEqual(again.stderr, "simslim: refusing to overwrite \(path)\n") + XCTAssertEqual(script.rawEntered, 0, "refused before any prompt") + XCTAssertEqual(try String(contentsOfFile: path, encoding: .utf8), text) + } + + func testADirectoryGetsANamedFileAndAnExistingOneIsPrintedInstead() throws { + let dir = scratch() + defer { try? FileManager.default.removeItem(atPath: dir) } + let (r, _) = runProfile([dir], lines: ["Team CI", ""], keys: [.character(" "), .enter]) + XCTAssertEqual(r.status, 0, r.stderr) + let file = dir + "/team-ci.json" + XCTAssertTrue(FileManager.default.fileExists(atPath: file)) + + let before = try String(contentsOfFile: file, encoding: .utf8) + let (second, _) = runProfile([dir], lines: ["Team CI", ""], keys: [.character("a"), .enter]) + XCTAssertEqual(second.status, 1) + XCTAssertEqual( + second.stderr.split(separator: "\n").last.map(String.init), + "simslim: \(file) already exists; printed the profile above instead of overwriting it") + XCTAssertTrue(second.stdout.contains("\"except\"")) + XCTAssertEqual(try String(contentsOfFile: file, encoding: .utf8), before) + } + + func testASymlinkAtTheDestinationIsNotFollowed() throws { + let dir = scratch() + defer { try? FileManager.default.removeItem(atPath: dir) } + let target = dir + "/target.json" + let link = dir + "/link.json" + try FileManager.default.createSymbolicLink(atPath: link, withDestinationPath: target) + let (r, _) = runProfile([link], keys: [.enter]) + XCTAssertEqual(r.status, 1) + XCTAssertFalse( + FileManager.default.fileExists(atPath: target), "nothing is written through a link") + } + + func testNeedsATerminalAndAtMostOnePath() { + let (piped, script) = runProfile([], keys: [.enter], interactive: false) + XCTAssertEqual(piped.status, 1) + XCTAssertEqual(piped.stderr, "simslim: profile is interactive; run it in a terminal\n") + XCTAssertEqual(script.rawEntered, 0) + let (many, _) = runProfile(["a", "b"], keys: []) + XCTAssertEqual(many.stderr, "simslim: profile takes an optional output path\n") + } + + func testTheProfileItWritesLoadsBack() throws { + let dir = scratch() + defer { try? FileManager.default.removeItem(atPath: dir) } + let path = dir + "/p.json" + let (r, _) = runProfile( + [path], keys: [.character(" "), .down, .right, .character(" "), .left, .enter]) + XCTAssertEqual(r.status, 0, r.stderr) + let profile = try loadSlimProfile(path: path) + XCTAssertFalse(profile.desired().isEmpty) + } +} diff --git a/swift/Tests/SimSlimCLITests/Support.swift b/swift/Tests/SimSlimCLITests/Support.swift new file mode 100644 index 0000000..51d49d6 --- /dev/null +++ b/swift/Tests/SimSlimCLITests/Support.swift @@ -0,0 +1,70 @@ +// Copyright (c) 2026 Pavel Akhrameev (Swift port). MIT License; see LICENSE. + +import Foundation +import SimSlimKit +import TestSupport + +@testable import SimSlimCLI + +struct CLIResult { + var status: Int32 + var stdout: String + var stderr: String +} + +final class Buffer: @unchecked Sendable { + private let lock = NSLock() + private var text = "" + func append(_ s: String) { + lock.lock() + text += s + lock.unlock() + } + var value: String { + lock.lock() + defer { lock.unlock() } + return text + } +} + +/// Runs the CLI against a fake host, capturing both streams. +func runCLI( + _ arguments: [String], host: FakeHost = FakeHost(), environment: [String: String] = [:], + storeRoot: String = "/nonexistent/simslim-tests", home: String = "/nonexistent/simslim-home" +) -> CLIResult { + let out = Buffer() + let err = Buffer() + let cli = CLI( + version: "test-version", environment: environment, runner: host, storeRoot: storeRoot, + home: home, + stdout: { out.append($0) }, stderr: { err.append($0) }) + let status = cli.run(arguments) + return CLIResult(status: status, stdout: out.value, stderr: err.value) +} + +let bootedUDID = "11111111-1111-1111-1111-111111111111" +let shutdownUDID = "22222222-2222-2222-2222-222222222222" +let oldUDID = "33333333-3333-3333-3333-333333333333" + +/// A host with a booted iOS 27.2 iPhone, a shut-down iPad, and a booted iOS 18.4 +/// iPhone, all partly slimmed. +func standardHost() -> FakeHost { + let host = FakeHost(devices: [ + .init(udid: shutdownUDID, name: "iPad Air", state: "Shutdown"), + .init(udid: bootedUDID, name: "iPhone 17", state: "Booted"), + .init( + udid: oldUDID, name: "iPhone 16", + runtime: "com.apple.CoreSimulator.SimRuntime.iOS-18-4", state: "Booted"), + ]) + host.disabled[bootedUDID] = Set(Profile().desired().sorted().prefix(100)) + host.disabled[oldUDID] = [] + host.launchdPIDs = [bootedUDID: 200, oldUDID: 300] + host.psOutput = """ + PID PPID %CPU COMM + 200 1 1.0 /x/launchd_sim + 201 200 2.0 /x/SpringBoard + 300 1 4.0 /x/launchd_sim + """ + host.topOutput = "PID MEM\n200 10M\n201 20M\n300 1G\n" + return host +} diff --git a/swift/Tests/SimSlimCLITests/TopCommandTests.swift b/swift/Tests/SimSlimCLITests/TopCommandTests.swift new file mode 100644 index 0000000..d33fac2 --- /dev/null +++ b/swift/Tests/SimSlimCLITests/TopCommandTests.swift @@ -0,0 +1,172 @@ +// Copyright (c) 2026 Pavel Akhrameev (Swift port). MIT License; see LICENSE. + +import SimSlimKit +import TestSupport +import XCTest + +@testable import SimSlimCLI + +final class TopCommandTests: XCTestCase { + func testTooManyArguments() { + let r = runCLI(["top", "a", "b"], host: standardHost()) + XCTAssertEqual(r.status, 1) + XCTAssertEqual(r.stderr, "simslim: top takes at most one simulator UDID\n") + } + + func testPipedOutputIsAOneShotFleetTable() { + let r = runCLI(["top"], host: standardHost()) + XCTAssertEqual(r.status, 0, r.stderr) + let lines = r.stdout.split(separator: "\n").map(String.init) + XCTAssertEqual( + lines[0], "SIMULATOR OS STATE PROC CPU RAM") + // The 1 GB iOS 18.4 simulator comes first, as the largest. + XCTAssertTrue(lines[1].hasPrefix("iPhone 16 · 33333333"), lines[1]) + XCTAssertTrue(lines[1].contains("iOS 18.4")) + XCTAssertTrue(lines[1].contains("stock")) + XCTAssertTrue(lines[2].hasPrefix("iPhone 17 · 11111111"), lines[2]) + XCTAssertTrue(lines[2].contains("part")) + XCTAssertEqual(lines[3], "2 booted · total 1.0G") + XCTAssertFalse(r.stdout.contains("\u{1B}"), "no terminal codes in a pipe") + } + + func testPipedDrillDownListsProcessesBiggestFirst() { + let r = runCLI(["top", bootedUDID], host: standardHost()) + XCTAssertEqual(r.status, 0, r.stderr) + XCTAssertEqual( + r.stdout, + """ + iPhone 17 — daemons by RAM + RAM CPU COMMAND + 20.0M 2.0% SpringBoard + 10.0M 1.0% launchd_sim + + """) + } + + func testJSONFleetCarriesDiskAndMemory() throws { + let host = standardHost() + host.dataRoot = NSTemporaryDirectory() + "simslim-top-\(UUID().uuidString)" + defer { try? FileManager.default.removeItem(atPath: host.dataRoot!) } + for udid in [bootedUDID, oldUDID] { + try FileManager.default.createDirectory( + atPath: "\(host.dataRoot!)/\(udid)/data", withIntermediateDirectories: true) + host.duKiB["\(host.dataRoot!)/\(udid)"] = 2048 + } + let r = runCLI(["top", "--json"], host: host) + XCTAssertEqual(r.status, 0, r.stderr) + let out = try JSONDecoder().decode(TopOutput.self, from: Data(r.stdout.utf8)) + XCTAssertEqual(out.sims.map(\.device.name), ["iPhone 16", "iPhone 17"]) + XCTAssertEqual(out.sims.map(\.diskBytes), [2_097_152, 2_097_152]) + XCTAssertEqual(out.sims[1].managedDisabled, 100) + XCTAssertEqual(out.sims[1].managedTotal, 173) + XCTAssertEqual(out.sims[1].memory, MemoryMeasurement(processes: 2, bytes: 30 << 20, cpu: 3)) + XCTAssertEqual(out.totalBytes, (30 << 20) + (1 << 30)) + // The keys the Go output uses, flattened with the device's. + XCTAssertTrue(r.stdout.contains("\"diskBytes\"")) + XCTAssertTrue(r.stdout.contains("\"platform\" : \"iOS\"")) + } + + func testJSONDrillDownTotalsTheProcesses() throws { + let r = runCLI(["top", "--json", bootedUDID], host: standardHost()) + XCTAssertEqual(r.status, 0, r.stderr) + let out = try JSONDecoder().decode(TopProcesses.self, from: Data(r.stdout.utf8)) + XCTAssertEqual(out.udid, bootedUDID) + XCTAssertEqual(out.name, "iPhone 17") + XCTAssertEqual(out.processes.map(\.command), ["SpringBoard", "launchd_sim"]) + XCTAssertEqual(out.totalBytes, 30 << 20) + } + + func testDrillDownOfAShutdownSimulatorIsAnError() { + let r = runCLI(["top", shutdownUDID], host: standardHost()) + XCTAssertEqual(r.status, 1) + XCTAssertEqual( + r.stderr, "simslim: simulator \(shutdownUDID) does not appear to be booted\n") + } + + func testNoBootedSimulators() { + let host = FakeHost(devices: [.init(udid: shutdownUDID, name: "iPad", state: "Shutdown")]) + let r = runCLI(["top"], host: host) + XCTAssertEqual(r.status, 0) + XCTAssertTrue(r.stdout.hasSuffix("0 booted · total 0B\n"), r.stdout) + } + + func testASimulatorWhoseStatusCannotBeReadStillAppears() throws { + let host = standardHost() + host.disabled[bootedUDID] = nil // print-disabled fails for it + let r = runCLI(["top", "--json"], host: host) + XCTAssertEqual(r.status, 0, r.stderr) + let out = try JSONDecoder().decode(TopOutput.self, from: Data(r.stdout.utf8)) + let sim = try XCTUnwrap(out.sims.first { $0.device.udid == bootedUDID }) + XCTAssertNil(sim.managedDisabled) + XCTAssertFalse(sim.statusError.isEmpty) + XCTAssertNotNil(sim.memory) + } + + // MARK: - disk + + func testDiskUsageResolvesTheUDIDAndMeasuresItsDeviceDirectory() throws { + let host = standardHost() + host.dataRoot = NSTemporaryDirectory() + "simslim-du-\(UUID().uuidString)" + defer { try? FileManager.default.removeItem(atPath: host.dataRoot!) } + try FileManager.default.createDirectory( + atPath: "\(host.dataRoot!)/\(bootedUDID)/data", withIntermediateDirectories: true) + host.duKiB["\(host.dataRoot!)/\(bootedUDID)"] = 5 + let ctl = Simctl(runner: host) + XCTAssertEqual(try ctl.deviceDiskUsage(udid: bootedUDID), 5120) + // An alias never becomes a filesystem path. + XCTAssertThrowsError(try ctl.deviceDiskUsage(udid: "all")) + XCTAssertFalse(host.calls.contains { $0.executable == .du && $0.arguments.contains("all") }) + } + + func testDiskUsageRefusesASymlinkedOrMissingDataDirectory() throws { + let host = standardHost() + let root = NSTemporaryDirectory() + "simslim-du-\(UUID().uuidString)" + host.dataRoot = root + defer { try? FileManager.default.removeItem(atPath: root) } + let ctl = Simctl(runner: host) + XCTAssertThrowsError(try ctl.deviceDiskUsage(udid: bootedUDID)) { + XCTAssertTrue("\($0)".hasPrefix("locate simulator data: "), "\($0)") + } + try FileManager.default.createDirectory( + atPath: "\(root)/\(bootedUDID)", withIntermediateDirectories: true) + try FileManager.default.createDirectory( + atPath: root + "/elsewhere", withIntermediateDirectories: true) + try FileManager.default.createSymbolicLink( + atPath: "\(root)/\(bootedUDID)/data", withDestinationPath: root + "/elsewhere") + XCTAssertThrowsError(try ctl.deviceDiskUsage(udid: bootedUDID)) { + XCTAssertTrue("\($0)".hasPrefix("simulator data path is not a real directory: "), "\($0)") + } + XCTAssertFalse(host.calls.contains { $0.executable == .du }) + } + + func testEqualFootprintsOrderByPID() throws { + let host = standardHost() + host.psOutput = """ + PID PPID %CPU COMM + 200 1 1.0 /x/launchd_sim + 205 200 2.0 /x/zeta + 203 200 2.0 /x/alpha + 204 200 2.0 /x/mid + """ + host.topOutput = "PID MEM\n200 10M\n203 5M\n204 5M\n205 5M\n" + let procs = try Simctl(runner: host).measureProcesses(udid: bootedUDID) + XCTAssertEqual(procs.map(\.pid), [200, 203, 204, 205]) + } + + func testNoDataPathIsAnError() { + let host = standardHost() + host.emptyDataPath = true + XCTAssertThrowsError(try Simctl(runner: host).deviceDiskUsage(udid: bootedUDID)) { + XCTAssertEqual("\($0)", "simctl reported no data path for \(bootedUDID)") + } + XCTAssertFalse(host.calls.contains { $0.executable == .du }) + } + + // MARK: - the terminal screen + + func testTheLiveScreenIsOnlyDrawnForARealTerminal() { + // With stdin/stdout not a terminal the command prints once and exits. + let r = runCLI(["top"], host: standardHost()) + XCTAssertFalse(r.stdout.contains("\u{1B}[?1049h")) + } +} diff --git a/swift/Tests/SimSlimCLITests/TopModelTests.swift b/swift/Tests/SimSlimCLITests/TopModelTests.swift new file mode 100644 index 0000000..00d5a07 --- /dev/null +++ b/swift/Tests/SimSlimCLITests/TopModelTests.swift @@ -0,0 +1,404 @@ +// Copyright (c) 2026 Pavel Akhrameev (Swift port). MIT License; see LICENSE. + +import SimSlimKit +import XCTest + +@testable import SimSlimCLI + +final class TopModelTests: XCTestCase { + private func sim( + _ n: Int, name: String? = nil, ram: Int64? = nil, cpu: Double = 0, procs: Int = 10, + disabled: Int? = 173, os: String = "27.2", platform: String = "iOS" + ) -> TopSim { + TopSim( + device: Device( + udid: String(format: "AAAAAAAA-0000-0000-0000-%012d", n), name: name ?? "Sim \(n)", + state: "Booted", platform: platform, osVersion: os, set: "default"), + managedDisabled: disabled, managedTotal: 173, + memory: ram.map { MemoryMeasurement(processes: procs, bytes: $0, cpu: cpu) }) + } + + private func loaded(_ sims: [TopSim], width: Int = 100, height: Int = 30) -> TopModel { + var model = TopModel() + _ = model.apply(.resize(width: width, height: height), now: Date()) + _ = model.apply( + .fleet( + .success( + TopOutput(sims: sims, totalBytes: sims.compactMap { $0.memory?.bytes }.reduce(0, +)))), + now: Date()) + return model + } + + // MARK: - fleet updates + + func testTheFirstSnapshotLoadsAndRequestsDiskForEverySimulator() { + var model = TopModel() + let effects = model.apply( + .fleet(.success(TopOutput(sims: [sim(1, ram: 5), sim(2, ram: 9)], totalBytes: 14))), + now: Date()) + XCTAssertTrue(model.loaded) + XCTAssertEqual(model.sims.map(\.device.name), ["Sim 2", "Sim 1"], "sorted by RAM, descending") + XCTAssertEqual( + effects, [.refreshDisk(model.sims.map { $0.device.udid })], + "disk is measured for the new ones") + XCTAssertTrue(model.diskBusy) + // Not again while a sweep is in flight. + XCTAssertEqual(model.apply(.fleet(.success(TopOutput(sims: model.sims))), now: Date()), []) + } + + func testAFailedRefreshKeepsThePreviousSnapshotAndShowsTheError() { + var model = loaded([sim(1, ram: 5)]) + _ = model.apply(.fleet(.failure(SimSlimError("simctl list: boom"))), now: Date()) + XCTAssertEqual(model.sims.count, 1) + XCTAssertTrue(model.screenLines().joined().contains("refresh error: simctl list: boom")) + _ = model.apply(.fleet(.success(TopOutput(sims: model.sims))), now: Date()) + XCTAssertNil(model.error, "a good refresh clears it") + } + + func testAnErrorBeforeTheFirstSnapshotIsTheOnlyThingShown() { + var model = TopModel() + _ = model.apply(.fleet(.failure(SimSlimError("no xcode"))), now: Date()) + XCTAssertTrue(model.screenLines().joined(separator: "\n").contains("no xcode")) + XCTAssertFalse(model.loaded) + } + + func testLoadingAndEmptyMessages() { + var model = TopModel() + XCTAssertTrue(model.screenLines().joined().contains("Loading booted simulators…")) + _ = model.apply(.fleet(.success(TopOutput())), now: Date()) + XCTAssertTrue( + model.screenLines().joined().contains( + "No booted simulators. Boot one with `simslim boot `.")) + } + + func testDiskIsRefreshedOnlyAfterItsTTL() { + var model = loaded([sim(1, ram: 5)]) + let start = Date() + _ = model.apply(.disk([model.sims[0].device.udid: 100]), now: start) + XCTAssertFalse(model.diskBusy) + XCTAssertEqual(model.tick(now: start.addingTimeInterval(topDiskTTL - 1)), [.refreshFleet]) + let late = model.tick(now: start.addingTimeInterval(topDiskTTL + 1)) + XCTAssertEqual(late, [.refreshFleet, .refreshDisk([model.sims[0].device.udid])]) + XCTAssertTrue(model.diskBusy) + XCTAssertEqual(model.tick(now: start.addingTimeInterval(topDiskTTL + 5)), [.refreshFleet]) + } + + // MARK: - sorting and the cursor + + func testSortKeysChooseAndFlipTheColumn() { + var model = loaded([ + sim(1, name: "b", ram: 5, cpu: 30), sim(2, name: "a", ram: 9, cpu: 10), + sim(3, name: "c", ram: 1, cpu: 20), + ]) + XCTAssertEqual(model.sims.map(\.device.name), ["a", "b", "c"], "RAM, descending") + _ = model.key(.character("c")) + XCTAssertEqual(model.sims.map(\.device.name), ["b", "c", "a"], "CPU, descending") + _ = model.key(.character("c")) + XCTAssertEqual(model.sims.map(\.device.name), ["a", "c", "b"], "again flips to ascending") + _ = model.key(.character("n")) + XCTAssertEqual(model.sims.map(\.device.name), ["c", "b", "a"], "name, descending first") + _ = model.key(.character("m")) + XCTAssertEqual(model.sims.map(\.device.name), ["a", "b", "c"]) + XCTAssertTrue(model.screenLines()[0].contains("RAM▼")) + } + + func testSortByOSComparesVersionsNumerically() { + var model = loaded([ + sim(1, name: "old", ram: 1, os: "9.0"), sim(2, name: "new", ram: 1, os: "26.4"), + sim(3, name: "tv", ram: 1, os: "26.4", platform: "tvOS"), + ]) + _ = model.key(.character("o")) + XCTAssertEqual(model.sims.map(\.device.name), ["tv", "new", "old"], "platform, then version") + XCTAssertTrue(osLess("9.0", "26.4")) + XCTAssertFalse(osLess("26.4", "9.0")) + XCTAssertTrue(osLess("26", "26.1")) + XCTAssertTrue(osLess("", "1")) + } + + func testStateAndProcessAndDiskSorts() { + var model = loaded([ + sim(1, name: "stock", ram: 1, procs: 5, disabled: 0), + sim(2, name: "slim", ram: 2, procs: 99, disabled: 173), + sim(3, name: "unknown", ram: 3, procs: 50, disabled: nil), + ]) + _ = model.key(.character("s")) + XCTAssertEqual(model.sims.map(\.device.name), ["slim", "stock", "unknown"]) + _ = model.key(.character("p")) + XCTAssertEqual(model.sims.map(\.device.name), ["slim", "unknown", "stock"]) + _ = model.apply( + .disk([model.sims[0].device.udid: 1, model.sims[2].device.udid: 9]), now: Date()) + _ = model.key(.character("d")) + XCTAssertEqual(model.sims[0].device.udid, String(format: "AAAAAAAA-0000-0000-0000-%012d", 1)) + } + + func testASimulatorWithoutAMeasurementSortsLastByRAM() { + let model = loaded([sim(1, ram: nil), sim(2, ram: 5), sim(3, ram: 1)]) + XCTAssertEqual(model.sims.map(\.device.name), ["Sim 2", "Sim 3", "Sim 1"]) + } + + func testTheCursorFollowsItsSimulatorAcrossRefreshesAndResorts() { + var model = loaded([sim(1, ram: 5), sim(2, ram: 9), sim(3, ram: 1)]) + _ = model.key(.down) // Sim 1 (second by RAM) + XCTAssertEqual(model.sims[model.cursor].device.name, "Sim 1") + // Sim 3 balloons and moves to the top; the cursor stays on Sim 1. + _ = model.apply( + .fleet(.success(TopOutput(sims: [sim(1, ram: 5), sim(2, ram: 9), sim(3, ram: 50)]))), + now: Date()) + XCTAssertEqual(model.sims.map(\.device.name), ["Sim 3", "Sim 2", "Sim 1"]) + XCTAssertEqual(model.sims[model.cursor].device.name, "Sim 1") + // It disappears: the cursor stays in range. + _ = model.apply(.fleet(.success(TopOutput(sims: [sim(2, ram: 9)]))), now: Date()) + XCTAssertEqual(model.cursor, 0) + } + + func testACursorWhoseSimulatorLeftDoesNotJumpBackWhenItReturns() { + var model = loaded([sim(1, ram: 5), sim(2, ram: 9), sim(3, ram: 1)]) + _ = model.key(.down) + _ = model.key(.down) // Sim 3, last + XCTAssertEqual(model.sims[model.cursor].device.name, "Sim 3") + _ = model.apply( + .fleet(.success(TopOutput(sims: [sim(1, ram: 5), sim(2, ram: 9)]))), now: Date()) + XCTAssertEqual(model.cursor, 1, "clamped into range") + // It returns as the biggest; the old anchor is gone, so the cursor stays put. + _ = model.apply( + .fleet(.success(TopOutput(sims: [sim(1, ram: 5), sim(2, ram: 9), sim(3, ram: 99)]))), + now: Date()) + XCTAssertEqual(model.sims.map(\.device.name), ["Sim 3", "Sim 2", "Sim 1"]) + XCTAssertEqual(model.cursor, 1) + } + + func testScrollIsPulledBackWhenTheProcessListShrinks() { + var model = loaded([sim(1, ram: 5)], height: 8) + _ = model.key(.enter) + let big = (1...10).map { + ProcessUsage(pid: $0, command: "p\($0)", bytes: Int64(100 - $0), cpu: 0) + } + _ = model.apply(.procs(udid: model.selUDID, .success(big)), now: Date()) + for _ in 0..<9 { _ = model.key(.down) } + XCTAssertEqual(model.scroll, 9) + _ = model.apply(.procs(udid: model.selUDID, .success(Array(big.prefix(3)))), now: Date()) + XCTAssertEqual(model.scroll, 2) + } + + func testCursorKeysStayInRange() { + var model = loaded([sim(1, ram: 5), sim(2, ram: 9)]) + _ = model.key(.up) + XCTAssertEqual(model.cursor, 0) + _ = model.key(.down) + _ = model.key(.down) + _ = model.key(.character("j")) + XCTAssertEqual(model.cursor, 1) + _ = model.key(.character("k")) + XCTAssertEqual(model.cursor, 0) + } + + // MARK: - drill-down + + func testEnterOpensTheDrillDownAndEscapeGoesBack() { + var model = loaded([sim(1, name: "Phone", ram: 5)]) + let effects = model.key(.enter) + XCTAssertEqual(effects, [.refreshProcs(model.sims[0].device.udid)]) + XCTAssertEqual(model.screen, .drill) + XCTAssertEqual(model.selName, "Phone") + XCTAssertTrue(model.screenLines().joined().contains("measuring…")) + _ = model.key(.escape) + XCTAssertEqual(model.screen, .fleet) + XCTAssertEqual(model.selUDID, "") + } + + func testProcessResultsOnlyCountForTheOpenSimulator() { + var model = loaded([sim(1, ram: 5)]) + _ = model.key(.enter) + let id = model.selUDID + _ = model.apply( + .procs( + udid: "someone-else", .success([ProcessUsage(pid: 1, command: "x", bytes: 1, cpu: 0)])), + now: Date()) + XCTAssertEqual(model.procs, []) + _ = model.apply( + .procs( + udid: id, + .success([ + ProcessUsage(pid: 1, command: "launchd_sim", bytes: 1 << 20, cpu: 0.5), + ProcessUsage(pid: 2, command: "SpringBoard", bytes: 300 << 20, cpu: 2), + ])), + now: Date()) + XCTAssertEqual(model.procs.map(\.command), ["SpringBoard", "launchd_sim"]) + let text = model.screenLines().joined(separator: "\n") + XCTAssertTrue( + text.contains("Phone — daemons by RAM") || text.contains("Sim 1 — daemons by RAM")) + XCTAssertTrue(text.contains("300.0M 2.0% SpringBoard"), text) + XCTAssertTrue(text.contains("1–2 of 2")) + } + + func testDrillSortsOnlyOfferRAMCPUAndName() { + var model = loaded([sim(1, ram: 5)]) + _ = model.key(.enter) + _ = model.apply( + .procs( + udid: model.selUDID, + .success([ + ProcessUsage(pid: 1, command: "b", bytes: 5, cpu: 1), + ProcessUsage(pid: 2, command: "a", bytes: 9, cpu: 3), + ])), + now: Date()) + _ = model.key(.character("d")) // a fleet-only column: ignored here + XCTAssertEqual(model.sortCol, .ram) + _ = model.key(.character("c")) + XCTAssertEqual(model.procs.map(\.command), ["a", "b"]) + _ = model.key(.character("n")) + XCTAssertEqual(model.procs.map(\.command), ["b", "a"], "name, descending") + XCTAssertTrue(model.screenLines()[0].contains("daemons by command")) + } + + func testDrillScrollingIsClamped() { + var model = loaded([sim(1, ram: 5)], height: 8) // 3 visible process rows + _ = model.key(.enter) + let procs = (1...10).map { + ProcessUsage(pid: $0, command: "p\($0)", bytes: Int64(100 - $0), cpu: 0) + } + _ = model.apply(.procs(udid: model.selUDID, .success(procs)), now: Date()) + for _ in 0..<50 { _ = model.key(.down) } + XCTAssertEqual(model.scroll, 9) + let lines = model.screenLines() + XCTAssertTrue(lines.last!.contains("8–10 of 10"), lines.last!) + for _ in 0..<50 { _ = model.key(.up) } + XCTAssertEqual(model.scroll, 0) + } + + func testAProcessErrorIsShownWithTheWayBack() { + var model = loaded([sim(1, ram: 5)]) + _ = model.key(.enter) + _ = model.apply( + .procs(udid: model.selUDID, .failure(SimSlimError("simulator does not appear to be booted"))), + now: Date()) + let text = model.screenLines().joined(separator: "\n") + XCTAssertTrue(text.contains("does not appear to be booted")) + XCTAssertTrue(text.contains("esc back · q quit")) + } + + func testStartingInsideADrillDown() { + var model = TopModel(drillInto: "UDID-1", name: "Phone") + XCTAssertEqual(model.start(), [.refreshFleet, .refreshProcs("UDID-1")]) + XCTAssertEqual(model.screen, .drill) + XCTAssertEqual(model.tick(now: Date()), [.refreshFleet, .refreshProcs("UDID-1")]) + var fleet = TopModel() + XCTAssertEqual(fleet.start(), [.refreshFleet]) + } + + func testQuitKeys() { + for key in [TopKey.ctrlC, .character("q")] { + var model = TopModel() + XCTAssertEqual(model.key(key), [.quit]) + } + } + + // MARK: - rendering + + func testTheFleetTableLayout() { + var model = loaded([sim(1, name: "iPhone 17", ram: 6_800_000_000, cpu: 136, procs: 90)]) + _ = model.apply(.disk([model.sims[0].device.udid: 7_000_000_000]), now: Date()) + let lines = model.screenLines() + XCTAssertTrue(lines[0].hasPrefix("\u{1B}[1mSIMULATOR")) + XCTAssertTrue(lines[0].contains("RAM▼")) + XCTAssertTrue(lines[1].hasPrefix("\u{1B}[7m"), "the selected row is reversed") + XCTAssertTrue(lines[1].contains("iPhone 17 · AAAAAAAA")) + XCTAssertTrue(lines[1].contains("iOS 27.2")) + XCTAssertTrue(lines[1].contains("slim")) + XCTAssertTrue(lines[1].contains("90")) + XCTAssertTrue(lines[1].contains("136%")) + XCTAssertTrue(lines[1].contains("6.3G")) + XCTAssertTrue(lines[1].contains("6.5G")) + XCTAssertTrue(lines.joined().contains("1 booted · total 6.3G")) + XCTAssertTrue(lines.joined().contains("↑↓ select · ↵ open · sort n·o·s·p·c·m·d · q quit")) + } + + func testEveryLineFitsTheTerminalWidth() { + for width in [20, 40, 80, 120] { + var model = loaded( + [sim(1, name: "A rather long simulator name that goes on", ram: 5)], width: width) + _ = model.key(.enter) + for screen in [TopModel.Screen.fleet, .drill] { + model.screen = screen + for line in model.screenLines() { + let visible = line.replacingOccurrences( + of: "\u{1B}\\[[0-9;]*m", with: "", options: .regularExpression) + XCTAssertLessThanOrEqual(visible.unicodeScalars.count, width, "\(screen) at \(width)") + } + } + } + } + + func testTheNameColumnFlexesWithTheTerminal() { + var model = TopModel() + XCTAssertEqual(model.nameWidth, 30) + model.width = 60 + XCTAssertEqual(model.nameWidth, 16) + model.width = 100 + XCTAssertEqual(model.nameWidth, 47) + model.width = 400 + XCTAssertEqual(model.nameWidth, 60) + } + + func testTheCursorRowStaysVisibleWhenThereAreMoreSimulatorsThanLines() { + let sims = (1...30).map { sim($0, ram: Int64(1000 - $0)) } + var model = loaded(sims, height: 10) + for _ in 0..<20 { _ = model.key(.down) } + let lines = model.screenLines() + XCTAssertLessThanOrEqual(lines.count, 10) + XCTAssertTrue(lines.contains { $0.hasPrefix("\u{1B}[7m") }, "the selected row is on screen") + } + + func testStatusAndMemoryLabels() { + let model = TopModel() + XCTAssertEqual(model.stateLabel(sim(1, disabled: 173)), "slim") + XCTAssertEqual(model.stateLabel(sim(1, disabled: 5)), "part") + XCTAssertEqual(model.stateLabel(sim(1, disabled: 0)), "stock") + XCTAssertEqual(model.stateLabel(sim(1, disabled: nil)), "?") + var broken = sim(1) + broken.statusError = "boom" + XCTAssertEqual(model.stateLabel(broken), "?") + XCTAssertEqual(model.ramLabel(sim(1, ram: nil)), "—") + var failed = sim(1) + failed.memoryError = "x" + XCTAssertEqual(model.ramLabel(failed), "err") + XCTAssertEqual(model.procCount(sim(1, ram: nil)), "—") + XCTAssertEqual(model.cpuLabel(sim(1, ram: nil)), "—") + XCTAssertEqual(model.osLabel(sim(1, os: "")), "?") + XCTAssertEqual(model.diskLabel("nope"), "…") + } + + func testFormatting() { + XCTAssertEqual(fmtBytes(0), "0B") + XCTAssertEqual(fmtBytes(1023), "1023B") + XCTAssertEqual(fmtBytes(1024), "1.0K") + XCTAssertEqual(fmtBytes(1536), "1.5K") + XCTAssertEqual(fmtBytes(10 << 20), "10.0M") + XCTAssertEqual(fmtBytes(14_740_000_000), "13.7G") + XCTAssertEqual(fmtBytes(Int64(5) << 40), "5.0T") + XCTAssertEqual(fmtBytes(Int64.max), "8.0E") + XCTAssertEqual(shortUDID("ABCDEFGH-1234"), "ABCDEFGH") + XCTAssertEqual(shortUDID("short"), "short") + XCTAssertEqual(padLeft("ab", 5), " ab") + XCTAssertEqual(padLeft("abcdef", 5), "abcdef") + XCTAssertEqual(clampScroll(-3, 10, 4), 0) + XCTAssertEqual(clampScroll(99, 10, 4), 6) + XCTAssertEqual(clampScroll(3, 2, 4), 0) + } + + // MARK: - keys + + func testKeyParsing() { + XCTAssertEqual(parseTopKeys([0x71]), [.character("q")]) + XCTAssertEqual(parseTopKeys([0x1B, 0x5B, 0x41]), [.up]) + XCTAssertEqual( + parseTopKeys([0x1B, 0x5B, 0x42, 0x1B, 0x5B, 0x43, 0x1B, 0x5B, 0x44]), [.down, .right, .left]) + XCTAssertEqual(parseTopKeys([0x1B, 0x4F, 0x41]), [.up], "application-mode arrows") + XCTAssertEqual(parseTopKeys([0x1B]), [.escape]) + XCTAssertEqual(parseTopKeys([0x0D]), [.enter]) + XCTAssertEqual(parseTopKeys([0x03]), [.ctrlC]) + XCTAssertEqual(parseTopKeys([0x6A, 0x6A]), [.character("j"), .character("j")]) + XCTAssertEqual(parseTopKeys([0xC3, 0xA9]), [], "UTF-8 is ignored") + XCTAssertEqual(parseTopKeys([]), []) + } +} diff --git a/swift/Tests/SimSlimCLITests/WatchCommandTests.swift b/swift/Tests/SimSlimCLITests/WatchCommandTests.swift new file mode 100644 index 0000000..0a0df88 --- /dev/null +++ b/swift/Tests/SimSlimCLITests/WatchCommandTests.swift @@ -0,0 +1,136 @@ +// Copyright (c) 2026 Pavel Akhrameev (Swift port). MIT License; see LICENSE. + +import SimSlimKit +import TestSupport +import XCTest + +@testable import SimSlimCLI + +private final class Sink: @unchecked Sendable { + private let lock = NSLock() + private var text = "" + func append(_ s: String) { + lock.lock() + text += s + lock.unlock() + } + var value: String { + lock.lock() + defer { lock.unlock() } + return text + } +} + +final class WatchCommandTests: XCTestCase { + private let udid = "AAAAAAAA-0000-0000-0000-000000000001" + private var root = "" + + override func setUpWithError() throws { + root = NSTemporaryDirectory() + "simslim-watchcli-\(UUID().uuidString)" + try FileManager.default.createDirectory( + atPath: root + "/home/Library/Developer/CoreSimulator/Devices", + withIntermediateDirectories: true) + } + + override func tearDown() { + try? FileManager.default.removeItem(atPath: root) + } + + /// Runs `simslim ` until `until` holds for what it has printed, then + /// interrupts it, as Ctrl-C would. + private func watch( + _ args: [String], host: FakeHost, until: @escaping (String, String) -> Bool + ) -> (status: Int32, stdout: String, stderr: String) { + let out = Sink() + let err = Sink() + let flag = InterruptFlag() + let cli = CLI( + version: "t", environment: [:], runner: host, storeRoot: root + "/store", + home: root + "/home", interrupt: flag, stdout: { out.append($0) }, stderr: { err.append($0) }) + let status = Sink() + let done = DispatchSemaphore(value: 0) + Thread.detachNewThread { + status.append(String(cli.run(args))) + done.signal() + } + let limit = Date().addingTimeInterval(10) + while !until(out.value, err.value) && Date() < limit { Thread.sleep(forTimeInterval: 0.01) } + flag.trigger() + XCTAssertEqual(done.wait(timeout: .now() + 15), .success, "watch stops on interrupt") + return (Int32(status.value) ?? -1, out.value, err.value) + } + + private func bootedHost() -> FakeHost { + let host = FakeHost(devices: [.init(udid: udid, name: "iPhone", state: "Booted")]) + host.disabled[udid] = [] + host.loaded[udid] = [] + return host + } + + func testJSONEventsAreOneObjectPerLineAndTheDeviceEndsSlim() throws { + let host = bootedHost() + let r = watch(["watch", "--json", "--interval", "200ms"], host: host) { out, _ in + out.contains("\"slimmed\"") + } + XCTAssertEqual(r.status, 0) + XCTAssertEqual(r.stderr, "", "stderr stays quiet under --json") + let lines = r.stdout.split(separator: "\n").map(String.init) + XCTAssertEqual( + lines, + [ + "{\"event\":\"slimming\",\"udid\":\"\(udid)\",\"set\":\"default\"}", + "{\"event\":\"slimmed\",\"udid\":\"\(udid)\",\"set\":\"default\"}", + ]) + for line in lines { + XCTAssertNotNil(try JSONSerialization.jsonObject(with: Data(line.utf8)) as? [String: Any]) + } + XCTAssertEqual(host.disabled[udid]?.intersection(Catalog.managedSet), Profile().desired()) + } + + func testTextModeAnnouncesTheSetsAndLogsEachDevice() { + let host = bootedHost() + let r = watch( + ["watch", "--interval", "200ms", "--set", "/custom/set"], host: host + ) { _, err in err.contains("watch: slimmed \(self.udid)") } + XCTAssertEqual(r.status, 0) + XCTAssertEqual(r.stdout, "") + XCTAssertTrue( + r.stderr.hasPrefix( + "Watching device sets [default, testing, /custom/set]; slimming each simulator before it boots where its runtime allows, and no-reboot as it boots. Ctrl-C to stop.\n" + ), r.stderr) + XCTAssertTrue(r.stderr.contains("watch: slimming \(udid) (set default)\n")) + XCTAssertTrue(r.stderr.contains("watch: \(udid): Booting the simulator")) + } + + func testExceptKeepsACategoryOutOfTheSlim() { + let host = bootedHost() + _ = watch(["watch", "--json", "--interval", "200ms", "--except", "search"], host: host) { + out, _ in out.contains("\"slimmed\"") + } + let search = Set(Catalog.category(id: "search")!.labels) + XCTAssertTrue(host.disabled[udid]!.isDisjoint(with: search)) + } + + func testBadArgumentsFailBeforeAnythingRuns() { + let host = bootedHost() + let flag = InterruptFlag() + func run(_ args: [String]) -> CLIResult { + let err = Sink() + let cli = CLI( + version: "t", environment: [:], runner: host, home: root + "/home", interrupt: flag, + stdout: { _ in }, stderr: { err.append($0) }) + let status = cli.run(args) + return CLIResult(status: status, stdout: "", stderr: err.value) + } + let interval = run(["watch", "--interval", "soon"]) + XCTAssertEqual(interval.status, 1) + XCTAssertTrue(interval.stderr.hasPrefix("simslim: invalid value \"soon\" for flag -interval")) + XCTAssertTrue( + run(["watch", "--profile", "x.json", "--keep", "a"]).stderr.contains( + "--profile cannot be combined with --except or --keep")) + XCTAssertTrue(run(["watch", "--except", "nope"]).stderr.contains("unknown category \"nope\"")) + XCTAssertTrue(run(["watch", udid]).stderr.contains("watch takes no arguments")) + XCTAssertTrue(host.calls.isEmpty) + XCTAssertFalse(flag.isSet) + } +} diff --git a/swift/Tests/SimSlimKitTests/CloneFilesystemTests.swift b/swift/Tests/SimSlimKitTests/CloneFilesystemTests.swift new file mode 100644 index 0000000..f498453 --- /dev/null +++ b/swift/Tests/SimSlimKitTests/CloneFilesystemTests.swift @@ -0,0 +1,596 @@ +// Copyright (c) 2026 Pavel Akhrameev (Swift port). MIT License; see LICENSE. + +import Foundation +import XCTest + +@testable import SimSlimKit + +final class CloneFilesystemTests: XCTestCase { + private let src = "AAAAAAAA-0000-0000-0000-000000000001" + private let dst = "BBBBBBBB-0000-0000-0000-000000000002" + private var root = "" + private let fm = FileManager.default + + override func setUpWithError() throws { + root = try resolvedPath(NSTemporaryDirectory()) + "/simslim-clonefs-\(UUID().uuidString)" + try fm.createDirectory(atPath: root, withIntermediateDirectories: true) + for udid in [src, dst] { + try fm.createDirectory( + atPath: "\(root)/devices/\(udid)/data", withIntermediateDirectories: true) + try fm.createDirectory( + atPath: "\(root)/home/Library/Logs/CoreSimulator/\(udid)", withIntermediateDirectories: true + ) + } + } + + override func tearDown() { try? fm.removeItem(atPath: root) } + + private var paths: CloneFilesystem { + CloneFilesystem( + sourceUDID: src, cloneUDID: dst, + sourceDeviceDirectory: "\(root)/devices/\(src)", + cloneDeviceDirectory: "\(root)/devices/\(dst)", + sourceDataDirectory: "\(root)/devices/\(src)/data", + cloneDataDirectory: "\(root)/devices/\(dst)/data", + sourceLogDirectory: "\(root)/home/Library/Logs/CoreSimulator/\(src)", + cloneLogDirectory: "\(root)/home/Library/Logs/CoreSimulator/\(dst)") + } + + private var cloneData: String { paths.cloneDataDirectory } + private var sourceData: String { paths.sourceDataDirectory } + + private func write(_ path: String, _ text: String = "x") throws { + try fm.createDirectory( + atPath: (path as NSString).deletingLastPathComponent, withIntermediateDirectories: true) + try Data(text.utf8).write(to: URL(fileURLWithPath: path)) + } + + private func exists(_ path: String) -> Bool { + var info = stat() + return lstat(path, &info) == 0 + } + + private func message(_ body: () throws -> Void) -> String { + do { + try body() + return "" + } catch { return "\(error)" } + } + + // MARK: - path logic + + func testRebasePathMapsOnlyWhatIsAtOrBelowTheSource() { + XCTAssertEqual(rebasePath("/s/dev", sourceRoot: "/s/dev", cloneRoot: "/s/new"), "/s/new") + XCTAssertEqual( + rebasePath("/s/dev/a/b", sourceRoot: "/s/dev", cloneRoot: "/s/new"), "/s/new/a/b") + XCTAssertEqual( + rebasePath("/s/dev/a/../b", sourceRoot: "/s/dev/", cloneRoot: "/s/new"), "/s/new/b") + XCTAssertNil( + rebasePath("/s/device", sourceRoot: "/s/dev", cloneRoot: "/s/new"), + "a name prefix is not a parent") + XCTAssertNil(rebasePath("/s/dev/../x", sourceRoot: "/s/dev", cloneRoot: "/s/new")) + XCTAssertNil(rebasePath("/other", sourceRoot: "/s/dev", cloneRoot: "/s/new")) + XCTAssertNil( + rebasePath("a/b", sourceRoot: "/s/dev", cloneRoot: "/s/new"), "relative is never mapped") + XCTAssertEqual(rebasePath("/x/y", sourceRoot: "/", cloneRoot: "/z"), "/z/x/y") + } + + func testRelativePath() { + XCTAssertEqual(relativePath(from: "/a/b", to: "/a/b/c/d"), "c/d") + XCTAssertEqual(relativePath(from: "/a/b/c", to: "/a/x"), "../../x") + XCTAssertEqual(relativePath(from: "/a/b", to: "/a/b"), ".") + XCTAssertEqual(relativePath(from: "/a/b", to: "/a"), "..") + XCTAssertEqual(relativePath(from: "/", to: "/a"), "a") + } + + func testPathContainsComponent() { + XCTAssertTrue(pathContainsComponent("/x/UDID/y", "UDID")) + XCTAssertTrue(pathContainsComponent("rel/UDID", "UDID")) + XCTAssertFalse(pathContainsComponent("/x/UDIDS/y", "UDID")) + XCTAssertFalse(pathContainsComponent("/x/UDID/../y", "UDID"), "cleaned first") + XCTAssertFalse(pathContainsComponent("/x/y", "")) + } + + func testClonedUDIDParsing() throws { + XCTAssertEqual(try Simctl.parseClonedUDID(" \(src)\n"), src) + XCTAssertEqual(try Simctl.parseClonedUDID(src.lowercased()), src.lowercased()) + for bad in [ + "", "garbage", src + "0", String(src.dropLast()), + src.replacingOccurrences(of: "-", with: "_"), + "ZZZZZZZZ-0000-0000-0000-000000000001", "warning\n" + src, + ] { + XCTAssertThrowsError(try Simctl.parseClonedUDID(bad), bad) { + XCTAssertTrue("\($0)".hasPrefix("simctl clone returned an invalid UDID"), "\($0)") + } + } + } + + func testOnlySlimmableOverridesAreCarriedOver() { + let slimmable = Catalog.categories[0].labels[0] + let alwaysOn = Catalog.categories.flatMap(\.alwaysEnabled)[0].label + let carried = desiredCloneDisabled([slimmable, alwaysOn, "com.example.unrelated"]) + XCTAssertEqual(carried, [slimmable]) + } + + // MARK: - the running audit + + func testProcessIDsComeFromTheEnvironmentMarker() { + let ps = """ + 10 /bin/a FOO=1 SIMULATOR_UDID=\(dst) BAR=2 + 11 /bin/b SIMULATOR_UDID=\(src) + 200 /bin/c SIMULATOR_UDID=\(dst) + 10 /bin/dup SIMULATOR_UDID=\(dst) + bad /bin/e SIMULATOR_UDID=\(dst) + -5 /bin/f SIMULATOR_UDID=\(dst) + 12 /bin/g + """ + XCTAssertEqual(Simctl.simulatorProcessIDs(fromPS: ps, udid: dst), [10, 200]) + } + + func testLsofParsingFindsSourcePathsInTheDeviceAndItsLogs() { + let output = """ + p10 + n/dev/null + n\(paths.sourceDeviceDirectory)/data/Library/x + p20 + n\(paths.sourceLogDirectory)/launchd.log + n\(paths.cloneDeviceDirectory)/data/ok + pjunk + n\(paths.sourceDeviceDirectory)/ignored-without-a-pid + """ + let parsed = Simctl.parseCloneLsofOutput(output, paths: paths) + XCTAssertTrue(parsed.hasRecords) + XCTAssertEqual( + parsed.references.map { "\($0.pid) \($0.path)" }, + [ + "10 \(paths.sourceDeviceDirectory)/data/Library/x", + "20 \(paths.sourceLogDirectory)/launchd.log", + ]) + XCTAssertFalse(Simctl.parseCloneLsofOutput("garbage\nx\n", paths: paths).hasRecords) + XCTAssertFalse(Simctl.parseCloneLsofOutput("n/foo\n", paths: paths).hasRecords, "no pid yet") + } + + func testAuditOutcomes() { + let clean = "p10\nn/dev/null\n" + XCTAssertTrue(Simctl.evaluateCloneLsofAudit(clean, commandFailure: nil, paths: paths).complete) + XCTAssertNil(Simctl.evaluateCloneLsofAudit(clean, commandFailure: nil, paths: paths).error) + // lsof exits 1 when a pid exited, but live processes still produced records. + let churn = Simctl.evaluateCloneLsofAudit(clean, commandFailure: "exit status 1", paths: paths) + XCTAssertTrue(churn.complete) + XCTAssertNil(churn.error) + let leak = Simctl.evaluateCloneLsofAudit( + "p10\nn\(paths.sourceDeviceDirectory)/data/f\n", commandFailure: "exit status 1", paths: paths + ) + XCTAssertTrue(leak.complete) + XCTAssertEqual( + leak.error, + "clone process 10 still has a source simulator path open: \(paths.sourceDeviceDirectory)/data/f" + ) + let empty = Simctl.evaluateCloneLsofAudit("", commandFailure: "exit status 1", paths: paths) + XCTAssertFalse(empty.complete) + XCTAssertEqual(empty.error, "audit cloned simulator open files: exit status 1") + let said = Simctl.evaluateCloneLsofAudit( + " boom \n", commandFailure: "exit status 1", paths: paths) + XCTAssertEqual(said.error, "audit cloned simulator open files: exit status 1: boom") + let silent = Simctl.evaluateCloneLsofAudit("", commandFailure: nil, paths: paths) + XCTAssertFalse(silent.complete) + XCTAssertEqual( + silent.error, "audit cloned simulator open files returned no process or path records") + } + + // MARK: - validation + + func testValidationRejectsBadDirectoriesAndEqualUDIDs() throws { + XCTAssertEqual(message { try validateCloneFilesystem(self.paths) }, "") + var same = paths + same.cloneUDID = src + XCTAssertTrue(message { try validateCloneFilesystem(same) }.contains("must be distinct")) + var empty = paths + empty.sourceUDID = "" + XCTAssertTrue(message { try validateCloneFilesystem(empty) }.contains("must be distinct")) + var missing = paths + missing.cloneDeviceDirectory += "-gone" + XCTAssertTrue( + message { try validateCloneFilesystem(missing) }.contains("locate clone device directory")) + + // A data directory that is a symlink is not a real directory. + try fm.removeItem(atPath: cloneData) + try fm.createSymbolicLink(atPath: cloneData, withDestinationPath: sourceData) + XCTAssertTrue( + message { try validateCloneFilesystem(self.paths) }.contains( + "clone data path is not a real directory")) + } + + func testValidationRejectsADataDirectoryOutsideItsDevice() throws { + var wrong = paths + wrong.cloneDataDirectory = sourceData + XCTAssertTrue(message { try validateCloneFilesystem(wrong) }.contains("refusing")) + } + + // MARK: - generated stores + + func testLaunchServicesStoresAreRemovedAndNothingElse() throws { + let lsd = cloneData + "/var/db/lsd" + try write(lsd + "/com.apple.LaunchServices-6040.csstore") + try write(lsd + "/com.apple.LaunchServices-ConfigV2.csstore.sb") + try write(lsd + "/com.apple.LaunchServices-keep.txt") + try write(lsd + "/other.csstore") + try resetClonedLaunchServices(dataDirectory: cloneData) + XCTAssertFalse(exists(lsd + "/com.apple.LaunchServices-6040.csstore")) + XCTAssertFalse(exists(lsd + "/com.apple.LaunchServices-ConfigV2.csstore.sb")) + XCTAssertTrue(exists(lsd + "/com.apple.LaunchServices-keep.txt"), "needs .csstore in the name") + XCTAssertTrue(exists(lsd + "/other.csstore"), "needs the LaunchServices- prefix") + } + + func testAMissingLaunchServicesDirectoryIsFine() throws { + XCTAssertEqual(message { try resetClonedLaunchServices(dataDirectory: self.cloneData) }, "") + XCTAssertEqual(message { try resetClonedFrontBoard(dataDirectory: self.cloneData) }, "") + } + + func testLaunchServicesRefusesAnythingButRealFilesAndDirectories() throws { + let lsd = cloneData + "/var/db/lsd" + try fm.createDirectory( + atPath: lsd + "/com.apple.LaunchServices-1.csstore", withIntermediateDirectories: true) + XCTAssertTrue( + message { try resetClonedLaunchServices(dataDirectory: self.cloneData) } + .contains("cloned LaunchServices store is not a regular file")) + XCTAssertTrue(exists(lsd + "/com.apple.LaunchServices-1.csstore")) + + try fm.removeItem(atPath: lsd + "/com.apple.LaunchServices-1.csstore") + try write(sourceData + "/victim.csstore") + try fm.createSymbolicLink( + atPath: lsd + "/com.apple.LaunchServices-2.csstore", + withDestinationPath: sourceData + "/victim.csstore") + XCTAssertTrue( + message { try resetClonedLaunchServices(dataDirectory: self.cloneData) } + .contains("not a regular file")) + XCTAssertTrue(exists(sourceData + "/victim.csstore"), "a link is never followed") + + try fm.removeItem(atPath: cloneData + "/var/db/lsd") + try fm.createSymbolicLink(atPath: cloneData + "/var/db/lsd", withDestinationPath: sourceData) + XCTAssertTrue( + message { try resetClonedLaunchServices(dataDirectory: self.cloneData) } + .contains("cloned LaunchServices path is not a real directory")) + } + + func testFrontBoardRemovesOnlyItsThreeDatabaseFiles() throws { + let dir = cloneData + "/Library/FrontBoard" + for name in [ + "applicationState.db", "applicationState.db-shm", "applicationState.db-wal", "keep.db", + ] { + try write(dir + "/" + name) + } + try resetClonedFrontBoard(dataDirectory: cloneData) + XCTAssertFalse(exists(dir + "/applicationState.db")) + XCTAssertFalse(exists(dir + "/applicationState.db-shm")) + XCTAssertFalse(exists(dir + "/applicationState.db-wal")) + XCTAssertTrue(exists(dir + "/keep.db")) + try fm.removeItem(atPath: dir + "/keep.db") + try fm.createDirectory(atPath: dir + "/applicationState.db", withIntermediateDirectories: true) + XCTAssertTrue( + message { try resetClonedFrontBoard(dataDirectory: self.cloneData) } + .contains("cloned FrontBoard store is not a regular file")) + } + + func testGeneratedPathStateIsClearedButItsDirectoriesAndNeighboursStay() throws { + let cleared = [ + "Library/AppleMediaServices/Engagement/internal/database", "Library/Spotlight", + "Library/chronod/replicator", "Library/com.apple.nsurlsessiond", + "private/var/MobileAsset/AssetsV2/locks", "private/var/MobileAsset/AssetsV2/persisted", + "private/var/db/assetsubscriptiond/history", "var/db/diagnostics/Persist", + "var/db/diagnostics/Special", "Containers/Shared/AppGroup/G1/replicatord", + "Containers/Shared/AppGroup/.hidden/replicatord", + ] + for dir in cleared { + try write("\(cloneData)/\(dir)/a.db") + try write("\(cloneData)/\(dir)/sub/b.db") + } + let kept = [ + "private/var/MobileAsset/AssetsV2/downloads/payload", "Library/Spotlight-other/x", + "var/db/diagnostics/Other/x", "Containers/Shared/AppGroup/G1/keep", "Documents/doc", + "Containers/Data/Application/APP/Documents/d", + ] + for file in kept { try write("\(cloneData)/\(file)") } + try write(cloneData + "/Containers/Shared/AppGroup/not-a-group-dir") + + try resetClonedGeneratedPathState(dataDirectory: cloneData) + for dir in cleared { + var isDir: ObjCBool = false + XCTAssertTrue(fm.fileExists(atPath: "\(cloneData)/\(dir)", isDirectory: &isDir), dir) + XCTAssertTrue(isDir.boolValue) + XCTAssertEqual(try fm.contentsOfDirectory(atPath: "\(cloneData)/\(dir)"), [], dir) + } + for file in kept { XCTAssertTrue(exists("\(cloneData)/\(file)"), file) } + } + + func testAnInTreeSymlinkCannotRedirectGeneratedStateCleanupIntoUserData() throws { + try write(cloneData + "/Media/photos/p.jpg") + try fm.createDirectory(atPath: cloneData + "/private/var/db", withIntermediateDirectories: true) + // `var` is a link: var/db/diagnostics/Persist would land in Media. + try fm.createDirectory( + atPath: cloneData + "/Media/db/diagnostics/Persist", withIntermediateDirectories: true) + try write(cloneData + "/Media/db/diagnostics/Persist/precious") + try fm.createSymbolicLink(atPath: cloneData + "/var", withDestinationPath: cloneData + "/Media") + let text = message { try resetClonedGeneratedPathState(dataDirectory: self.cloneData) } + XCTAssertTrue(text.contains("refusing symlinked cleanup path"), text) + XCTAssertTrue(exists(cloneData + "/Media/db/diagnostics/Persist/precious")) + XCTAssertTrue(exists(cloneData + "/Media/photos/p.jpg")) + } + + func testASymlinkedAppGroupIsRefusedNotFollowed() throws { + try write(cloneData + "/Documents/replicatord/precious") + try fm.createDirectory( + atPath: cloneData + "/Containers/Shared/AppGroup", withIntermediateDirectories: true) + try fm.createSymbolicLink( + atPath: cloneData + "/Containers/Shared/AppGroup/G", + withDestinationPath: cloneData + "/Documents") + let text = message { try resetClonedGeneratedPathState(dataDirectory: self.cloneData) } + XCTAssertTrue(text.contains("refusing symlinked cleanup path"), text) + XCTAssertTrue(exists(cloneData + "/Documents/replicatord/precious")) + } + + func testTransientStateIsClearedBySanitize() throws { + try write(cloneData + "/Library/Caches/c/cache.bin") + try write(cloneData + "/tmp/t.tmp") + try write(cloneData + "/Library/Preferences/keep.txt") + try sanitizeClonedDevice(paths) + XCTAssertEqual(try fm.contentsOfDirectory(atPath: cloneData + "/Library/Caches"), []) + XCTAssertEqual(try fm.contentsOfDirectory(atPath: cloneData + "/tmp"), []) + XCTAssertTrue(exists(cloneData + "/Library/Preferences/keep.txt")) + } + + // MARK: - rebasing + + func testPropertyListsPointAtTheCloneAndKeepTheirMode() throws { + let xml = "file://\(sourceData)/Media/wall.jpg" + let target = cloneData + "/Library/Preferences/a.plist" + try write(target, xml) + XCTAssertEqual(chmod(target, 0o600), 0) + let upper = cloneData + "/Library/Preferences/B.PLIST" + try write(upper, "ref \(src) and again \(src)") + let untouched = cloneData + "/Library/Preferences/c.plist" + try write(untouched, "nothing here") + let other = cloneData + "/Library/Preferences/notes.txt" + try write(other, "ref \(src)") + var before = stat() + XCTAssertEqual(stat(untouched, &before), 0) + + try rebaseClonePropertyLists(paths) + + XCTAssertEqual( + try String(contentsOfFile: target, encoding: .utf8), + xml.replacingOccurrences(of: src, with: dst)) + XCTAssertEqual( + try String(contentsOfFile: upper, encoding: .utf8), "ref \(dst) and again \(dst)") + XCTAssertEqual( + try String(contentsOfFile: other, encoding: .utf8), "ref \(src)", "only .plist files") + var after = stat() + XCTAssertEqual(stat(untouched, &after), 0) + XCTAssertEqual(before.st_ino, after.st_ino, "a file with nothing to change is not rewritten") + var info = stat() + XCTAssertEqual(stat(target, &info), 0) + XCTAssertEqual(info.st_mode & 0o777, 0o600) + XCTAssertEqual( + try fm.contentsOfDirectory(atPath: cloneData + "/Library/Preferences").filter { + $0.hasPrefix(".simslim") + }, [], + "no temporary file is left behind") + } + + func testBinaryPropertyListBytesAreReplacedInPlace() throws { + let path = cloneData + "/a.plist" + var bytes = Data([0x62, 0x70, 0x6C, 0x69, 0x73, 0x74, 0x00, 0xFF]) + bytes.append(Data(src.utf8)) + bytes.append(0x00) + try bytes.write(to: URL(fileURLWithPath: path)) + try rebaseClonePropertyLists(paths) + var expected = Data([0x62, 0x70, 0x6C, 0x69, 0x73, 0x74, 0x00, 0xFF]) + expected.append(Data(dst.utf8)) + expected.append(0x00) + XCTAssertEqual(try Data(contentsOf: URL(fileURLWithPath: path)), expected) + } + + func testPropertyListRebaseNeedsEqualLengthUDIDs() { + var short = paths + short.cloneUDID = "SHORT" + XCTAssertEqual( + message { try rebaseClonePropertyLists(short) }, + "source and clone UDIDs must have equal lengths") + } + + func testPropertyListsOutsideTheCloneAreNeverTouched() throws { + let sourcePlist = sourceData + "/a.plist" + try write(sourcePlist, "ref \(src)") + try rebaseClonePropertyLists(paths) + XCTAssertEqual(try String(contentsOfFile: sourcePlist, encoding: .utf8), "ref \(src)") + } + + func testSymlinksIntoTheSourceAreRebasedAbsoluteAndRelative() throws { + try write(sourceData + "/Media/file") + let lib = cloneData + "/Library" + try fm.createDirectory(atPath: lib, withIntermediateDirectories: true) + try fm.createSymbolicLink(atPath: lib + "/abs", withDestinationPath: sourceData + "/Media/file") + try fm.createSymbolicLink( + atPath: lib + "/rel", withDestinationPath: "../../../\(src)/data/Media/file") + try fm.createSymbolicLink(atPath: lib + "/logs", withDestinationPath: paths.sourceLogDirectory) + try fm.createSymbolicLink( + atPath: lib + "/logfile", withDestinationPath: paths.sourceLogDirectory + "/launchd.log") + try fm.createSymbolicLink(atPath: lib + "/self", withDestinationPath: cloneData + "/Media") + try fm.createSymbolicLink(atPath: lib + "/elsewhere", withDestinationPath: "/usr/lib") + try fm.createSymbolicLink(atPath: lib + "/sibling", withDestinationPath: "../Media") + + try rebaseCloneSymlinks(paths) + + func dest(_ name: String) throws -> String { + try fm.destinationOfSymbolicLink(atPath: lib + "/" + name) + } + XCTAssertEqual(try dest("abs"), cloneData + "/Media/file") + XCTAssertEqual(try dest("rel"), "../Media/file", "a relative link stays relative") + XCTAssertEqual(try dest("logs"), paths.cloneLogDirectory) + XCTAssertEqual(try dest("logfile"), paths.cloneLogDirectory + "/launchd.log") + XCTAssertEqual(try dest("self"), cloneData + "/Media") + XCTAssertEqual(try dest("elsewhere"), "/usr/lib") + XCTAssertEqual(try dest("sibling"), "../Media") + XCTAssertEqual( + try fm.contentsOfDirectory(atPath: lib).filter { $0.hasPrefix(".simslim") }, []) + } + + func testRebasingNeverFollowsOrTouchesTheSource() throws { + try fm.createSymbolicLink(atPath: sourceData + "/link", withDestinationPath: sourceData + "/x") + // A clone link to a directory in the source must be replaced, not entered. + try write(sourceData + "/dir/inner") + try fm.createSymbolicLink( + atPath: cloneData + "/dirlink", withDestinationPath: sourceData + "/dir") + try rebaseCloneSymlinks(paths) + XCTAssertEqual( + try fm.destinationOfSymbolicLink(atPath: cloneData + "/dirlink"), cloneData + "/dir") + XCTAssertEqual( + try fm.destinationOfSymbolicLink(atPath: sourceData + "/link"), sourceData + "/x") + XCTAssertTrue(exists(sourceData + "/dir/inner")) + } + + // MARK: - independence + + func testIndependenceFlagsLinksIntoTheSourceAndNamingItsUDID() throws { + try fm.createSymbolicLink(atPath: cloneData + "/a", withDestinationPath: sourceData + "/x") + XCTAssertTrue( + message { try verifyCloneIndependence(self.paths) }.contains( + "still resolves into the source simulator")) + try fm.removeItem(atPath: cloneData + "/a") + + try fm.createSymbolicLink(atPath: cloneData + "/b", withDestinationPath: "/elsewhere/\(src)/y") + XCTAssertTrue( + message { try verifyCloneIndependence(self.paths) }.contains( + "still resolves into the source simulator")) + try fm.removeItem(atPath: cloneData + "/b") + + // A dangling relative link whose text names the source is caught too. + try fm.createSymbolicLink(atPath: cloneData + "/c", withDestinationPath: "../\(src)/z") + XCTAssertTrue( + message { try verifyCloneIndependence(self.paths) }.contains( + "still resolves into the source simulator")) + try fm.removeItem(atPath: cloneData + "/c") + + try fm.createSymbolicLink(atPath: cloneData + "/ok", withDestinationPath: cloneData + "/Media") + XCTAssertEqual(message { try verifyCloneIndependence(self.paths) }, "") + } + + func testIndependenceFlagsAHardLinkToTheSource() throws { + try write(sourceData + "/Media/shared.bin") + try write(cloneData + "/Media/copy.bin") + try write(sourceData + "/Media/copy.bin", "different file, same name") + XCTAssertEqual( + message { try verifyCloneIndependence(self.paths) }, "", "same name, different file") + + try fm.removeItem(atPath: cloneData + "/Media/copy.bin") + XCTAssertEqual(link(sourceData + "/Media/copy.bin", cloneData + "/Media/copy.bin"), 0) + let text = message { try verifyCloneIndependence(self.paths) } + XCTAssertTrue(text.contains("is hard-linked to the source simulator"), text) + } + + func testIndependenceIgnoresFilesWithNoSourceCounterpart() throws { + try write(cloneData + "/only-in-clone") + XCTAssertEqual(message { try verifyCloneIndependence(self.paths) }, "") + } + + func testSanitizeEndToEndLeavesACloneThatPassesTheCheck() throws { + try write(sourceData + "/Media/photo.jpg", "photo") + try write(cloneData + "/Media/photo.jpg", "photo") + try write(cloneData + "/var/db/lsd/com.apple.LaunchServices-1.csstore") + try write( + cloneData + "/Library/Preferences/p.plist", "\(sourceData)/Media/photo.jpg") + try fm.createSymbolicLink( + atPath: cloneData + "/Library/Logs", withDestinationPath: paths.sourceLogDirectory) + try sanitizeClonedDevice(paths) + XCTAssertFalse(exists(cloneData + "/var/db/lsd/com.apple.LaunchServices-1.csstore")) + XCTAssertEqual( + try fm.destinationOfSymbolicLink(atPath: cloneData + "/Library/Logs"), paths.cloneLogDirectory + ) + XCTAssertEqual( + try String(contentsOfFile: cloneData + "/Library/Preferences/p.plist", encoding: .utf8), + "\(cloneData)/Media/photo.jpg") + XCTAssertEqual( + try String(contentsOfFile: cloneData + "/Media/photo.jpg", encoding: .utf8), "photo") + } + + func testSanitizeFailsRatherThanLeavingAnUnsafeClone() throws { + // A link the rebase cannot express still names the source: the final check fails. + try fm.createSymbolicLink(atPath: cloneData + "/x", withDestinationPath: "/elsewhere/\(src)/f") + XCTAssertTrue( + message { try sanitizeClonedDevice(self.paths) }.contains("still resolves into the source")) + } + + // MARK: - review follow-ups + + func testLsofPathsNamingTheSourceUDIDAreFlaggedEvenUnderADifferentRoot() { + // CoreSimulator moved to another volume: lsof prints the real path. + let output = "p10\nn/Volumes/External/CoreSimulator/Devices/\(src)/data/f\n" + let parsed = Simctl.parseCloneLsofOutput(output, paths: paths) + XCTAssertEqual(parsed.references.map(\.pid), [10]) + let clean = Simctl.parseCloneLsofOutput( + "p10\nn/Volumes/External/CoreSimulator/Devices/\(dst)/data/f\n", paths: paths) + XCTAssertTrue(clean.references.isEmpty) + } + + func testValidationRequiresThePathsToLookLikeSetUDIDData() throws { + var wrongName = paths + wrongName.cloneDeviceDirectory = "\(root)/devices" + wrongName.cloneDataDirectory = "\(root)/devices/\(dst)/data" + XCTAssertNotEqual(message { try validateCloneFilesystem(wrongName) }, "") + + try fm.createDirectory( + atPath: "\(root)/devices/\(dst)/notdata", withIntermediateDirectories: true) + var wrongData = paths + wrongData.cloneDataDirectory = "\(root)/devices/\(dst)/notdata" + XCTAssertTrue( + message { try validateCloneFilesystem(wrongData) }.contains("is not /\(dst)/data") + ) + + var lower = paths + lower.sourceUDID = src.lowercased() + XCTAssertEqual( + message { try validateCloneFilesystem(lower) }, "", "UDID case is not significant") + + var same = paths + same.cloneUDID = src.lowercased() + same.cloneDeviceDirectory = paths.sourceDeviceDirectory + same.cloneDataDirectory = paths.sourceDataDirectory + XCTAssertTrue(message { try validateCloneFilesystem(same) }.contains("must be distinct")) + } + + func testAFileThatVanishesMidWalkIsSkippedWhenAsked() throws { + for name in ["a", "b", "c"] { try write("\(cloneData)/\(name)") } + var visited: [String] = [] + try walkTree(cloneData, skippingVanished: true) { path, _ in + visited.append((path as NSString).lastPathComponent) + if path.hasSuffix("/a") { try? FileManager.default.removeItem(atPath: self.cloneData + "/b") } + return .descend + } + XCTAssertEqual(visited, ["data", "a", "c"]) + try write(cloneData + "/b") + XCTAssertThrowsError( + try walkTree(cloneData) { path, _ in + if path.hasSuffix("/a") { + try? FileManager.default.removeItem(atPath: self.cloneData + "/b") + } + return .descend + }, "the default stays strict") + } + + func testAFileInTheSourceAndADirectoryInTheCloneIsNotAnError() throws { + try write(sourceData + "/x", "file") + try write(cloneData + "/x/inside", "dir") + XCTAssertEqual(message { try verifyCloneIndependence(self.paths) }, "") + } + + func testAnAppGroupDirectoryThatIsAFileIsRefused() throws { + try write(cloneData + "/Containers/Shared/AppGroup", "not a directory") + XCTAssertTrue( + message { try resetClonedGeneratedPathState(dataDirectory: self.cloneData) } + .contains("is not a real directory")) + try fm.removeItem(atPath: cloneData + "/Containers/Shared/AppGroup") + XCTAssertEqual( + message { try resetClonedGeneratedPathState(dataDirectory: self.cloneData) }, "", + "absent is fine") + } +} diff --git a/swift/Tests/SimSlimKitTests/CloneTests.swift b/swift/Tests/SimSlimKitTests/CloneTests.swift new file mode 100644 index 0000000..d1e95a9 --- /dev/null +++ b/swift/Tests/SimSlimKitTests/CloneTests.swift @@ -0,0 +1,572 @@ +// Copyright (c) 2026 Pavel Akhrameev (Swift port). MIT License; see LICENSE. + +import Foundation +import TestSupport +import XCTest + +@testable import SimSlimKit + +/// A clock that only moves when the code under test sleeps. +private final class Clock: @unchecked Sendable { + private let lock = NSLock() + private var current = Date(timeIntervalSince1970: 1_000_000) + var now: Date { + lock.lock() + defer { lock.unlock() } + return current + } + func advance(_ seconds: TimeInterval) { + lock.lock() + current = current.addingTimeInterval(seconds) + lock.unlock() + } +} + +private final class Flag: @unchecked Sendable { + private let lock = NSLock() + private var value = false + private var counter = 0 + var isSet: Bool { + lock.lock() + defer { lock.unlock() } + return value + } + func set() { + lock.lock() + value = true + lock.unlock() + } + func bump() -> Int { + lock.lock() + defer { lock.unlock() } + counter += 1 + return counter + } +} + +final class CloneTests: XCTestCase { + private let src = "AAAAAAAA-0000-0000-0000-000000000001" + private let dst = "BBBBBBBB-0000-0000-0000-000000000002" + private var root = "" + private let fm = FileManager.default + private var label: String { Catalog.categories[0].labels[0] } + private let unmanaged = "com.example.not-simslim" + + override func setUpWithError() throws { + root = try resolvedPath(NSTemporaryDirectory()) + "/simslim-clone-\(UUID().uuidString)" + try fm.createDirectory(atPath: root + "/store", withIntermediateDirectories: true) + } + + override func tearDown() { try? fm.removeItem(atPath: root) } + + private var home: String { root + "/home" } + private func data(_ udid: String) -> String { "\(root)/devices/\(udid)/data" } + + private func write(_ path: String, _ text: String = "x") throws { + try fm.createDirectory( + atPath: (path as NSString).deletingLastPathComponent, withIntermediateDirectories: true) + try Data(text.utf8).write(to: URL(fileURLWithPath: path)) + } + + /// A host with a source simulator (and, for repair, the clone as well). + private func host( + source: String = "Shutdown", clone: String? = nil, + cloneRuntime: String = "com.apple.CoreSimulator.SimRuntime.iOS-27-2" + ) throws -> FakeHost { + var devices: [FakeHost.FakeDevice] = [.init(udid: src, name: "Source", state: source)] + try write(data(src) + "/Media/photo.jpg", "photo") + if let clone { + devices.append(.init(udid: dst, name: "Old clone", runtime: cloneRuntime, state: clone)) + try fm.createDirectory(atPath: data(dst), withIntermediateDirectories: true) + } + let host = FakeHost(devices: devices) + host.dataRoot = root + "/devices" + host.storeRoot = root + "/store" + host.disabled[src] = [label, unmanaged] + host.cloneUDIDs = [dst] + host.psOutput = "10 /usr/bin/launchd_sim SIMULATOR_UDID=\(dst)\n" + return host + } + + private func simctl(_ host: FakeHost) -> Simctl { + var simctl = Simctl(runner: host) + simctl.retryDelays = [0, 0, 0, 0] + let clock = Clock() + simctl.now = { clock.now } + simctl.sleep = { clock.advance($0) } + simctl.storeRoot = root + "/store" + return simctl + } + + private func clone(_ host: FakeHost, name: String = "Clone") throws -> String { + try simctl(host).cloneDevice(udid: src, name: name, home: home, restoreTimeout: 60) + } + + private func repair(_ host: FakeHost) throws { + try simctl(host).repairClonedDevice( + sourceUDID: src, cloneUDID: dst, home: home, restoreTimeout: 60) + } + + private func state(_ host: FakeHost, _ udid: String) -> String? { + host.devices.first { $0.udid == udid }?.state + } + + private func verbs(_ host: FakeHost) -> [String] { + host.calls.compactMap { call -> String? in + guard call.executable == .xcrun else { return nil } + var args = call.arguments + if args.count > 2, args[1] == "--set" { args.removeSubrange(1...2) } + guard args.count > 2, ["boot", "shutdown", "clone", "delete"].contains(args[1]) else { + return nil + } + return args[1] + ":" + (args[2] == src ? "src" : args[2] == dst ? "dst" : args[2]) + } + } + + private func failure(_ body: () throws -> Void) -> String { + do { + try body() + return "" + } catch { return "\(error)" } + } + + // MARK: - clone + + func testACloneOfAShutDownSourceLeavesBothShutDown() throws { + let host = try host() + XCTAssertEqual(try clone(host, name: " My Clone "), dst) + XCTAssertEqual(state(host, src), "Shutdown") + XCTAssertEqual(state(host, dst), "Shutdown") + XCTAssertEqual(host.devices.first { $0.udid == dst }?.name, "My Clone") + } + + func testACloneOfABootedSourceBringsTheSourceBack() throws { + let host = try host(source: "Booted") + XCTAssertEqual(try clone(host), dst) + XCTAssertEqual(state(host, src), "Booted") + XCTAssertEqual(state(host, dst), "Shutdown") + } + + func testTheSourceIsShutDownBeforeTheCopyAndTheCloneBeforeItIsReturned() throws { + let host = try host(source: "Booted") + _ = try clone(host) + let order = verbs(host) + let copy = try XCTUnwrap(order.firstIndex(of: "clone:src")) + XCTAssertTrue(order[..\(src)") + host.disabled[dst] = [label] + try repair(host) + XCTAssertEqual( + try fm.destinationOfSymbolicLink(atPath: data(dst) + "/Logs"), data(dst) + "/Media") + XCTAssertEqual( + try String(contentsOfFile: data(dst) + "/Library/p.plist", encoding: .utf8), "\(dst)") + XCTAssertEqual(state(host, dst), "Shutdown") + XCTAssertEqual(state(host, src), "Shutdown") + XCTAssertTrue(host.disabled[dst]?.contains(label) == true, "its service profile is kept") + } + + func testRepairKeepsBothBootedSimulatorsBooted() throws { + let host = try host(source: "Booted", clone: "Booted") + host.disabled[dst] = [label, unmanaged] + try repair(host) + XCTAssertEqual(state(host, src), "Booted") + XCTAssertEqual(state(host, dst), "Booted") + XCTAssertEqual(verbs(host).filter { $0 == "shutdown:src" }.count, 1) + } + + func testRepairShutsBothDownBeforeRebuildingAnything() throws { + let host = try host(source: "Booted", clone: "Booted") + host.disabled[dst] = [label] + try repair(host) + let order = verbs(host) + XCTAssertEqual(order.prefix(2), ["shutdown:dst", "shutdown:src"], "\(order)") + XCTAssertEqual(order.last, "boot:src") + } + + func testRepairRefusesWhatItCannotTrust() throws { + let host = try host(source: "Shutdown", clone: "Shutdown") + XCTAssertEqual( + failure { + try self.simctl(host).repairClonedDevice( + sourceUDID: self.src, cloneUDID: self.src, home: self.home, restoreTimeout: 60) + }, + "clone source and destination UDIDs must be distinct") + XCTAssertEqual(verbs(host), []) + + let other = try self.host( + source: "Shutdown", clone: "Shutdown", + cloneRuntime: "com.apple.CoreSimulator.SimRuntime.iOS-18-4") + XCTAssertEqual( + failure { try self.repair(other) }, "source and clone runtimes differ (iOS 27.2 and iOS 18.4)" + ) + let tv = try self.host( + source: "Shutdown", clone: "Shutdown", + cloneRuntime: "com.apple.CoreSimulator.SimRuntime.tvOS-27-2") + XCTAssertTrue(failure { try self.repair(tv) }.contains("runtimes differ")) + + for (s, c) in [("Booting", "Shutdown"), ("Shutdown", "Shutting Down")] { + let busy = try self.host(source: s, clone: c) + let bad = s == "Booting" ? src : dst + let current = s == "Booting" ? s : c + XCTAssertEqual( + failure { try self.repair(busy) }, + "simulator \(bad) must be booted or shutdown before repair (it is \(current))") + XCTAssertEqual(verbs(busy), []) + } + XCTAssertEqual( + try String(contentsOfFile: data(src) + "/Media/photo.jpg", encoding: .utf8), "photo") + } + + func testRepairRefusesACloneInAnotherDeviceSet() throws { + let host = try host(source: "Shutdown", clone: nil) + host.sets["testing"] = [.init(udid: dst, name: "Elsewhere")] + try fm.createDirectory(atPath: data(dst), withIntermediateDirectories: true) + XCTAssertEqual( + failure { try self.repair(host) }, "source and clone must belong to the same simulator set") + XCTAssertEqual(verbs(host), []) + } + + func testAFailedRepairLeavesTheCloneShutDownAndTheSourceRestored() throws { + let host = try host(source: "Booted", clone: "Booted") + host.disabled[dst] = [label] + try fm.createSymbolicLink( + atPath: data(dst) + "/bad", withDestinationPath: "/elsewhere/\(src)/f") + let text = failure { try self.repair(host) } + XCTAssertTrue(text.contains("still resolves into the source simulator"), text) + XCTAssertEqual(state(host, dst), "Shutdown", "left safely shut down") + XCTAssertEqual(state(host, src), "Booted") + XCTAssertNotNil(state(host, dst), "a repair never deletes the clone") + } + + func testARepairWhoseAuditFindsAnOpenSourceFileFailsSafely() throws { + let host = try host(source: "Shutdown", clone: "Booted") + host.disabled[dst] = [label] + host.psOutput = "10 /x SIMULATOR_UDID=\(dst)\n" + let leaked = "\(root)/devices/\(src)/data/f" + host.lsofResult = { pids in + CommandResult(status: 0, stdout: Data("p\(pids[0])\nn\(leaked)\n".utf8)) + } + let text = failure { try self.repair(host) } + XCTAssertTrue(text.contains("still has a source simulator path open"), text) + XCTAssertEqual(state(host, dst), "Shutdown") + } + + func testAFailedRepairThatCannotShutTheCloneDownSaysSo() throws { + let host = try host(source: "Shutdown", clone: "Shutdown") + host.disabled[dst] = [label] + let leaked = "\(root)/devices/\(src)/data/f" + host.lsofResult = { pids in + CommandResult(status: 0, stdout: Data("p\(pids[0])\nn\(leaked)\n".utf8)) + } + nonisolated(unsafe) let fake = host + host.onCall = { exe, args in + if exe == .xcrun, args.contains("bootstatus") { fake.stuckBooted = true } + } + let text = failure { try self.repair(host) } + XCTAssertTrue(text.contains("still has a source simulator path open"), text) + XCTAssertTrue(text.contains("; additionally could not leave the clone safely shutdown: "), text) + } + + func testRepairOnlyTouchesTheCloneNeverTheSource() throws { + let host = try host(source: "Shutdown", clone: "Shutdown") + try write(data(src) + "/Library/p.plist", "\(src)") + try fm.createSymbolicLink(atPath: data(src) + "/l", withDestinationPath: data(src) + "/Media") + host.disabled[dst] = [] + try repair(host) + XCTAssertEqual( + try String(contentsOfFile: data(src) + "/Library/p.plist", encoding: .utf8), "\(src)") + XCTAssertEqual(try fm.destinationOfSymbolicLink(atPath: data(src) + "/l"), data(src) + "/Media") + } + + // MARK: - review follow-ups + + func testACloneUDIDThatNamesTheSourceOrAnyExistingSimulatorDeletesNothing() throws { + for output in [src, src.lowercased(), "CCCCCCCC-0000-0000-0000-000000000003"] { + let host = try host(source: "Booted") + host.devices.append(.init(udid: "CCCCCCCC-0000-0000-0000-000000000003", name: "Bystander")) + host.cloneOutput = output + "\n" + let text = failure { _ = try self.clone(host) } + XCTAssertTrue( + text.contains("returned the UDID of an existing simulator"), "\(output): \(text)") + XCTAssertFalse(verbs(host).contains { $0.hasPrefix("delete:") }, "\(output): \(verbs(host))") + XCTAssertNotNil(state(host, src), "the source survives") + XCTAssertNotNil(state(host, "CCCCCCCC-0000-0000-0000-000000000003")) + XCTAssertEqual(state(host, src), "Booted") + } + } + + func testACloneCreatedInAnotherSetIsReported() throws { + let host = try host() + host.cloneIntoSet = "testing" + let text = failure { _ = try self.clone(host) } + XCTAssertTrue( + text.contains("CoreSimulator placed clone \(dst) in testing instead of source set default"), + text) + } + + func testCleanupStillRunsAfterTheOperationBudgetIsSpent() throws { + let host = try host(source: "Booted") + let clock = Clock() + var handle = simctl(host) + handle.now = { clock.now } + handle.sleep = { clock.advance($0) } + handle.deadline = clock.now.addingTimeInterval(100) + let dstID = dst + host.onCall = { exe, args in + if exe == .xcrun, args.contains("bootstatus"), args.contains(dstID) { clock.advance(1000) } + } + let text = failure { + _ = try handle.cloneDevice(udid: self.src, name: "x", home: self.home, restoreTimeout: 60) + } + XCTAssertTrue(text.contains("context deadline exceeded"), text) + XCTAssertTrue(text.hasSuffix("; deleted the unsafe clone"), text) + XCTAssertNil(state(host, dst)) + XCTAssertEqual(state(host, src), "Booted", "the restore ran on a fresh budget") + } + + func testTheAuditStopsWhenTheBudgetRunsOutBetweenAttempts() throws { + let host = try host() + host.psOutput = "" + let clock = Clock() + var handle = simctl(host) + handle.now = { clock.now } + handle.sleep = { clock.advance($0) } + handle.deadline = clock.now.addingTimeInterval(1000) + host.onCall = { exe, _ in if exe == .ps { clock.advance(2000) } } + let text = failure { + _ = try handle.cloneDevice(udid: self.src, name: "x", home: self.home, restoreTimeout: 60) + } + XCTAssertTrue( + text.contains("audit cloned simulator open files: context deadline exceeded"), text) + } + + func testAnLsofThatTimesOutIsRetriedAndThenReported() throws { + let host = try host() + host.lsofResult = { _ in CommandResult(status: -9, timedOut: true) } + let text = failure { _ = try self.clone(host) } + XCTAssertTrue(text.contains("audit cloned simulator open files: signal: killed"), text) + XCTAssertNil(state(host, dst)) + } + + func testRepairNeverFollowsALinkIntoTheSourceToRewriteItsPropertyLists() throws { + let host = try host(source: "Shutdown", clone: "Shutdown") + host.disabled[dst] = [] + try write(data(src) + "/Library/Preferences/a.plist", "\(src)") + try write(data(src) + "/dirwithplist/b.plist", "\(src)") + try write(data(src) + "/lone.plist", "\(src)") + // A link to a source directory, and a .plist that is itself a link to a source file. + try fm.createSymbolicLink( + atPath: data(dst) + "/linkdir", withDestinationPath: data(src) + "/dirwithplist") + try fm.createSymbolicLink( + atPath: data(dst) + "/link.plist", withDestinationPath: data(src) + "/lone.plist") + try repair(host) + for path in ["/Library/Preferences/a.plist", "/dirwithplist/b.plist", "/lone.plist"] { + XCTAssertEqual( + try String(contentsOfFile: data(src) + path, encoding: .utf8), "\(src)", path) + } + XCTAssertEqual( + try fm.destinationOfSymbolicLink(atPath: data(dst) + "/linkdir"), data(dst) + "/dirwithplist") + XCTAssertEqual( + try fm.destinationOfSymbolicLink(atPath: data(dst) + "/link.plist"), data(dst) + "/lone.plist" + ) + } + + func testALinkThatAppearsWhileTheCloneRunsIsCaughtByTheFinalCheck() throws { + let host = try host() + let link = data(dst) + "/appeared-at-boot" + let source = src + let dstID = dst + host.onCall = { exe, args in + // The clone's own daemons create it after the first check, before shutdown. + if exe == .xcrun, args.contains("shutdown"), args.contains(dstID) { + try? FileManager.default.createSymbolicLink( + atPath: link, withDestinationPath: "/elsewhere/\(source)/f") + } + } + let text = failure { _ = try self.clone(host) } + XCTAssertTrue(text.contains("still resolves into the source simulator"), text) + XCTAssertTrue(text.hasSuffix("; deleted the unsafe clone"), text) + XCTAssertNil(state(host, dst)) + } +} diff --git a/swift/Tests/SimSlimKitTests/DiskCleanupSimulatorTests.swift b/swift/Tests/SimSlimKitTests/DiskCleanupSimulatorTests.swift new file mode 100644 index 0000000..b0961fe --- /dev/null +++ b/swift/Tests/SimSlimKitTests/DiskCleanupSimulatorTests.swift @@ -0,0 +1,74 @@ +// Copyright (c) 2026 Pavel Akhrameev (Swift port). MIT License; see LICENSE. + +import TestSupport +import XCTest + +@testable import SimSlimKit + +final class DiskCleanupSimulatorTests: XCTestCase { + func testAnInvalidSelectionIsRefusedBeforeABootedSimulatorIsShutDown() throws { + let udid = "AAAAAAAA-0000-0000-0000-000000000001" + let root = NSTemporaryDirectory() + "simslim-diskkit-\(UUID().uuidString)" + defer { try? FileManager.default.removeItem(atPath: root) } + try FileManager.default.createDirectory( + atPath: "\(root)/\(udid)/data", withIntermediateDirectories: true) + let host = FakeHost(devices: [.init(udid: udid, name: "iPhone", state: "Booted")]) + host.dataRoot = root + host.disabled[udid] = [] + for ids in [["nope"], ["required-siri-assets"], []] as [[String]] { + XCTAssertThrowsError( + try Simctl(runner: host).cleanDeviceDisk( + udid: udid, categoryIDs: ids, preserveBootState: false), "\(ids)") + XCTAssertFalse( + host.calls.contains { $0.arguments.contains("shutdown") }, + "\(ids): the simulator kept running") + } + XCTAssertEqual(host.devices[0].state, "Booted") + } + + func testASimulatorThatIsBootingIsNeverCleanedUnderneath() throws { + let udid = "AAAAAAAA-0000-0000-0000-000000000001" + let root = NSTemporaryDirectory() + "simslim-diskkit-\(UUID().uuidString)" + defer { try? FileManager.default.removeItem(atPath: root) } + let cache = "\(root)/\(udid)/data/Library/Caches/c.bin" + try FileManager.default.createDirectory( + atPath: (cache as NSString).deletingLastPathComponent, withIntermediateDirectories: true) + try Data(count: 4096).write(to: URL(fileURLWithPath: cache)) + for state in ["Booting", "Shutting Down"] { + let host = FakeHost(devices: [.init(udid: udid, name: "iPhone", state: state)]) + host.dataRoot = root + XCTAssertThrowsError( + try Simctl(runner: host).cleanDeviceDisk( + udid: udid, categoryIDs: ["caches"], preserveBootState: false), state + ) { + XCTAssertTrue("\($0)".contains("wait until it is Booted or Shutdown"), "\($0)") + } + XCTAssertTrue(FileManager.default.fileExists(atPath: cache), state) + } + } + + func testACleanupFailureAndARebootFailureAreReportedTogether() throws { + let udid = "AAAAAAAA-0000-0000-0000-000000000001" + let root = NSTemporaryDirectory() + "simslim-diskkit-\(UUID().uuidString)" + defer { try? FileManager.default.removeItem(atPath: root) } + let data = "\(root)/\(udid)/data" + try FileManager.default.createDirectory( + atPath: data + "/Media/log", withIntermediateDirectories: true) + // An in-tree symlink makes the cleanup itself fail. + try FileManager.default.createSymbolicLink( + atPath: data + "/var", withDestinationPath: data + "/Media") + let host = FakeHost(devices: [.init(udid: udid, name: "iPhone", state: "Booted")]) + host.dataRoot = root + host.disabled[udid] = [] + host.bootFailure = "boot refused" + XCTAssertThrowsError( + try Simctl(runner: host).cleanDeviceDisk( + udid: udid, categoryIDs: ["logs"], preserveBootState: true) + ) { + let text = "\($0)" + XCTAssertTrue(text.contains("refusing symlinked cleanup path"), text) + XCTAssertTrue(text.contains("; additionally could not restore boot state: "), text) + XCTAssertTrue(text.contains("boot refused"), text) + } + } +} diff --git a/swift/Tests/SimSlimKitTests/DiskCleanupTests.swift b/swift/Tests/SimSlimKitTests/DiskCleanupTests.swift new file mode 100644 index 0000000..c0604d6 --- /dev/null +++ b/swift/Tests/SimSlimKitTests/DiskCleanupTests.swift @@ -0,0 +1,592 @@ +// Copyright (c) 2026 Pavel Akhrameev (Swift port). MIT License; see LICENSE. + +import XCTest + +@testable import SimSlimKit + +final class DiskCleanupTests: XCTestCase { + private var root = "" + private var data = "" + + override func setUpWithError() throws { + // Resolved, because /var is a symlink to /private/var on macOS: the code + // under test must cope with a data directory that lives behind one. + root = NSTemporaryDirectory() + "simslim-disk-\(UUID().uuidString)" + try FileManager.default.createDirectory(atPath: root, withIntermediateDirectories: true) + data = root + "/data" + try FileManager.default.createDirectory(atPath: data, withIntermediateDirectories: true) + } + + override func tearDown() { + try? FileManager.default.removeItem(atPath: root) + } + + private func write(_ path: String, size: Int = 4096) throws { + try FileManager.default.createDirectory( + atPath: (path as NSString).deletingLastPathComponent, withIntermediateDirectories: true) + try Data(count: size).write(to: URL(fileURLWithPath: path)) + } + + private func exists(_ path: String) -> Bool { + var info = stat() + return lstat(path, &info) == 0 + } + + private func plan() throws -> DiskCleanupPlan { + try diskCleanupPlan(udid: "TEST-UDID", dataDirectory: data) + } + + // MARK: - the model + + func testCategoriesAreUniqueAndSafeByDefault() throws { + var seen = Set() + for category in diskCleanupCategories { + XCTAssertFalse(category.id.isEmpty) + XCTAssertTrue(seen.insert(category.id).inserted, "duplicate \(category.id)") + XCTAssertFalse(category.defaultSelected && !category.canClean, category.id) + } + XCTAssertFalse(try XCTUnwrap(diskCleanupCategory(id: "required-siri-assets")).canClean) + let language = try XCTUnwrap(diskCleanupCategory(id: "linguistic-data")) + XCTAssertTrue(language.canClean) + XCTAssertFalse(language.defaultSelected, "opt-in") + } + + func testRecoveryModelsStayDistinct() throws { + for id in ["caches", "logs", "temporary"] { + XCTAssertTrue(try XCTUnwrap(diskCleanupCategory(id: id)).recovery.contains("deleted"), id) + } + XCTAssertTrue( + try XCTUnwrap(diskCleanupCategory(id: "required-siri-assets")).recovery.contains( + "return automatically")) + let language = try XCTUnwrap(diskCleanupCategory(id: "linguistic-data")) + XCTAssertTrue(language.recovery.contains("downloads")) + XCTAssertEqual(language.risk, "Restored on demand") + } + + func testSelectionValidation() throws { + XCTAssertEqual( + try validateDiskCleanupSelection([" logs ", "caches", "logs", "", " "]), ["caches", "logs"]) + for (ids, message) in [ + ([], "select at least one cleanable disk category"), + ([" ", ""], "select at least one cleanable disk category"), + (["nope"], "unknown disk cleanup category \"nope\""), + ( + ["required-siri-assets"], + "disk cleanup category \"required-siri-assets\" is measured only and cannot be cleaned" + ), + (["caches", "required-siri-assets"], "measured only"), + ] as [([String], String)] { + XCTAssertThrowsError(try validateDiskCleanupSelection(ids), "\(ids)") { + XCTAssertTrue("\($0)".contains(message), "\($0)") + } + } + } + + func testPathHelpers() { + XCTAssertEqual(cleanPath("/a//b/./c/../d/"), "/a/b/d") + XCTAssertEqual(cleanPath("a/../.."), "..") + XCTAssertEqual(cleanPath("/.."), "/") + XCTAssertEqual(cleanPath(""), ".") + XCTAssertTrue(isStrictDescendant("/d", "/d/x")) + XCTAssertTrue(isStrictDescendant("/d/", "/d/x/../y")) + XCTAssertFalse(isStrictDescendant("/d", "/d")) + XCTAssertFalse(isStrictDescendant("/d", "/d/")) + XCTAssertFalse(isStrictDescendant("/d", "/")) + XCTAssertFalse(isStrictDescendant("/d", "/d/../e")) + XCTAssertFalse(isStrictDescendant("/d", "/dx"), "a sibling sharing a prefix is not inside") + XCTAssertFalse(isStrictDescendant("/d/data", "/d/data/..")) + XCTAssertTrue(isStrictDescendant("/", "/x")) + XCTAssertFalse(isStrictDescendant("/", "/")) + } + + func testRequireDescendantRejectsTheRootAndItsParents() throws { + XCTAssertThrowsError(try requireDescendant(data, data)) + XCTAssertThrowsError(try requireDescendant(data, root)) + XCTAssertThrowsError(try requireDescendant(data, data + "/../x")) + XCTAssertNoThrow(try requireDescendant(data, data + "/Library/Caches")) + } + + // MARK: - plan and clean stay inside the allowlist + + func testPlanAndCleanStayInsideTheAllowlist() throws { + let cache = data + "/Library/Caches" + let temp = data + "/Containers/Data/Application/A/tmp" + let diagnostics = data + "/var/db/diagnostics" + let uuidtext = data + "/var/db/uuidtext" + let assets = data + "/private/var/MobileAsset/AssetsV2" + let siri = assets + "/com_apple_MobileAsset_UAF_Siri_Understanding" + let linguistic = assets + "/com_apple_MobileAsset_LinguisticData" + let unrelated = assets + "/com_apple_MobileAsset_PKITrustStore" + let documents = data + "/Containers/Data/Application/A/Documents" + let keep = [ + siri + "/model.bin", unrelated + "/trust.bin", documents + "/user.db", + documents + "/Caches/keep-cache.bin", documents + "/Logs/keep-log.txt", + documents + "/tmp/keep-temp.bin", siri + "/Caches/keep-asset-cache.bin", + ] + let remove = [ + cache + "/cache.bin", temp + "/temp.bin", diagnostics + "/log.tracev3", + uuidtext + "/symbols", linguistic + "/language-model.bin", + ] + for path in remove + keep { try write(path, size: 16 * 1024) } + + let before = try plan() + let byID = Dictionary(uniqueKeysWithValues: before.categories.map { ($0.category.id, $0) }) + for id in ["caches", "logs", "temporary", "linguistic-data", "required-siri-assets"] { + XCTAssertGreaterThan(byID[id]!.bytes, 0, id) + } + XCTAssertGreaterThan(before.cleanableBytes, 0) + XCTAssertGreaterThan(before.totalBytes, before.cleanableBytes) + + let result = try cleanDisk( + udid: "TEST-UDID", dataDirectory: data, + categoryIDs: ["temporary", "logs", "caches", "linguistic-data"]) + XCTAssertGreaterThan(result.reclaimedBytes, 0) + XCTAssertEqual(result.categoryIds, ["caches", "linguistic-data", "logs", "temporary"]) + for path in remove { XCTAssertFalse(exists(path), "left \(path)") } + for directory in [cache, temp, diagnostics, uuidtext, linguistic] { + var info = stat() + XCTAssertEqual(lstat(directory, &info), 0, "the directory itself stays: \(directory)") + } + for path in keep { XCTAssertTrue(exists(path), "touched \(path)") } + } + + func testInstalledBundlesAreNeverTouched() throws { + for (category, name) in [("caches", "Caches"), ("logs", "Logs"), ("temporary", "tmp")] { + try? FileManager.default.removeItem(atPath: data) + try FileManager.default.createDirectory(atPath: data, withIntermediateDirectories: true) + let bundle = data + "/Containers/Bundle/Application" + let app = bundle + "/APP/Example.app" + var resources: [String] = [] + for directory in [ + app, app + "/PlugIns/Example.appex", app + "/Frameworks/Example.framework", + ] { + let resource = "\(directory)/\(name)/keep.bin" + try write(resource) + resources.append(resource) + } + let target = + category == "temporary" + ? data + "/Containers/Data/Application/DATA/tmp" + : data + "/Containers/Data/Application/DATA/Library/\(name)" + let file = target + "/remove.bin" + try write(file, size: 8192) + let targetBytes = try allocatedSize(target) + let bundleBytes = try allocatedSize(bundle) + + let before = try plan() + XCTAssertEqual(before.cleanableBytes, targetBytes, category) + XCTAssertEqual(before.categories.first { $0.category.id == category }?.targets, 1, category) + XCTAssertEqual(before.storage.first { $0.id == "installed-apps" }?.bytes, bundleBytes) + + _ = try cleanDisk(udid: "T", dataDirectory: data, categoryIDs: [category]) + for resource in resources { XCTAssertTrue(exists(resource), "touched \(resource)") } + XCTAssertFalse(exists(file), category) + var info = stat() + XCTAssertEqual(lstat(target, &info), 0) + } + } + + func testAnIntermediateSymlinkIsRejectedAndNothingOutsideIsTouched() throws { + let outsideFile = root + "/outside/log/keep.log" + try write(outsideFile) + try FileManager.default.createSymbolicLink( + atPath: data + "/var", withDestinationPath: root + "/outside") + XCTAssertThrowsError(try cleanDisk(udid: "T", dataDirectory: data, categoryIDs: ["logs"])) + XCTAssertTrue(exists(outsideFile)) + } + + func testSymlinksInsideATargetAreRemovedNotFollowed() throws { + let outsideFile = root + "/outside/keep.txt" + try write(outsideFile) + try write(data + "/Library/Caches/own.bin") + try FileManager.default.createSymbolicLink( + atPath: data + "/Library/Caches/link", withDestinationPath: root + "/outside") + try FileManager.default.createSymbolicLink( + atPath: data + "/Library/Caches/filelink", withDestinationPath: outsideFile) + _ = try cleanDisk(udid: "T", dataDirectory: data, categoryIDs: ["caches"]) + XCTAssertTrue(exists(outsideFile), "a symlink was followed out of the data directory") + XCTAssertFalse(exists(data + "/Library/Caches/link")) + XCTAssertFalse(exists(data + "/Library/Caches/filelink")) + XCTAssertFalse(exists(data + "/Library/Caches/own.bin")) + } + + func testASymlinkedTargetDirectoryIsNeverACleanupTarget() throws { + let outsideFile = root + "/outside/Caches/keep.bin" + try write(outsideFile) + try FileManager.default.createDirectory( + atPath: data + "/Library", withIntermediateDirectories: true) + try FileManager.default.createSymbolicLink( + atPath: data + "/Library/Caches", withDestinationPath: root + "/outside/Caches") + let before = try plan() + XCTAssertEqual(before.categories.first { $0.category.id == "caches" }?.targets, 0) + _ = try cleanDisk(udid: "T", dataDirectory: data, categoryIDs: ["caches"]) + XCTAssertTrue(exists(outsideFile)) + // The fixed log paths are directories that may be symlinks too. + let outsideLog = root + "/outside2/log/keep.log" + try write(outsideLog) + try FileManager.default.createSymbolicLink( + atPath: data + "/var", withDestinationPath: root + "/outside2") + XCTAssertThrowsError(try cleanDisk(udid: "T", dataDirectory: data, categoryIDs: ["logs"])) + XCTAssertTrue(exists(outsideLog)) + XCTAssertTrue(exists(outsideFile)) + } + + func testTheDataDirectoryMayLiveBehindASymlink() throws { + // macOS temp directories are under /var -> /private/var. + let real = root + "/real/data" + try write(real + "/Library/Caches/x.bin") + try FileManager.default.createSymbolicLink( + atPath: root + "/alias", withDestinationPath: root + "/real") + let result = try cleanDisk( + udid: "T", dataDirectory: root + "/alias/data", categoryIDs: ["caches"]) + XCTAssertGreaterThan(result.reclaimedBytes, 0) + XCTAssertFalse(exists(real + "/Library/Caches/x.bin")) + } + + func testClearDirectoryContentsRefusesWhatIsNotAnInsideDirectory() throws { + try write(data + "/Library/Caches/a.bin") + let file = data + "/file" + try write(file) + XCTAssertThrowsError(try clearDirectoryContents(dataDirectory: data, target: data)) + XCTAssertThrowsError(try clearDirectoryContents(dataDirectory: data, target: root)) + XCTAssertThrowsError(try clearDirectoryContents(dataDirectory: data, target: "/")) + XCTAssertThrowsError(try clearDirectoryContents(dataDirectory: data, target: file)) { + XCTAssertTrue("\($0)".hasPrefix("refusing to clear non-directory target"), "\($0)") + } + XCTAssertThrowsError( + try clearDirectoryContents(dataDirectory: data, target: data + "/Library/../../data")) + XCTAssertNoThrow(try clearDirectoryContents(dataDirectory: data, target: data + "/missing")) + XCTAssertTrue(exists(data + "/Library/Caches/a.bin")) + XCTAssertTrue(exists(file)) + } + + func testProtectedSubtreesAreNeverSearched() throws { + for protected in ["Documents", "Mobile Documents", "Media", "MobileAsset"] { + try write("\(data)/\(protected)/Caches/keep.bin") + try write("\(data)/\(protected)/x/Logs/keep.bin") + try write("\(data)/\(protected)/x/tmp/keep.bin") + } + let p = try plan() + for measurement in p.categories + where ["caches", "logs", "temporary"].contains(measurement.category.id) { + XCTAssertEqual(measurement.targets, 0, measurement.category.id) + } + } + + func testNamesAreExactAndTemporaryIgnoresCacheSubtrees() throws { + try write(data + "/a/Caches/x/tmp/inner.bin") // inside Caches: Caches owns it + try write(data + "/a/tmp/t.bin") + try write(data + "/a/CACHES/c.bin") // not the name + try write(data + "/a/Caches2/c.bin") + let tmp = try findNamedDirectories(root: data, name: "tmp", excludedAncestors: ["Caches"]) + XCTAssertEqual(tmp, [data + "/a/tmp"]) + let caches = try findNamedDirectories(root: data, name: "Caches", excludedAncestors: []) + XCTAssertEqual(caches, [data + "/a/Caches"]) + } + + func testNestedTargetsAreCompactedSoNothingIsCountedTwice() throws { + try write(data + "/Library/Logs/a.log") + try write(data + "/Library/Logs/Logs/b.log") // Logs inside Logs + try write(data + "/var/log/c.log") + let targets = try diskCleanupTargets(dataDirectory: data, categoryID: "logs") + XCTAssertEqual(Set(targets), [data + "/Library/Logs", data + "/var/log"]) + let compacted = try compactExistingTargets( + data, [data + "/Library/Logs/Logs", data + "/Library/Logs", data + "/Library/Logs/"]) + XCTAssertEqual(compacted, [data + "/Library/Logs"]) + } + + func testCandidatesOutsideTheRootAreAnError() throws { + XCTAssertThrowsError(try compactExistingTargets(data, [root + "/other"])) + XCTAssertThrowsError(try compactExistingTargets(data, [data])) + XCTAssertThrowsError(try compactExistingTargets(data, [data + "/../x"])) + } + + func testRequiredSiriAssetsAreMeasuredButNeverCleaned() throws { + let assets = data + "/private/var/MobileAsset/AssetsV2" + for name in [ + "com_apple_MobileAsset_UAF_Siri_X", "com_apple_MobileAsset_TTS_Y", + "com_apple_MobileAsset_VoiceServices_Z", "com_apple_MobileAsset_VoiceTrigger", + ] { + try write("\(assets)/\(name)/m.bin") + } + try write(assets + "/com_apple_MobileAsset_Other/m.bin") + let p = try plan() + let siri = try XCTUnwrap(p.categories.first { $0.category.id == "required-siri-assets" }) + XCTAssertEqual(siri.targets, 4) + XCTAssertGreaterThan(siri.bytes, 0) + XCTAssertEqual(p.cleanableBytes, 0, "measure-only bytes are never cleanable") + XCTAssertThrowsError( + try cleanDisk(udid: "T", dataDirectory: data, categoryIDs: ["required-siri-assets"])) + XCTAssertTrue(exists(assets + "/com_apple_MobileAsset_UAF_Siri_X/m.bin")) + } + + func testCleaningWithNoDirectoriesReclaimsNothing() throws { + let result = try cleanDisk(udid: "T", dataDirectory: data, categoryIDs: ["caches", "logs"]) + XCTAssertEqual(result.reclaimedBytes, 0) + XCTAssertEqual(result.beforeBytes, 0) + XCTAssertEqual(result.afterBytes, 0) + } + + // MARK: - storage breakdown + + func testStorageSeparatesDurableDataFromCleanup() throws { + let container = data + "/Containers/Data/Application/DATA-CONTAINER" + try write(data + "/Containers/Bundle/Application/APP/Example.app/Example", size: 32 * 1024) + try write(container + "/Documents/project.data", size: 24 * 1024) + try write(container + "/Library/Application Support/database.sqlite", size: 20 * 1024) + try write(container + "/Library/Caches/response.cache", size: 64 * 1024) + try write(container + "/Library/Logs/app.log", size: 64 * 1024) + try write(container + "/tmp/work.tmp", size: 64 * 1024) + try write(data + "/Media/DCIM/100APPLE/photo.heic", size: 28 * 1024) + + var measurements = try diskStorageMeasurements(data) + XCTAssertEqual( + measurements.map(\.id), ["installed-apps", "documents", "app-data", "user-media"]) + for m in measurements { XCTAssertGreaterThan(m.bytes, 0, m.id) } + let appDataBefore = measurements.first { $0.id == "app-data" }!.bytes + + try write(container + "/Library/Caches/larger.cache", size: 512 * 1024) + measurements = try diskStorageMeasurements(data) + XCTAssertEqual( + measurements.first { $0.id == "app-data" }?.bytes, appDataBefore, + "app-data excludes cleanable caches") + } + + func testThePlanIncludesTheReadOnlyStorageBreakdown() throws { + try write(data + "/Containers/Bundle/Application/APP/Example.app/Example") + try write(data + "/Containers/Data/Application/DATA/Documents/keep.txt") + let p = try plan() + XCTAssertEqual(p.storage.count, diskStorageCategories.count) + XCTAssertEqual(p.cleanableBytes, 0, "durable storage never counts as cleanable") + } + + func testASymlinkedContainerRootIsNeverFollowed() throws { + let outside = root + "/elsewhere/APP/Documents/big.bin" + try write(outside, size: 100_000) + try FileManager.default.createDirectory( + atPath: data + "/Containers/Data", withIntermediateDirectories: true) + try FileManager.default.createSymbolicLink( + atPath: data + "/Containers/Data/Application", withDestinationPath: root + "/elsewhere") + // app-data skips the symlink; the Documents measurement refuses to resolve + // through it. Either way nothing outside is counted, and nothing is changed. + XCTAssertEqual(try appDataSize(data), 0) + XCTAssertThrowsError(try diskStorageMeasurements(data)) { + XCTAssertTrue("\($0)".contains("refusing symlinked cleanup path"), "\($0)") + } + XCTAssertTrue(exists(outside)) + } + + func testAllocatedSizeCountsBlocksNotLength() throws { + try write(data + "/a/one.bin", size: 1) + let size = try allocatedSize(data + "/a") + XCTAssertGreaterThanOrEqual(size, 4096, "a one-byte file still takes a block") + XCTAssertEqual(size % 512, 0) + XCTAssertEqual( + try allocatedSizeExcludingNames(data + "/a", excluded: ["x"]), size) + try write(data + "/a/x/big.bin", size: 100_000) + let with = try allocatedSize(data + "/a") + let without = try allocatedSizeExcludingNames(data + "/a", excluded: ["x"]) + XCTAssertGreaterThan(with, without) + } + + func testJSONShapeMatchesTheGoContract() throws { + try write(data + "/Library/Caches/a.bin") + let plan = try plan() + let object = + try JSONSerialization.jsonObject(with: JSONEncoder().encode(plan)) as! [String: Any] + XCTAssertEqual( + Set(object.keys), ["udid", "totalBytes", "cleanableBytes", "categories", "storage"]) + let first = (object["categories"] as! [[String: Any]])[0] + XCTAssertEqual( + Set(first.keys), + [ + "id", "name", "description", "downside", "recovery", "risk", "defaultSelected", + "canClean", "bytes", "targets", + ]) + let result = + try JSONSerialization.jsonObject( + with: JSONEncoder().encode( + DiskCleanupResult( + udid: "U", categoryIds: ["caches"], beforeBytes: 2, afterBytes: 1, reclaimedBytes: 1))) + as! [String: Any] + XCTAssertEqual( + Set(result.keys), + [ + "udid", "categoryIds", "beforeBytes", "afterBytes", "reclaimedBytes", "wasBooted", + "bootStateRestored", + ]) + } + + // MARK: - each containment layer on its own + + func testAMissingTargetOutsideTheDataDirectoryIsStillRefused() throws { + // Only the lexical check can catch this: nothing exists to resolve. + XCTAssertThrowsError( + try clearDirectoryContents(dataDirectory: data, target: root + "/does-not-exist")) + XCTAssertThrowsError( + try clearDirectoryContents(dataDirectory: data, target: data + "/../does-not-exist")) + } + + func testATargetReachedThroughAnIntermediateSymlinkIsNeverCleared() throws { + let outside = root + "/outside/Caches/keep.bin" + try write(outside) + try FileManager.default.createSymbolicLink( + atPath: data + "/link", withDestinationPath: root + "/outside") + // data/link/Caches is a real directory, lexically inside data, physically outside. + XCTAssertThrowsError( + try clearDirectoryContents(dataDirectory: data, target: data + "/link/Caches") + ) { + XCTAssertTrue("\($0)".contains("refusing symlinked cleanup path"), "\($0)") + } + XCTAssertTrue(exists(outside)) + } + + func testAFixedLogPathThatIsASymlinkIsNotATargetAndIsNeverFollowed() throws { + let outside = root + "/outside/keep.log" + try write(outside) + try FileManager.default.createDirectory( + atPath: data + "/Library", withIntermediateDirectories: true) + try FileManager.default.createSymbolicLink( + atPath: data + "/Library/Logs", withDestinationPath: root + "/outside") + XCTAssertEqual(try diskCleanupTargets(dataDirectory: data, categoryID: "logs"), []) + let result = try cleanDisk(udid: "T", dataDirectory: data, categoryIDs: ["logs"]) + XCTAssertEqual(result.reclaimedBytes, 0) + XCTAssertTrue(exists(outside)) + XCTAssertTrue(exists(data + "/Library/Logs"), "the symlink itself is left alone") + } + + func testWalksNeverDescendIntoASymlinkedDirectory() throws { + try write(root + "/outside/Caches/huge.bin", size: 200_000) + try write(data + "/own/small.bin", size: 100) + try FileManager.default.createSymbolicLink( + atPath: data + "/own/link", withDestinationPath: root + "/outside") + // A symlink counts as the small entry it is, not the 200 KB it points at. + XCTAssertLessThan(try allocatedSize(data + "/own"), 100_000) + XCTAssertLessThan(try allocatedSizeExcludingNames(data + "/own", excluded: []), 100_000) + // And name discovery does not walk through it either. + XCTAssertEqual(try findNamedDirectories(root: data, name: "Caches", excludedAncestors: []), []) + XCTAssertEqual(try diskCleanupTargets(dataDirectory: data, categoryID: "caches"), []) + } + + func testTemporaryDirectoriesInsideCachesBelongToCachesAlone() throws { + try write(data + "/Library/Caches/work/tmp/x.bin") + try write(data + "/Library/tmp/y.bin") + XCTAssertEqual( + try diskCleanupTargets(dataDirectory: data, categoryID: "caches"), [data + "/Library/Caches"]) + XCTAssertEqual( + try diskCleanupTargets(dataDirectory: data, categoryID: "temporary"), [data + "/Library/tmp"]) + let p = try plan() + let temp = try XCTUnwrap(p.categories.first { $0.category.id == "temporary" }) + XCTAssertEqual(temp.targets, 1) + } + + // MARK: - from the independent review + + func testASymlinkInsideTheDataDirectoryCannotRedirectAFixedPathIntoProtectedData() throws { + let photo = data + "/Media/log/precious-photo.heic" + try write(photo) + // data/var -> data/Media: lexically data/var/log, physically data/Media/log. + try FileManager.default.createSymbolicLink( + atPath: data + "/var", withDestinationPath: data + "/Media") + XCTAssertThrowsError(try cleanDisk(udid: "T", dataDirectory: data, categoryIDs: ["logs"])) { + XCTAssertTrue("\($0)".contains("refusing symlinked cleanup path"), "\($0)") + } + XCTAssertTrue(exists(photo), "user media was deleted through an in-tree symlink") + XCTAssertThrowsError( + try clearDirectoryContents(dataDirectory: data, target: data + "/var/log")) + XCTAssertTrue(exists(photo)) + } + + func testEveryFixedPathIsGuardedAgainstInTreeRedirects() throws { + let precious = data + "/Containers/Data/Application/A/Documents" + try write(precious + "/log/keep.bin") + try write(precious + "/MobileAsset/AssetsV2/com_apple_MobileAsset_LinguisticData/keep.bin") + for (link, category) in [("Library", "logs"), ("private", "linguistic-data")] { + try? FileManager.default.removeItem(atPath: data + "/" + link) + try FileManager.default.createSymbolicLink( + atPath: data + "/" + link, withDestinationPath: precious) + if link == "Library" { try write(precious + "/Logs/keep.log") } + if link == "private" { + try write( + precious + "/var/MobileAsset/AssetsV2/com_apple_MobileAsset_LinguisticData/keep.bin") + } + XCTAssertThrowsError( + try cleanDisk(udid: "T", dataDirectory: data, categoryIDs: [category]), "\(link)") + try FileManager.default.removeItem(atPath: data + "/" + link) + } + XCTAssertTrue(exists(precious + "/log/keep.bin")) + XCTAssertTrue(exists(precious + "/Logs/keep.log")) + XCTAssertTrue( + exists( + precious + "/var/MobileAsset/AssetsV2/com_apple_MobileAsset_LinguisticData/keep.bin")) + } + + func testAppleDoubleFilesAreListedMeasuredAndCleaned() throws { + try write(data + "/Library/Caches/real.bin", size: 100) + try write(data + "/Library/Caches/._real.bin", size: 100_000) + let names = try readDirectory(data + "/Library/Caches").map(\.name) + XCTAssertEqual(names, ["._real.bin", "real.bin"], "readdir does not hide ._ files") + XCTAssertGreaterThan(try allocatedSize(data + "/Library/Caches"), 100_000) + let result = try cleanDisk(udid: "T", dataDirectory: data, categoryIDs: ["caches"]) + XCTAssertFalse(exists(data + "/Library/Caches/._real.bin")) + XCTAssertFalse(exists(data + "/Library/Caches/real.bin")) + XCTAssertEqual(result.afterBytes, try allocatedSize(data + "/Library/Caches")) + } + + func testDirectoryListingIsSortedByBytesAndReportsTypes() throws { + try write(data + "/b/file") + try FileManager.default.createDirectory(atPath: data + "/a", withIntermediateDirectories: true) + try FileManager.default.createSymbolicLink( + atPath: data + "/c", withDestinationPath: data + "/a") + let entries = try readDirectory(data) + XCTAssertEqual(entries.map(\.name), ["a", "b", "c"]) + XCTAssertEqual(entries.map(\.isDirectory), [true, true, false], "a symlink is not a directory") + XCTAssertThrowsError(try readDirectory(data + "/missing")) + } + + func testAChildThatIsAlreadyGoneIsNotAnError() throws { + XCTAssertNoThrow(try removeIfPresent(data + "/never-existed")) + try write(data + "/x/y.bin") + XCTAssertNoThrow(try removeIfPresent(data + "/x")) + XCTAssertFalse(exists(data + "/x")) + // A real failure is still an error: a directory we may not touch. + try write(data + "/locked/inner.bin") + chmod(data + "/locked", 0o500) + defer { chmod(data + "/locked", 0o700) } + XCTAssertThrowsError(try removeIfPresent(data + "/locked/inner.bin")) + } + + func testDiscoveryToleratesADirectoryThatVanishes() throws { + try write(data + "/a/Caches/x.bin") + try write(data + "/gone/Caches/y.bin") + // Simulate the race: the directory listing names `gone`, then it is deleted. + var removed = false + var found: [String] = [] + try walkDirectoriesForTest(data) { path in + if path == data + "/a" || path == data + "/gone", !removed { + removed = true + try? FileManager.default.removeItem(atPath: data + "/gone") + } + if (path as NSString).lastPathComponent == "Caches" { found.append(path) } + return true + } + XCTAssertTrue(found.contains(data + "/a/Caches")) + } + + func testPathsWithCombiningMarksAreJudgedByBytes() throws { + XCTAssertTrue(isStrictDescendant("/d", "/d/\u{301}x")) + XCTAssertTrue(isStrictDescendant("/d", "/d/\u{301}x/Caches")) + XCTAssertEqual(cleanPath("/d/\u{301}x/../y"), "/d/y") + XCTAssertFalse(isStrictDescendant("/d", "/d\u{301}"), "a different name, not a child") + try write(data + "/\u{301}odd/Library/Caches/c.bin") + XCTAssertNoThrow(try plan()) + _ = try cleanDisk(udid: "T", dataDirectory: data, categoryIDs: ["caches"]) + XCTAssertFalse(exists(data + "/\u{301}odd/Library/Caches/c.bin")) + } + + func testQuotedCategoryNamesUseGosRules() { + XCTAssertThrowsError(try validateDiskCleanupSelection(["bad\u{200D}id"])) { + XCTAssertEqual("\($0)", "unknown disk cleanup category \"bad\\u200did\"") + } + } +} diff --git a/swift/Tests/SimSlimKitTests/DiskUsageTests.swift b/swift/Tests/SimSlimKitTests/DiskUsageTests.swift new file mode 100644 index 0000000..245f907 --- /dev/null +++ b/swift/Tests/SimSlimKitTests/DiskUsageTests.swift @@ -0,0 +1,44 @@ +// Copyright (c) 2026 Pavel Akhrameev (Swift port). MIT License; see LICENSE. + +import XCTest + +@testable import SimSlimKit + +final class DiskUsageTests: XCTestCase { + func testDUOutputParsing() throws { + XCTAssertEqual(try Simctl.parseDUDiskUsage("5\t/x\n"), 5120) + XCTAssertEqual(try Simctl.parseDUDiskUsage("0 /x"), 0) + for bad in ["", " \n", "abc\t/x", "-4\t/x", "99999999999999999999 /x"] { + XCTAssertThrowsError(try Simctl.parseDUDiskUsage(bad), bad) + } + XCTAssertThrowsError(try Simctl.parseDUDiskUsage("\(Int64.max / 1024 + 1) /x")) + } + + func testTopJSONKeysFollowTheGoContract() throws { + let sim = TopSim( + device: Device( + udid: "U", name: "n", state: "Booted", platform: "iOS", osVersion: "27.2", set: "default"), + managedDisabled: 3, managedTotal: 173, + memory: MemoryMeasurement(processes: 2, bytes: 5, cpu: 1), + diskBytes: 9) + let data = try JSONEncoder().encode(TopOutput(sims: [sim], totalBytes: 5)) + let object = try JSONSerialization.jsonObject(with: data) as! [String: Any] + let first = (object["sims"] as! [[String: Any]])[0] + XCTAssertEqual( + Set(first.keys), + [ + "udid", "name", "state", "platform", "osVersion", "set", "managedDisabled", "managedTotal", + "memory", "diskBytes", + ]) + XCTAssertEqual(object["totalBytes"] as? Int, 5) + // Empty error strings and absent values are omitted, as Go's omitempty does. + let bare = try JSONEncoder().encode(TopSim(device: Device(udid: "U"), managedTotal: 1)) + let keys = Set((try JSONSerialization.jsonObject(with: bare) as! [String: Any]).keys) + XCTAssertFalse(keys.contains("statusError")) + XCTAssertFalse(keys.contains("memory")) + XCTAssertFalse(keys.contains("diskBytes")) + let procs = try JSONEncoder().encode(TopProcesses(udid: "U", processes: [], totalBytes: 0)) + let procKeys = Set((try JSONSerialization.jsonObject(with: procs) as! [String: Any]).keys) + XCTAssertEqual(procKeys, ["udid", "processes", "totalBytes"]) + } +} diff --git a/swift/Tests/SimSlimKitTests/FeaturesTests.swift b/swift/Tests/SimSlimKitTests/FeaturesTests.swift new file mode 100644 index 0000000..a41ccdb --- /dev/null +++ b/swift/Tests/SimSlimKitTests/FeaturesTests.swift @@ -0,0 +1,124 @@ +// Copyright (c) 2026 Pavel Akhrameev (Swift port). MIT License; see LICENSE. + +import XCTest + +@testable import SimSlimKit + +/// Ports of features_test.go. +final class FeaturesTests: XCTestCase { + func testFeatureLabelsAreManaged() { + for feature in Catalog.features { + XCTAssertFalse(feature.labels.isEmpty, "feature \(feature.id) has no labels") + for label in feature.labels { + XCTAssertTrue( + Catalog.managedSet.contains(label), + "feature \(feature.id) names unmanaged daemon \(label)") + } + } + } + + func testFeatureIDsAreUniqueAndNamed() { + var seen = Set() + for feature in Catalog.features { + XCTAssertFalse(feature.id.isEmpty) + XCTAssertFalse(feature.name.isEmpty, "feature \(feature.id) has no name") + XCTAssertTrue(seen.insert(feature.id).inserted, "duplicate feature ID \(feature.id)") + } + XCTAssertFalse(seen.isEmpty) + } + + func testResolveFeatures() throws { + let got = try Catalog.resolveFeatures(["push", "storekit"]) + XCTAssertEqual(got.map(\.id), ["push", "storekit"]) + XCTAssertThrowsError(try Catalog.resolveFeatures(["push", "nope"])) { error in + XCTAssertEqual( + (error as? SimSlimError)?.message, + "unknown feature \"nope\" (see `simslim doctor --list`)") + } + } + + func testGameCenterDiagnosesLegacyDisabledGamed() throws { + let features = try Catalog.resolveFeatures(["game-center"]) + XCTAssertTrue(Catalog.diagnoseFeatures(features, disabled: []).ok) + let report = Catalog.diagnoseFeatures(features, disabled: ["com.apple.gamed"]) + XCTAssertFalse(report.ok) + XCTAssertEqual(report.features.first?.disabled, ["com.apple.gamed"]) + } + + func testWidgetsDiagnoseDisabledNavd() throws { + let features = try Catalog.resolveFeatures(["widgets"]) + XCTAssertTrue(Catalog.diagnoseFeatures(features, disabled: []).ok) + let report = Catalog.diagnoseFeatures(features, disabled: ["com.apple.navd"]) + XCTAssertFalse(report.ok) + XCTAssertEqual(report.features.first?.disabled, ["com.apple.navd"]) + } + + func testFilesRecentsDiagnoseDisabledSearchd() throws { + let features = try Catalog.resolveFeatures(["files-recents"]) + XCTAssertTrue(Catalog.diagnoseFeatures(features, disabled: ["com.apple.searchtoold"]).ok) + let report = Catalog.diagnoseFeatures(features, disabled: ["com.apple.searchd"]) + XCTAssertFalse(report.ok) + XCTAssertEqual(report.features.first?.disabled, ["com.apple.searchd"]) + } + + func testSlimProfileReportsMDMAndAppClipsUntilExcepted() throws { + let features = try Catalog.resolveFeatures(["mdm", "app-clips"]) + XCTAssertFalse( + Catalog.diagnoseFeatures(features, disabled: Profile().desired()).ok, + "a full slim profile must break MDM and App Clips") + let kept = Profile(exceptCategories: ["mdm", "other"]) + XCTAssertTrue( + Catalog.diagnoseFeatures(features, disabled: kept.desired()).ok, + "--except mdm,other must keep MDM and App Clips") + } + + func testDiagnoseFeatures() throws { + let features = try Catalog.resolveFeatures(["push", "storekit", "universal-links"]) + + XCTAssertTrue(Catalog.diagnoseFeatures(features, disabled: []).ok, "healthy on a stock device") + + let report = Catalog.diagnoseFeatures(features, disabled: ["com.apple.storekitd"]) + XCTAssertFalse(report.ok) + let byID = Dictionary(uniqueKeysWithValues: report.features.map { ($0.id, $0) }) + XCTAssertEqual(byID["storekit"]?.ok, false) + XCTAssertEqual(byID["storekit"]?.disabled, ["com.apple.storekitd"]) + XCTAssertEqual(byID["push"]?.ok, true) + XCTAssertEqual(byID["universal-links"]?.ok, true) + + let spotlight = try Catalog.resolveFeatures(["spotlight"]) + XCTAssertFalse( + Catalog.diagnoseFeatures(spotlight, disabled: ["com.apple.searchtoold"]).ok, + "any disabled backing daemon breaks a multi-daemon feature") + } + + // MARK: - JSON contract + + func testDoctorOutputOmitsEmptyFields() throws { + let features = try Catalog.resolveFeatures(["push"]) + let healthy = Catalog.diagnoseFeatures(features, disabled: []) + let json = try jsonObject(healthy) + XCTAssertEqual(Set(json.keys), ["ok", "features"], "empty udid is omitted") + let status = try XCTUnwrap((json["features"] as? [[String: Any]])?.first) + XCTAssertEqual(Set(status.keys), ["id", "name", "ok"], "empty disabled list is omitted") + + var broken = Catalog.diagnoseFeatures(features, disabled: ["com.apple.apsd"]) + broken.udid = "UDID-1" + let brokenJSON = try jsonObject(broken) + XCTAssertEqual(Set(brokenJSON.keys), ["udid", "ok", "features"]) + let brokenStatus = try XCTUnwrap((brokenJSON["features"] as? [[String: Any]])?.first) + XCTAssertEqual(Set(brokenStatus.keys), ["id", "name", "ok", "disabled"]) + } + + func testDoctorOutputRoundTrips() throws { + let features = try Catalog.resolveFeatures(["push", "storekit"]) + var report = Catalog.diagnoseFeatures(features, disabled: ["com.apple.storekitd"]) + report.udid = "UDID-2" + let data = try JSONEncoder().encode(report) + XCTAssertEqual(try JSONDecoder().decode(DoctorOutput.self, from: data), report) + } + + private func jsonObject(_ value: T) throws -> [String: Any] { + let data = try JSONEncoder().encode(value) + return try XCTUnwrap(JSONSerialization.jsonObject(with: data) as? [String: Any]) + } +} diff --git a/swift/Tests/SimSlimKitTests/Generated/ForbiddenLabels.swift b/swift/Tests/SimSlimKitTests/Generated/ForbiddenLabels.swift new file mode 100644 index 0000000..c024b58 --- /dev/null +++ b/swift/Tests/SimSlimKitTests/Generated/ForbiddenLabels.swift @@ -0,0 +1,21 @@ +// swift-format-ignore-file +// Copyright (c) 2026 Pavel Akhrameev (Swift port). MIT License; see LICENSE. + +/// Daemons that wedge a simulator when disabled; none may ever be managed. +let forbiddenLabels: [String] = [ + "com.apple.nanoregistryd", + "com.apple.nanoregistrylaunchd", + "com.apple.nanoprefsyncd.2", + "com.apple.nanotimekitcompaniond", + "com.apple.nanobackupd", + "com.apple.sleepd", + "com.apple.appprotectiond", + "com.apple.ManagedSettingsAgent", + "com.apple.managedconfiguration.profiled", + "com.apple.mobiletimerd", + "com.apple.routined", + "com.apple.biomed", + "com.apple.biomesyncd", + "com.apple.dmd", + "com.apple.donotdisturbd", +] diff --git a/swift/Tests/SimSlimKitTests/LiveTests.swift b/swift/Tests/SimSlimKitTests/LiveTests.swift new file mode 100644 index 0000000..1fd0d2c --- /dev/null +++ b/swift/Tests/SimSlimKitTests/LiveTests.swift @@ -0,0 +1,535 @@ +// Copyright (c) 2026 Pavel Akhrameev (Swift port). MIT License; see LICENSE. + +import TestSupport +import XCTest + +@testable import SimSlimKit + +private final class Lines: @unchecked Sendable { + private let lock = NSLock() + private var items: [String] = [] + func add(_ line: String) { + lock.lock() + items.append(line) + lock.unlock() + } + var all: [String] { + lock.lock() + defer { lock.unlock() } + return items + } +} + +final class LiveTests: XCTestCase { + private let ios = "com.apple.CoreSimulator.SimRuntime.iOS-27-2" + private let watch = "com.apple.CoreSimulator.SimRuntime.watchOS-11-5" + private let udid = "AAAAAAAA-0000-0000-0000-000000000001" + private var root = "" + + override func setUpWithError() throws { + root = NSTemporaryDirectory() + "simslim-live-\(UUID().uuidString)" + try FileManager.default.createDirectory(atPath: root, withIntermediateDirectories: true) + } + + override func tearDown() { + try? FileManager.default.removeItem(atPath: root) + } + + private func host( + state: String = "Booted", runtime: String? = nil, disabled: Set = [], + loaded: Set = [] + ) -> FakeHost { + let host = FakeHost(devices: [ + .init(udid: udid, name: "iPhone", runtime: runtime ?? ios, state: state) + ]) + host.storeRoot = root + "/store" + if state == "Booted" { + host.disabled[udid] = disabled + host.loaded[udid] = loaded + } + return host + } + + private func simctl(_ host: FakeHost) -> Simctl { + var simctl = Simctl(runner: host) + simctl.retryDelays = [0, 0, 0, 0] + simctl.sleep = { _ in } + return simctl + } + + private func installPlists( + _ host: FakeHost, labels: [String], missing: Set = [] + ) throws { + let dir = root + "/runtime/System/Library/LaunchDaemons" + try FileManager.default.createDirectory(atPath: dir, withIntermediateDirectories: true) + host.runtimeRoots[ios] = root + "/runtime" + host.runtimeRoots[watch] = root + "/runtime" + for label in labels where !missing.contains(label) { + let path = "\(dir)/\(label).plist" + FileManager.default.createFile(atPath: path, contents: Data()) + host.plistLabels[path] = label + } + } + + private func spawnVerbs(_ host: FakeHost) -> [String] { + host.calls.compactMap { call in + guard call.executable == .xcrun, call.arguments.count > 4, call.arguments[1] == "spawn" + else { return nil } + return call.arguments[4] + } + } + + private func category(_ id: String) -> [String] { Catalog.category(id: id)!.labels } + + private var profilePath: String { root + "/profile.json" } + + private func writeProfile(_ text: String) throws { + try text.write(toFile: profilePath, atomically: true, encoding: .utf8) + } + + // MARK: - enable + + func testEnableLoadsACategoryInOneBatchAndSortsTheResult() throws { + let labels = category("search") + let host = host(disabled: Set(labels)) + try installPlists(host, labels: labels) + let lines = Lines() + let out = try simctl(host).enableServices( + udid: udid, ids: ["search"], reporter: { lines.add($0) }) + XCTAssertEqual(out.action, "enable") + XCTAssertTrue(out.live) + XCTAssertEqual(out.labels, labels.sorted()) + XCTAssertEqual(out.notStarted, []) + XCTAssertEqual(host.disabled[udid], []) + XCTAssertEqual(host.loaded[udid], Set(labels)) + XCTAssertEqual(spawnVerbs(host).filter { $0 == "load" }.count, 1) + XCTAssertFalse(spawnVerbs(host).contains("enable"), "the batch did everything") + XCTAssertTrue( + lines.all.contains(" \(labels.count)/\(labels.count) services started in one batch")) + } + + func testEnableOnlyLiftsTheOverrideOfALabelWithNoPlist() throws { + let label = category("search")[0] + let host = host(disabled: [label]) + try installPlists(host, labels: category("search"), missing: [label]) + let out = try simctl(host).enableServices(udid: udid, ids: [label]) + XCTAssertEqual(host.disabled[udid], []) + XCTAssertEqual(out.labels, [label]) + XCTAssertEqual(out.notStarted, [], "launchd starts an on-demand job when asked") + XCTAssertEqual(spawnVerbs(host).filter { $0 == "enable" }.count, 1) + XCTAssertFalse(spawnVerbs(host).contains("bootstrap")) + } + + func testEnableReportsALabelThatOnlyStartsAtTheNextBoot() throws { + let labels = category("search") + let stubborn = labels[0] + let host = host(disabled: Set(labels)) + try installPlists(host, labels: labels) + host.failTransition = { verb, label in + label == stubborn && (verb == "load" || verb == "bootstrap") + ? CommandResult(status: 1) : nil + } + let out = try simctl(host).enableServices(udid: udid, ids: ["search"]) + XCTAssertEqual(out.notStarted, [stubborn]) + XCTAssertFalse(host.disabled[udid]!.contains(stubborn), "its override is lifted") + XCTAssertTrue(spawnVerbs(host).contains("bootstrap")) + } + + func testEnableFailsWhenALabelStaysDisabled() throws { + let label = category("search")[0] + let host = host(disabled: [label]) + try installPlists(host, labels: [], missing: []) + host.failTransition = { _, l in l == label ? CommandResult(status: 1) : nil } + XCTAssertThrowsError(try simctl(host).enableServices(udid: udid, ids: [label])) { + XCTAssertTrue( + "\($0)".contains("still disabled") || "\($0)".contains("transitions failed"), "\($0)") + } + } + + func testEnableFailsWhenTheOverrideIsAcceptedButNeverLifted() throws { + let label = category("search")[0] + let host = host(disabled: [label]) + // launchctl exits 0 for `enable` but the override stays: only the read-back sees it. + host.failTransition = { verb, l in + verb == "enable" && l == label ? CommandResult(status: 0) : nil + } + XCTAssertThrowsError(try simctl(host).enableServices(udid: udid, ids: [label])) { + XCTAssertEqual("\($0)", "1 of 1 services are still disabled: \(label)") + } + } + + func testEnableOfARunningCategoryChangesNothing() throws { + let labels = category("search") + let host = host(loaded: Set(labels)) + try installPlists(host, labels: labels) + let lines = Lines() + let out = try simctl(host).enableServices( + udid: udid, ids: ["search"], reporter: { lines.add($0) }) + XCTAssertEqual(out.notStarted, []) + XCTAssertTrue(lines.all.contains(" all \(labels.count) services were already running")) + XCTAssertEqual(spawnVerbs(host).filter { !["print-disabled", "list"].contains($0) }, []) + } + + func testEnableRejectsBadInputBeforeTouchingAnything() throws { + let host = host() + for (ids, fragment) in [ + (["no-such-thing"], "unknown category or managed daemon \"no-such-thing\""), + (["com.apple.not.managed"], "unknown category or managed daemon"), + ([], "name at least one category ID or managed daemon to enable"), + ] { + XCTAssertThrowsError(try simctl(host).enableServices(udid: udid, ids: ids)) { + XCTAssertTrue("\($0)".contains(fragment), "\($0)") + } + } + XCTAssertTrue(host.calls.isEmpty) + } + + func testEnableNeverReachesAnAlias() throws { + let host = host(disabled: ["com.apple.x"]) + XCTAssertThrowsError(try simctl(host).enableServices(udid: "all", ids: ["search"])) { + XCTAssertEqual("\($0)", "no simulator with udid all") + } + XCTAssertTrue(spawnVerbs(host).isEmpty) + } + + func testEnableOnAShutdownSimulatorNeedsSave() throws { + let host = host(state: "Shutdown") + XCTAssertThrowsError(try simctl(host).enableServices(udid: udid, ids: ["search"])) { + let text = "\($0)" + XCTAssertTrue(text.contains("is not booted (it is Shutdown)"), text) + XCTAssertTrue(text.contains("pass --save "), text) + } + XCTAssertTrue(spawnVerbs(host).isEmpty) + } + + func testEnableOnAShutdownSimulatorOnlyWritesTheProfile() throws { + let host = host(state: "Shutdown") + let out = try simctl(host).enableServices(udid: udid, ids: ["search"], save: profilePath) + XCTAssertFalse(out.live) + XCTAssertEqual(out.labels, []) + XCTAssertEqual(out.saved, profilePath) + XCTAssertTrue(spawnVerbs(host).isEmpty) + XCTAssertEqual(try loadSlimProfile(path: profilePath).exceptCategories, ["search"]) + } + + // MARK: - disable + + func testDisableStopsACategoryAndReadsItBack() throws { + let labels = category("search") + let host = host(loaded: Set(labels)) + try installPlists(host, labels: labels) + let out = try simctl(host).disableServices(udid: udid, ids: ["search"]) + XCTAssertEqual(out.labels, labels.sorted()) + XCTAssertEqual(out.stillEnabled, []) + XCTAssertEqual(host.disabled[udid], Set(labels)) + XCTAssertEqual(host.loaded[udid], []) + } + + /// What stopping `target` must keep, worked out independently: the labels it + /// lists that some other category with every daemon enabled also lists. + private func expectedKept(stopping target: String, down: Set) -> Set { + var kept = Set() + for other in Catalog.categories where other.id != target { + if !down.isDisjoint(with: other.labels) { continue } + kept.formUnion(Set(other.labels).intersection(category(target))) + } + return kept + } + + func testDisableKeepsTheLabelsAnotherEnabledCategoryShares() throws { + let shared = Set(category("store")).intersection(category("icloud")) + XCTAssertFalse(shared.isEmpty) + // iCloud is fully enabled, so stopping the store keeps what they share. + let kept = expectedKept(stopping: "store", down: []) + XCTAssertTrue(kept.isSuperset(of: shared)) + let host = host(loaded: Set(category("store"))) + try installPlists(host, labels: category("store")) + let out = try simctl(host).disableServices(udid: udid, ids: ["store"]) + XCTAssertEqual(Set(out.stillEnabled), kept) + XCTAssertEqual(Set(out.labels), Set(category("store")).subtracting(kept)) + XCTAssertTrue(host.disabled[udid]!.isDisjoint(with: kept)) + + // Once iCloud has a daemon down it is no longer "on", so what only it + // shared goes too. + let down = category("icloud").first { !shared.contains($0) }! + let kept2 = expectedKept(stopping: "store", down: [down]) + XCTAssertTrue(kept2.count < kept.count) + let host2 = self.host(disabled: [down], loaded: Set(category("store"))) + try installPlists(host2, labels: category("store")) + let out2 = try simctl(host2).disableServices(udid: udid, ids: ["store"]) + XCTAssertEqual(Set(out2.stillEnabled), kept2) + XCTAssertTrue(host2.disabled[udid]!.isSuperset(of: shared.subtracting(kept2))) + } + + func testDisableOfANamedLabelIsAlwaysStopped() throws { + let shared = Set(category("store")).intersection(category("icloud")).sorted()[0] + let host = host(loaded: [shared]) + try installPlists(host, labels: [shared]) + let out = try simctl(host).disableServices(udid: udid, ids: [shared]) + XCTAssertEqual(out.labels, [shared]) + XCTAssertEqual(out.stillEnabled, []) + } + + func testANamedLabelIsStoppedEvenWhenItsCategoryAlsoNamesItAndANeighbourSharesIt() throws { + let shared = Set(category("store")).intersection(category("icloud")).sorted()[0] + let host = host(loaded: Set(category("store"))) + try installPlists(host, labels: category("store")) + let out = try simctl(host).disableServices(udid: udid, ids: ["store", shared]) + XCTAssertTrue(out.labels.contains(shared), "named on its own, so it is stopped") + XCTAssertFalse(out.stillEnabled.contains(shared)) + XCTAssertTrue(host.disabled[udid]!.contains(shared)) + } + + func testDisableKeepsHomedOnWatchOS() throws { + let health = Catalog.categories.first { $0.labels.contains("com.apple.homed") }! + let host = host(runtime: watch, loaded: Set(health.labels)) + try installPlists(host, labels: health.labels) + let out = try simctl(host).disableServices(udid: udid, ids: [health.id]) + XCTAssertTrue(out.stillEnabled.contains("com.apple.homed")) + XCTAssertFalse(out.labels.contains("com.apple.homed")) + XCTAssertFalse(host.disabled[udid]!.contains("com.apple.homed")) + } + + func testDisableRefusesACompatibilityDaemon() throws { + let host = host() + let compat = Catalog.managedSet.subtracting(Catalog.slimmableSet).sorted()[0] + XCTAssertThrowsError(try simctl(host).disableServices(udid: udid, ids: [compat])) { + XCTAssertEqual( + "\($0)", + "\(compat) is never disabled: simslim keeps it running for compatibility (see `simslim profiles`)" + ) + } + XCTAssertTrue(host.calls.isEmpty) + } + + func testDisableReportsOverridesThatDidNotTake() throws { + let label = category("search")[0] + let host = host(loaded: [label]) + host.failTransition = { _, l in l == label ? CommandResult(status: 1) : nil } + XCTAssertThrowsError(try simctl(host).disableServices(udid: udid, ids: [label])) + } + + func testDisableOnAShutdownSimulatorNeedsSave() throws { + let host = host(state: "Shutdown") + XCTAssertThrowsError(try simctl(host).disableServices(udid: udid, ids: ["search"])) + XCTAssertTrue(spawnVerbs(host).isEmpty) + } + + // MARK: - --save + + func testSaveAddsInOrderWithoutDuplicates() throws { + try writeProfile(#"{"name":"mine","except":["siri"],"keep":["\#(category("siri")[0])"]}"#) + let keepable = category("search")[0] + let (data, changed) = try updatedProfile( + path: profilePath, categories: ["icloud", "siri"], labels: [keepable], enable: true) + XCTAssertTrue(changed) + let parsed = try parseSlimProfile(XCTUnwrap(data), path: profilePath) + XCTAssertEqual(parsed.except, ["siri", "icloud"]) + XCTAssertEqual(parsed.name, "mine") + } + + func testSaveSkipsADaemonAnExceptedCategoryAlreadyKeeps() throws { + try writeProfile(#"{"except":["search"]}"#) + let covered = category("search")[0] + let (data, changed) = try updatedProfile( + path: profilePath, categories: [], labels: [covered], enable: true) + XCTAssertFalse(changed) + XCTAssertNil(data) + } + + func testSaveCreatesAMissingFileFromTheDefaultProfile() throws { + XCTAssertFalse(FileManager.default.fileExists(atPath: profilePath)) + try saveServices(path: profilePath, categories: ["search"], labels: [], enable: true) + XCTAssertEqual(try loadSlimProfile(path: profilePath).exceptCategories, ["search"]) + // Disabling from a missing file still creates it, as the default profile. + let other = root + "/other.json" + try saveServices(path: other, categories: ["search"], labels: [], enable: false) + XCTAssertTrue(FileManager.default.fileExists(atPath: other)) + } + + func testSaveLeavesAnUnchangedProfileUntouched() throws { + try writeProfile(#"{"except":["search"]}"#) + let before = try FileManager.default.attributesOfItem(atPath: profilePath)[.systemFileNumber] + try saveServices(path: profilePath, categories: ["search"], labels: [], enable: true) + let after = try FileManager.default.attributesOfItem(atPath: profilePath)[.systemFileNumber] + XCTAssertEqual(before as? UInt64, after as? UInt64, "not rewritten") + XCTAssertEqual( + try String(contentsOfFile: profilePath, encoding: .utf8), #"{"except":["search"]}"#) + } + + func testSaveDisableRemovesAndRefusesToLeaveACategoryKeepingTheDaemon() throws { + let label = category("search")[0] + try writeProfile(#"{"except":["search","siri"],"keep":["\#(label)"]}"#) + XCTAssertThrowsError( + try updatedProfile(path: profilePath, categories: [], labels: [label], enable: false) + ) { + XCTAssertEqual( + "\($0)", + "profile \(profilePath) keeps \(label) enabled through category \"search\"; disable that category instead, or edit the file" + ) + } + try saveServices(path: profilePath, categories: ["search"], labels: [label], enable: false) + let profile = try parseSlimProfile( + Data(contentsOf: URL(fileURLWithPath: profilePath)), path: profilePath) + XCTAssertEqual(profile.except, ["siri"]) + XCTAssertEqual(profile.keep, []) + } + + func testSaveRewritesAtomicallyKeepingModeAndFollowingSymlinks() throws { + let real = root + "/real.json" + try #"{"except":[]}"#.write(toFile: real, atomically: true, encoding: .utf8) + try FileManager.default.setAttributes([.posixPermissions: 0o600], ofItemAtPath: real) + try FileManager.default.createSymbolicLink(atPath: profilePath, withDestinationPath: real) + try saveServices(path: profilePath, categories: ["search"], labels: [], enable: true) + let link = try FileManager.default.destinationOfSymbolicLink(atPath: profilePath) + XCTAssertEqual(link, real, "the symlink survives") + XCTAssertEqual(try loadSlimProfile(path: real).exceptCategories, ["search"]) + let mode = try FileManager.default.attributesOfItem(atPath: real)[.posixPermissions] as? Int + XCTAssertEqual(mode, 0o600) + let leftovers = try FileManager.default.contentsOfDirectory(atPath: root).filter { + $0.hasPrefix(".") + } + XCTAssertEqual(leftovers, []) + } + + func testAnInvalidProfileFailsBeforeTheSimulatorChanges() throws { + try writeProfile(#"{"except":["no-such-category"]}"#) + let host = host(disabled: Set(category("search"))) + XCTAssertThrowsError( + try simctl(host).enableServices(udid: udid, ids: ["search"], save: profilePath)) + XCTAssertEqual(host.disabled[udid], Set(category("search")), "nothing was changed") + XCTAssertTrue(spawnVerbs(host).isEmpty) + } + + func testAFailedLiveChangeLeavesTheProfileAlone() throws { + let label = category("search")[0] + try writeProfile(#"{"except":[]}"#) + let host = host(disabled: [label]) + host.failTransition = { _, l in l == label ? CommandResult(status: 1) : nil } + XCTAssertThrowsError( + try simctl(host).enableServices(udid: udid, ids: [label], save: profilePath) + ) { + XCTAssertTrue("\($0)".hasSuffix("(profile \(profilePath) not changed)"), "\($0)") + } + XCTAssertEqual(try String(contentsOfFile: profilePath, encoding: .utf8), #"{"except":[]}"#) + } + + func testAFailedSaveAfterALiveChangeSaysSo() throws { + let host = host(loaded: Set(category("search"))) + try installPlists(host, labels: category("search")) + // The directory vanishes between validation and the write. + let ghost = root + "/missing-dir/profile.json" + XCTAssertThrowsError( + try simctl(host).enableServices(udid: udid, ids: ["search"], save: ghost) + ) { + XCTAssertTrue( + "\($0)".hasPrefix("the simulator was changed, but profile \(ghost) was not: "), "\($0)") + } + } + + func testIDsAreDeduplicatedAndSorted() throws { + let (categories, labels) = try simctl(host()).resolveServiceIDs([ + "siri", "search", "siri", category("search")[0], category("search")[0], + ]) + XCTAssertEqual(categories, ["search", "siri"]) + XCTAssertEqual(labels, [category("search")[0]]) + } + + // MARK: - from the independent review + + func testDisableFailsWhenTheOverrideIsAcceptedButNeverAppears() throws { + let label = category("search")[0] + let host = host(loaded: [label]) + // launchctl exits 0 for `disable` but nothing changes: only the read-back sees it. + host.failTransition = { verb, l in + verb == "disable" && l == label ? CommandResult(status: 0) : nil + } + XCTAssertThrowsError(try simctl(host).disableServices(udid: udid, ids: [label])) { + XCTAssertEqual("\($0)", "1 of 1 disable overrides did not take") + } + } + + func testWithoutARuntimeRootEveryUnloadedLabelCountsAsOneLaunchdShouldLoad() throws { + let label = category("search")[0] + let host = host(disabled: [label]) // no runtime roots: plists cannot be looked up + let out = try simctl(host).enableServices(udid: udid, ids: [label]) + XCTAssertEqual(host.disabled[udid], []) + XCTAssertEqual(out.notStarted, [label], "re-enabled, but not loaded in this boot") + } + + func testDisableValidatesTheProfileBeforeTouchingTheSimulator() throws { + let label = category("search")[0] + try writeProfile(#"{"except":["search"],"keep":["\#(label)"]}"#) + let host = host(loaded: Set(category("search"))) + XCTAssertThrowsError( + try simctl(host).disableServices(udid: udid, ids: [label], save: profilePath)) + XCTAssertEqual(host.disabled[udid], []) + XCTAssertTrue(spawnVerbs(host).filter { !["print-disabled", "list"].contains($0) }.isEmpty) + } + + func testAFailedLiveDisableLeavesTheProfileAlone() throws { + let label = category("search")[0] + try writeProfile(#"{"except":["siri"],"keep":["\#(label)"]}"#) + let host = host(loaded: [label]) + host.failTransition = { _, l in l == label ? CommandResult(status: 1) : nil } + XCTAssertThrowsError( + try simctl(host).disableServices(udid: udid, ids: [label], save: profilePath) + ) { + XCTAssertTrue("\($0)".hasSuffix("(profile \(profilePath) not changed)"), "\($0)") + } + XCTAssertTrue(try String(contentsOfFile: profilePath, encoding: .utf8).contains(label)) + } + + func testDisablingOnlyWhatThePlatformKeepsStopsNothing() throws { + let host = host(runtime: watch, loaded: ["com.apple.homed"]) + let out = try simctl(host).disableServices(udid: udid, ids: ["com.apple.homed"]) + XCTAssertEqual(out.labels, []) + XCTAssertEqual(out.stillEnabled, ["com.apple.homed"]) + XCTAssertTrue(spawnVerbs(host).filter { !["print-disabled", "list"].contains($0) }.isEmpty) + } + + func testWhitespacePaddedEntriesAreFoundNotDuplicated() throws { + try writeProfile(#"{"except":[" search "],"keep":[" "]}"#) + // Disabling finds the padded category and removes it. + try saveServices(path: profilePath, categories: ["search"], labels: [], enable: false) + XCTAssertEqual( + try parseSlimProfile(Data(contentsOf: URL(fileURLWithPath: profilePath)), path: "p").except, + []) + // Enabling a category already present padded does not add it again. + try writeProfile(#"{"except":[" search "]}"#) + let (data, changed) = try updatedProfile( + path: profilePath, categories: ["search"], labels: [], enable: true) + XCTAssertFalse(changed) + XCTAssertNil(data) + } + + func testASymlinkNamedWithABareFileNameIsFollowed() throws { + let target = root + "/shared.json" + try #"{"except":[]}"#.write(toFile: target, atomically: true, encoding: .utf8) + try FileManager.default.setAttributes([.posixPermissions: 0o600], ofItemAtPath: target) + let cwd = FileManager.default.currentDirectoryPath + defer { FileManager.default.changeCurrentDirectoryPath(cwd) } + FileManager.default.changeCurrentDirectoryPath(root) + try FileManager.default.createSymbolicLink( + atPath: root + "/link.json", withDestinationPath: "shared.json") + try saveServices(path: "link.json", categories: ["search"], labels: [], enable: true) + XCTAssertEqual( + try FileManager.default.destinationOfSymbolicLink(atPath: root + "/link.json"), + "shared.json", "still a symlink") + XCTAssertEqual(try loadSlimProfile(path: target).exceptCategories, ["search"]) + let mode = try FileManager.default.attributesOfItem(atPath: target)[.posixPermissions] as? Int + XCTAssertEqual(mode, 0o600) + } + + func testAProfilePathThatCannotBeReadIsNeverOverwrittenAsAMissingFile() throws { + // A symlink loop is an error (ELOOP), not a missing file to start afresh. + try FileManager.default.createSymbolicLink( + atPath: root + "/loop.json", withDestinationPath: root + "/loop.json") + XCTAssertThrowsError( + try saveServices( + path: root + "/loop.json", categories: ["search"], labels: [], enable: true)) + XCTAssertEqual( + try FileManager.default.destinationOfSymbolicLink(atPath: root + "/loop.json"), + root + "/loop.json", "the symlink was not replaced") + } +} diff --git a/swift/Tests/SimSlimKitTests/ProfileFileTests.swift b/swift/Tests/SimSlimKitTests/ProfileFileTests.swift new file mode 100644 index 0000000..b16271d --- /dev/null +++ b/swift/Tests/SimSlimKitTests/ProfileFileTests.swift @@ -0,0 +1,199 @@ +// Copyright (c) 2026 Pavel Akhrameev (Swift port). MIT License; see LICENSE. + +import XCTest + +@testable import SimSlimKit + +/// Ports of profile_file_test.go. +final class ProfileFileTests: XCTestCase { + /// Writes `contents` to a fresh temporary file and returns its path. + private func writeProfile(_ contents: String) throws -> String { + let directory = FileManager.default.temporaryDirectory + .appendingPathComponent("simslim-tests-\(UUID().uuidString)") + try FileManager.default.createDirectory(at: directory, withIntermediateDirectories: true) + addTeardownBlock { try? FileManager.default.removeItem(at: directory) } + let url = directory.appendingPathComponent("profile.json") + try Data(contents.utf8).write(to: url) + return url.path + } + + private func missingPath() -> String { + FileManager.default.temporaryDirectory + .appendingPathComponent("simslim-absent-\(UUID().uuidString).json").path + } + + func testLoadSlimProfile() throws { + let path = try writeProfile( + """ + { + "name": "ci", + "description": "UI test runs", + "except": ["search", "store"], + "keep": ["com.apple.apsd"] + } + """) + let profile = try loadSlimProfile(path: path) + XCTAssertEqual(profile.exceptCategories, ["search", "store"]) + XCTAssertEqual(profile.keep, ["com.apple.apsd"]) + } + + func testLoadSlimProfileMinimal() throws { + let profile = try loadSlimProfile(path: try writeProfile("{}")) + XCTAssertTrue(profile.exceptCategories.isEmpty) + XCTAssertTrue(profile.keep.isEmpty) + } + + func testNullDocumentIsTheEmptyProfile() throws { + // Go decodes JSON null into the zero value. + XCTAssertEqual(try loadSlimProfile(path: try writeProfile("null")), Profile()) + } + + func testLoadSlimProfileKeepsRequiredEnabledLabels() throws { + let path = try writeProfile(#"{"keep": ["com.apple.gamed", "com.apple.sharingd"]}"#) + let profile = try loadSlimProfile(path: path) + for label in ["com.apple.gamed", "com.apple.sharingd"] { + XCTAssertTrue(profile.keep.contains(label)) + XCTAssertFalse( + profile.desired().contains(label), "must keep required service \(label) enabled") + } + } + + func testLoadSlimProfileTrimsAndSkipsBlankEntries() throws { + let path = try writeProfile( + #"{"except": [" search ", "", " "], "keep": [" com.apple.apsd "]}"#) + let profile = try loadSlimProfile(path: path) + XCTAssertEqual(profile.exceptCategories, ["search"]) + XCTAssertEqual(profile.keep, ["com.apple.apsd"]) + } + + func testLoadSlimProfileRejects() throws { + let cases: [(name: String, contents: String, messagePart: String)] = [ + ("unknown category", #"{"except": ["nope"]}"#, "unknown category \"nope\""), + ( + "unknown keep label", #"{"keep": ["com.apple.does-not-exist"]}"#, + "\"com.apple.does-not-exist\" is not a managed daemon" + ), + ("unknown field", #"{"disable": ["search"]}"#, "unknown field \"disable\""), + ("malformed json", #"{"except": ["#, "parse profile"), + ("wrong type for except", #"{"except": "search"}"#, "must be an array of strings"), + ("wrong type for name", #"{"name": 5}"#, "must be a string"), + ("array at top level", #"[]"#, "top level must be a JSON object"), + ("empty file", "", "is empty; write {} for the default profile"), + ("whitespace only", " \n ", "is empty; write {} for the default profile"), + ] + for tc in cases { + let path = try writeProfile(tc.contents) + XCTAssertThrowsError(try loadSlimProfile(path: path), tc.name) { error in + let message = (error as? SimSlimError)?.message ?? "\(error)" + XCTAssertTrue(message.contains(tc.messagePart), "\(tc.name): got \"\(message)\"") + } + } + } + + func testUnknownFieldMatchingIsCaseInsensitiveLikeGo() throws { + let profile = try loadSlimProfile(path: try writeProfile(#"{"Except": ["search"]}"#)) + XCTAssertEqual(profile.exceptCategories, ["search"]) + } + + func testLoadSlimProfileMissingFile() { + XCTAssertThrowsError(try loadSlimProfile(path: missingPath())) { error in + let message = (error as? SimSlimError)?.message ?? "" + XCTAssertTrue(message.hasPrefix("read profile "), message) + XCTAssertTrue(message.contains("no such file"), message) + } + } + + func testBuildProfile() throws { + let fromFlags = try buildProfile(profilePath: "", except: "search", keep: "com.apple.apsd") + XCTAssertTrue(fromFlags.exceptCategories.contains("search")) + XCTAssertTrue(fromFlags.keep.contains("com.apple.apsd")) + + XCTAssertThrowsError(try buildProfile(profilePath: "", except: "nope", keep: "")) + + let path = try writeProfile(#"{"except": ["search"]}"#) + XCTAssertEqual( + try buildProfile(profilePath: path, except: "", keep: "").exceptCategories, ["search"]) + + XCTAssertThrowsError(try buildProfile(profilePath: "some.json", except: "search", keep: "")) { + XCTAssertEqual( + ($0 as? SimSlimError)?.message, "--profile cannot be combined with --except or --keep") + } + XCTAssertThrowsError( + try buildProfile(profilePath: "some.json", except: "", keep: "com.apple.apsd")) + } + + func testBuildProfileKeepFlagIsNotValidatedLikeGo() throws { + // Go's --keep flag accepts any label (only profile files are validated); + // delta() later ignores unmanaged labels, so this is safe. Ported as-is. + let profile = try buildProfile(profilePath: "", except: "", keep: "com.apple.unknown") + XCTAssertEqual(profile.keep, ["com.apple.unknown"]) + } + + func testSplitList() { + XCTAssertEqual(splitList("a, b ,,c"), ["a", "b", "c"]) + XCTAssertEqual(splitList(""), []) + XCTAssertEqual(splitList(" , "), []) + } + + func testProfileFileName() { + let cases: [(String, String)] = [ + ("ci", "ci.json"), + ("UI Test Runs", "ui-test-runs.json"), + ("", "profile.json"), + (" ", "profile.json"), + ("prod.json", "prod.json"), + ("a/b:c", "a-b-c.json"), + ("--weird--", "weird.json"), + ] + for (name, want) in cases { + XCTAssertEqual(profileFileName(name), want, "profileFileName(\"\(name)\")") + } + } + + // MARK: - marshalProfile: byte-for-byte what Go's json.MarshalIndent prints + + func testMarshalProfileFull() { + let data = marshalProfile( + SlimProfile( + name: "ci", description: "UI test runs", except: ["search", "store"], + keep: ["com.apple.apsd"])) + XCTAssertEqual( + String(decoding: data, as: UTF8.self), + """ + { + "name": "ci", + "description": "UI test runs", + "except": [ + "search", + "store" + ], + "keep": [ + "com.apple.apsd" + ] + } + + """) + } + + func testMarshalProfileEmptyAndPartial() { + XCTAssertEqual(String(decoding: marshalProfile(SlimProfile()), as: UTF8.self), "{}\n") + XCTAssertEqual( + String(decoding: marshalProfile(SlimProfile(keep: ["com.apple.apsd"])), as: UTF8.self), + "{\n \"keep\": [\n \"com.apple.apsd\"\n ]\n}\n") + } + + func testMarshalProfileEscapesLikeGo() { + let data = marshalProfile(SlimProfile(name: "a&\"q\"\\\n\u{2028}\u{01}")) + XCTAssertEqual( + String(decoding: data, as: UTF8.self), + "{\n \"name\": \"a\\u003cb\\u003e\\u0026\\\"q\\\"\\\\\\n\\u2028\\u0001\"\n}\n") + } + + func testMarshalThenLoadRoundTrips() throws { + let original = SlimProfile( + name: "x & y", description: "d", except: ["search", "store"], keep: ["com.apple.apsd"]) + let path = try writeProfile(String(decoding: marshalProfile(original), as: UTF8.self)) + let parsed = try parseSlimProfile(try Data(contentsOf: URL(fileURLWithPath: path)), path: path) + XCTAssertEqual(parsed, original) + } +} diff --git a/swift/Tests/SimSlimKitTests/ProfilesTests.swift b/swift/Tests/SimSlimKitTests/ProfilesTests.swift new file mode 100644 index 0000000..93bb5fa --- /dev/null +++ b/swift/Tests/SimSlimKitTests/ProfilesTests.swift @@ -0,0 +1,302 @@ +// Copyright (c) 2026 Pavel Akhrameev (Swift port). MIT License; see LICENSE. + +import XCTest + +@testable import SimSlimKit + +/// Ports of profiles_test.go. These encode the safety invariants of the tool: +/// what may ever be disabled, and that nothing outside the allowlist is touched. +final class ProfilesTests: XCTestCase { + private let full = Profile() + + func testManagedExcludesForbidden() { + for label in forbiddenLabels { + XCTAssertFalse( + Catalog.managedSet.contains(label), + "forbidden daemon \(label) is in a category; it must never be managed") + } + } + + func testForbiddenListIsNotEmpty() { + // Guards against the generator silently producing an empty list, which + // would make testManagedExcludesForbidden vacuous. + XCTAssertGreaterThanOrEqual(forbiddenLabels.count, 10) + XCTAssertTrue(forbiddenLabels.contains("com.apple.nanoregistryd")) + } + + func testFullProfileDoesNotClaimUnmanagedProcesses() { + let desired = full.desired() + for label in [ + "com.apple.routined", "com.apple.sharingd", "com.apple.locationd", + "com.apple.eventkitsyncd", "com.apple.Spotlight", "com.apple.MercuryPoster", + "com.apple.texttospeech.SiriAUSP", + ] { + XCTAssertFalse(desired.contains(label), "full profile claims live process \(label)") + } + } + + func testNoDuplicateLabelsWithinCategory() { + for category in Catalog.categories { + XCTAssertEqual( + category.labels.count, Set(category.labels).count, + "category \(category.id) lists a label twice") + } + } + + func testCategoryIDsAreUnique() { + let ids = Catalog.categories.map(\.id) + XCTAssertEqual(ids.count, Set(ids).count) + XCTAssertFalse(ids.isEmpty) + } + + func testDesiredKeepsSharedLabelsOfExceptedCategories() { + var owners: [String: [String]] = [:] + for category in Catalog.categories { + for label in category.labels { owners[label, default: []].append(category.id) } + } + var sharedSeen = false + for (label, ids) in owners where ids.count >= 2 { + sharedSeen = true + for id in ids { + let profile = Profile(exceptCategories: [id]) + XCTAssertFalse( + profile.desired().contains(label), + "--except \(id) should keep shared label \(label) enabled") + } + } + XCTAssertTrue(sharedSeen, "expected at least one shared label (the AMS payment-sheet daemons)") + } + + func testEveryServiceHasShortDescription() { + var known = Set() + for category in Catalog.categories { + XCTAssertEqual( + category.serviceDescriptions.count, category.labels.count, + "category \(category.id) label and description counts differ") + for label in category.labels { + known.insert(label) + let description = category.serviceDescriptions[label] ?? "" + XCTAssertFalse( + description.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty, + "service \(label) has no user-facing description") + XCTAssertFalse( + description.contains("\n") || description.contains("\r"), + "service \(label) description must stay on one logical line") + XCTAssertLessThanOrEqual( + description.utf8.count, 90, "service \(label) description is too long") + } + } + for label in serviceDescriptionByLabel.keys { + XCTAssertTrue(known.contains(label), "description exists for unmanaged service \(label)") + } + } + + func testRequiredEnabledLabelsAreNeverSlimmed() { + let desired = full.desired() + var sawRequired = false + for category in Catalog.categories { + for service in category.alwaysEnabled { + sawRequired = true + XCTAssertFalse( + Catalog.slimmableSet.contains(service.label) || desired.contains(service.label), + "required daemon \(service.label) is included in a slim profile") + XCTAssertTrue( + Catalog.managedSet.contains(service.label), + "required daemon \(service.label) is missing from the repair allowlist") + XCTAssertFalse(service.reason.isEmpty, "\(service.label) has no user-facing reason") + } + } + XCTAssertTrue(sawRequired) + } + + func testDeltaRepairsRequiredEnabledLabels() { + let current: Set = ["com.apple.sharingd"] + let result = delta(current: current, desired: full.desired(), managed: Catalog.managedSet) + XCTAssertFalse(result.toDisable.isEmpty, "full profile should still disable slimmable labels") + XCTAssertEqual(result.toEnable, ["com.apple.sharingd"]) + } + + func testGamedStaysEnabledForXCTest() throws { + let label = "com.apple.gamed" + let desired = full.desired() + XCTAssertFalse(Catalog.slimmableSet.contains(label) || desired.contains(label)) + let apps = try XCTUnwrap(Catalog.category(id: "apps")) + XCTAssertTrue( + apps.alwaysEnabled.contains { + $0.label == label && !$0.reason.trimmingCharacters(in: .whitespaces).isEmpty + }, "apps must explain why gamed stays enabled") + let repair = delta(current: [label], desired: desired, managed: Catalog.managedSet) + XCTAssertEqual(repair.toEnable, [label]) + for other in ["com.apple.gamesaved", "com.apple.GameController.gamecontrollerd"] { + XCTAssertTrue( + desired.contains(other), "unrelated game service \(other) should stay slimmable") + } + } + + func testAssistantdStaysEnabledForSpotlight() throws { + let label = "com.apple.assistantd" + let desired = full.desired() + XCTAssertFalse(Catalog.slimmableSet.contains(label) || desired.contains(label)) + let siri = try XCTUnwrap(Catalog.category(id: "siri")) + XCTAssertTrue( + siri.alwaysEnabled.contains { + $0.label == label && !$0.reason.trimmingCharacters(in: .whitespaces).isEmpty + }, "siri must explain why assistantd stays enabled") + let repair = delta(current: [label], desired: desired, managed: Catalog.managedSet) + XCTAssertEqual(repair.toEnable, [label]) + for other in [ + "com.apple.assistant_service", "com.apple.corespeechd", "com.apple.siriknowledged", + ] { + XCTAssertTrue(desired.contains(other), "other Siri service \(other) should stay slimmable") + } + } + + func testWidgetsKeepNavdForMapsWidget() { + let label = "com.apple.navd" + XCTAssertFalse( + Profile(exceptCategories: ["widgets"]).desired().contains(label), + "--except widgets must keep navd enabled: the Maps widget spins without it") + XCTAssertTrue( + full.desired().contains(label), "navd should stay slimmable when widgets are disabled") + } + + func testCategoriesHaveUserImpactMetadata() { + for category in Catalog.categories { + XCTAssertFalse(category.downside.isEmpty, "category \(category.id) has no downside") + XCTAssertGreaterThan(category.approxMemoryMB, 0, "category \(category.id) memory estimate") + } + } + + func testCategoryByID() { + for category in Catalog.categories { + XCTAssertEqual(Catalog.category(id: category.id)?.id, category.id) + } + XCTAssertNil(Catalog.category(id: "nope")) + } + + func testDesiredHonorsKeep() { + XCTAssertTrue(full.desired().contains("com.apple.apsd")) + XCTAssertFalse(Profile(keep: ["com.apple.apsd"]).desired().contains("com.apple.apsd")) + } + + // MARK: - Platform rules (Profile.desired(for:)) + + func testWatchOSKeepsHomedEnabled() { + let watch = Device(udid: "W", platform: "watchOS") + XCTAssertTrue(full.desired().contains("com.apple.homed")) + XCTAssertFalse(full.desired(for: watch).contains("com.apple.homed")) + XCTAssertTrue(full.desired(for: watch).contains("com.apple.mobileassetd")) + } + + func testVisionOSKeepsMobileassetdEnabled() { + let vision = Device(udid: "V", platform: "visionOS") + XCTAssertTrue(full.desired().contains("com.apple.mobileassetd")) + XCTAssertFalse(full.desired(for: vision).contains("com.apple.mobileassetd")) + XCTAssertTrue(full.desired(for: vision).contains("com.apple.homed")) + } + + func testIOSAndEmptyPlatformGetTheFullCatalog() { + for platform in ["", "iOS", "tvOS"] { + let device = Device(udid: "D", platform: platform) + XCTAssertEqual(full.desired(for: device), full.desired(), "platform \"\(platform)\"") + } + } + + // MARK: - delta + + func testDelta() { + let managed: Set = ["a", "b", "c"] + struct Case { + let name: String + let current: Set + let desired: Set + let disable: [String] + let enable: [String] + } + let cases = [ + Case( + name: "enable all from stock", current: [], desired: ["a", "b", "c"], + disable: ["a", "b", "c"], enable: []), + Case( + name: "restore all to stock", current: ["a", "b", "c"], desired: [], disable: [], + enable: ["a", "b", "c"]), + Case( + name: "already in desired state", current: ["a", "b"], desired: ["a", "b"], disable: [], + enable: []), + Case( + name: "profile edit adds and removes", current: ["a", "b"], desired: ["b", "c"], + disable: ["c"], enable: ["a"]), + Case( + name: "unmanaged desired label is ignored", current: [], desired: ["x"], disable: [], + enable: []), + Case( + name: "unmanaged disabled label is left alone", current: ["x"], desired: [], disable: [], + enable: []), + ] + for tc in cases { + let got = delta(current: tc.current, desired: tc.desired, managed: managed) + XCTAssertEqual(got.toDisable, tc.disable, tc.name) + XCTAssertEqual(got.toEnable, tc.enable, tc.name) + } + } + + func testDeltaNeverTouchesUnmanagedLabels() { + // The central safety property, checked against the real allowlist: whatever + // the device has disabled and whatever the profile asks for, delta only + // ever names managed labels. + let current: Set = Set(forbiddenLabels).union(["com.apple.not-ours", "com.apple.apsd"]) + let desired = Set(forbiddenLabels).union(full.desired()).union(["com.apple.also-not-ours"]) + let result = delta(current: current, desired: desired, managed: Catalog.managedSet) + for label in result.toDisable + result.toEnable { + XCTAssertTrue(Catalog.managedSet.contains(label), "delta named unmanaged label \(label)") + } + for label in forbiddenLabels { + XCTAssertFalse(result.toDisable.contains(label) || result.toEnable.contains(label)) + } + } + + func testDeltaIsSorted() { + let result = delta(current: [], desired: ["c", "a", "b"], managed: ["a", "b", "c"]) + XCTAssertEqual(result.toDisable, ["a", "b", "c"]) + } + + // MARK: - JSON contract with the SwiftUI app + + func testCategoryJSONKeys() throws { + let siri = try XCTUnwrap(Catalog.category(id: "siri")) + let search = try XCTUnwrap(Catalog.category(id: "search")) + + let siriJSON = try jsonObject(siri) + XCTAssertEqual( + Set(siriJSON.keys), + [ + "id", "name", "description", "downside", "approxMemoryMB", "labels", + "serviceDescriptions", "alwaysEnabled", + ]) + // `omitempty`: a category with no always-enabled services omits the key. + XCTAssertFalse(try jsonObject(search).keys.contains("alwaysEnabled")) + + let alwaysEnabled = try XCTUnwrap(siriJSON["alwaysEnabled"] as? [[String: Any]]) + XCTAssertEqual(Set(try XCTUnwrap(alwaysEnabled.first).keys), ["label", "reason"]) + } + + func testCategoryRoundTrips() throws { + for category in Catalog.categories { + let data = try JSONEncoder().encode(category) + XCTAssertEqual(try JSONDecoder().decode(Category.self, from: data), category) + } + } + + func testDeviceJSONKeysExcludeInternalFields() throws { + let device = Device( + udid: "U", name: "N", state: "Booted", platform: "iOS", osVersion: "27.2", set: "default", + dataPath: "/secret/path", runtimeID: "com.apple.CoreSimulator.SimRuntime.iOS-27-2") + XCTAssertEqual( + Set(try jsonObject(device).keys), ["udid", "name", "state", "platform", "osVersion", "set"]) + } + + private func jsonObject(_ value: T) throws -> [String: Any] { + let data = try JSONEncoder().encode(value) + return try XCTUnwrap(JSONSerialization.jsonObject(with: data) as? [String: Any]) + } +} diff --git a/swift/Tests/SimSlimKitTests/SimctlTests.swift b/swift/Tests/SimSlimKitTests/SimctlTests.swift new file mode 100644 index 0000000..09f7ac9 --- /dev/null +++ b/swift/Tests/SimSlimKitTests/SimctlTests.swift @@ -0,0 +1,293 @@ +// Copyright (c) 2026 Pavel Akhrameev (Swift port). MIT License; see LICENSE. + +import TestSupport +import XCTest + +@testable import SimSlimKit + +final class SimctlTests: XCTestCase { + private let ios = "com.apple.CoreSimulator.SimRuntime.iOS-27-2" + private let tvos = "com.apple.CoreSimulator.SimRuntime.tvOS-27-2" + private let xros = "com.apple.CoreSimulator.SimRuntime.xrOS-27-2" + + // MARK: - parseRuntime + + func testParseRuntime() { + let cases: [(String, String?, String?)] = [ + ("com.apple.CoreSimulator.SimRuntime.iOS-27-2", "iOS", "27.2"), + ("com.apple.CoreSimulator.SimRuntime.iOS-18-5", "iOS", "18.5"), + ("com.apple.CoreSimulator.SimRuntime.tvOS-26-5", "tvOS", "26.5"), + ("com.apple.CoreSimulator.SimRuntime.watchOS-11-5", "watchOS", "11.5"), + ("com.apple.CoreSimulator.SimRuntime.xrOS-2-5", "visionOS", "2.5"), + ("com.apple.CoreSimulator.SimRuntime.iOS-17-0-1", "iOS", "17.0.1"), + ("com.apple.CoreSimulator.SimRuntime.macOS-15-0", nil, nil), + ("com.apple.CoreSimulator.SimRuntime.iOS", nil, nil), + ("com.apple.CoreSimulator.SimRuntime.iOS-", nil, nil), + ("something.else.iOS-27-2", nil, nil), + ("", nil, nil), + ] + for (runtime, platform, version) in cases { + let parsed = Simctl.parseRuntime(runtime) + XCTAssertEqual(parsed?.platform, platform, runtime) + XCTAssertEqual(parsed?.version, version, runtime) + } + } + + // MARK: - parseDisabled + + func testParseDisabled() { + let output = """ + disabled services = { + \t"com.apple.a" => disabled + \t"com.apple.b" => enabled + \t"com.apple.c" => true + \t"com.apple.d" => false + \t"com.apple.e"=>disabled + \tno quotes => disabled + \t"unterminated => disabled + \t"com.apple.f" disabled + } + """ + XCTAssertEqual(Simctl.parseDisabled(output), ["com.apple.a", "com.apple.c", "com.apple.e"]) + XCTAssertEqual(Simctl.parseDisabled(""), []) + } + + // MARK: - listing + + func testListDevicesFiltersAndMapsFields() throws { + let host = FakeHost(devices: [ + .init(udid: "A", name: "iPhone", state: "Booted"), + .init(udid: "B", name: "iPad"), + .init(udid: "C", name: "Gone", isAvailable: false), + .init(udid: "D", name: "TV", runtime: tvos), + .init(udid: "E", name: "Vision", runtime: xros), + .init(udid: "F", name: "Mac", runtime: "com.apple.CoreSimulator.SimRuntime.macOS-15-0"), + ]) + let devices = try Simctl(runner: host).listDevices() + XCTAssertEqual( + Set(devices.map(\.udid)), ["A", "B", "D", "E"], "unavailable and unsupported dropped") + + let iphone = try XCTUnwrap(devices.first { $0.udid == "A" }) + XCTAssertEqual(iphone.name, "iPhone") + XCTAssertEqual(iphone.state, "Booted") + XCTAssertEqual(iphone.platform, "iOS") + XCTAssertEqual(iphone.osVersion, "27.2") + XCTAssertEqual(iphone.set, "default") + XCTAssertEqual(iphone.runtimeID, ios) + XCTAssertEqual(iphone.dataPath, "/fake/A/data") + XCTAssertEqual(devices.first { $0.udid == "E" }?.platform, "visionOS") + } + + func testListDevicesTreatsMissingIsAvailableAsUnavailable() throws { + // Like the Go tool: an entry without isAvailable is not listed. + final class Raw: CommandRunning, @unchecked Sendable { + func run(_ e: Executable, _ a: [String], timeout: TimeInterval?) throws -> CommandResult { + let json = + #"{"devices":{"com.apple.CoreSimulator.SimRuntime.iOS-27-2":[{"udid":"X","name":"n","state":"Shutdown"}]}}"# + return CommandResult(status: 0, stdout: Data(json.utf8)) + } + } + XCTAssertTrue(try Simctl(runner: Raw()).listDevices().isEmpty) + } + + func testDefaultSetFailureIsFatalWithStderrAndHint() { + let host = FakeHost() + host.listFailure = + "xcrun: error: unable to find utility \"simctl\", not a developer tool or in PATH" + XCTAssertThrowsError(try Simctl(runner: host).listDevices()) { error in + let message = (error as? SimSlimError)?.message ?? "" + XCTAssertTrue(message.hasPrefix("simctl list: exit status 1: xcrun: error"), message) + XCTAssertTrue( + message.contains("select one with `sudo xcode-select -s /Applications/Xcode.app`"), message) + } + host.listFailure = "boom" + XCTAssertThrowsError(try Simctl(runner: host).listDevices()) { error in + XCTAssertEqual((error as? SimSlimError)?.message, "simctl list: exit status 1: boom") + } + } + + func testSecondarySetThatCannotBeListedIsSkipped() throws { + let host = FakeHost(devices: [.init(udid: "A", name: "default one")]) + var simctl = Simctl(runner: host) + simctl.registerDeviceSet("/no/such/set") + let devices = try simctl.listDevices() + XCTAssertEqual(devices.map(\.udid), ["A"]) + } + + func testExtraAndTestingSetsAreScanned() throws { + let host = FakeHost(devices: [.init(udid: "A", name: "d")]) + host.sets["testing"] = [.init(udid: "T", name: "clone")] + host.sets["/custom"] = [.init(udid: "C", name: "custom")] + var simctl = Simctl(runner: host) + simctl.registerDeviceSet("/custom") + let devices = try simctl.listDevices() + XCTAssertEqual(Set(devices.map(\.udid)), ["A", "T", "C"]) + XCTAssertEqual(devices.first { $0.udid == "T" }?.set, "testing") + XCTAssertEqual(devices.first { $0.udid == "C" }?.set, "/custom") + } + + func testRegisterDeviceSetIgnoresDuplicatesAndKnownTokens() { + var simctl = Simctl(runner: FakeHost()) + simctl.registerDeviceSet("testing") + simctl.registerDeviceSet("/x") + simctl.registerDeviceSet("/x") + XCTAssertEqual(simctl.extraSets, ["/x"]) + XCTAssertEqual(simctl.knownSets.map(\.token), ["", "testing", "/x"]) + } + + func testSimctlArgsPutSetBeforeTheSubcommand() { + var simctl = Simctl(runner: FakeHost()) + simctl.registerDeviceSet("/x") + XCTAssertEqual(simctl.simctlArgs(set: "default", ["list"]), ["simctl", "list"]) + XCTAssertEqual( + simctl.simctlArgs(set: "testing", ["list"]), ["simctl", "--set", "testing", "list"]) + XCTAssertEqual(simctl.simctlArgs(set: "/x", ["list"]), ["simctl", "--set", "/x", "list"]) + XCTAssertEqual(simctl.simctlArgs(set: "unknown", ["list"]), ["simctl", "list"]) + } + + func testFindDevice() throws { + let host = FakeHost(devices: [.init(udid: "A", name: "d")]) + host.sets["testing"] = [.init(udid: "T", name: "clone")] + let simctl = Simctl(runner: host) + XCTAssertEqual(try simctl.findDevice(udid: "A").set, "default") + XCTAssertEqual(try simctl.findDevice(udid: "T").set, "testing") + XCTAssertThrowsError(try simctl.findDevice(udid: "nope")) { error in + XCTAssertEqual((error as? SimSlimError)?.message, "no simulator with udid nope") + } + // A named set looks only there. + XCTAssertThrowsError(try simctl.findDevice(udid: "A", set: "testing")) + XCTAssertEqual(try simctl.findDevice(udid: "T", set: "testing").udid, "T") + } + + func testFindDeviceNeverMatchesAnAlias() { + // `simctl` accepts aliases like "all" and "booted"; a lookup by UDID must not. + let host = FakeHost(devices: [.init(udid: "A", name: "d", state: "Booted")]) + for alias in ["all", "booted", "available", ""] { + XCTAssertThrowsError(try Simctl(runner: host).findDevice(udid: alias), alias) + } + } + + // MARK: - reading launchd, with retries + + private func settling() -> CommandResult { + CommandResult(status: 124, stderr: Data("launchctl: Domain is tearing down".utf8)) + } + + private func slept(_ simctl: inout Simctl) -> SleepLog { + let log = SleepLog() + simctl.sleep = { log.record($0) } + return log + } + + func testReadDisabledPassesTheSpawnTimeoutAndArguments() throws { + let host = FakeHost() + host.disabled["U"] = ["com.apple.apsd"] + var simctl = Simctl(runner: host) + simctl.spawnTimeout = 77 + XCTAssertEqual(try simctl.readDisabled(set: "default", udid: "U"), ["com.apple.apsd"]) + let call = try XCTUnwrap(host.calls.last) + XCTAssertEqual( + call.arguments, ["simctl", "spawn", "U", "launchctl", "print-disabled", "system"]) + XCTAssertEqual(call.timeout, 77) + } + + func testReadLaunchdRetriesErrorOneTwentyFourWithBackoff() throws { + let host = FakeHost() + host.disabled["U"] = ["com.apple.apsd"] + host.queueSpawnResults(udid: "U", [settling(), settling()]) + var simctl = Simctl(runner: host) + let log = slept(&simctl) + XCTAssertEqual(try simctl.readDisabled(set: "default", udid: "U"), ["com.apple.apsd"]) + XCTAssertEqual(log.values, [1, 2], "waits the first two retry delays") + XCTAssertEqual(host.calls.count, 3) + } + + func testReadLaunchdRecognizesSettlingByTextToo() throws { + let host = FakeHost() + host.disabled["U"] = [] + host.queueSpawnResults( + udid: "U", [CommandResult(status: 1, stderr: Data("xpc error code=124".utf8))]) + var simctl = Simctl(runner: host) + _ = slept(&simctl) + XCTAssertNoThrow(try simctl.readDisabled(set: "default", udid: "U")) + XCTAssertEqual(host.calls.count, 2) + } + + func testReadLaunchdGivesUpAfterTheLastDelay() { + let host = FakeHost() + host.disabled["U"] = [] + host.queueSpawnResults(udid: "U", Array(repeating: settling(), count: 10)) + var simctl = Simctl(runner: host) + let log = slept(&simctl) + XCTAssertThrowsError(try simctl.readDisabled(set: "default", udid: "U")) { error in + let message = (error as? SimSlimError)?.message ?? "" + XCTAssertTrue(message.hasPrefix("launchctl print-disabled: exit status 124:"), message) + XCTAssertTrue(message.contains("Domain is tearing down"), message) + } + XCTAssertEqual(log.values, [1, 2, 4, 8]) + XCTAssertEqual(host.calls.count, 5, "the first attempt plus one per delay") + } + + func testReadLaunchdDoesNotRetryOtherFailures() { + let host = FakeHost() + host.disabled["U"] = [] + host.queueSpawnResults( + udid: "U", [CommandResult(status: 2, stderr: Data("permission denied".utf8))]) + var simctl = Simctl(runner: host) + let log = slept(&simctl) + XCTAssertThrowsError(try simctl.readDisabled(set: "default", udid: "U")) + XCTAssertEqual(log.values, []) + XCTAssertEqual(host.calls.count, 1) + } + + func testReadLaunchdRetriesATimedOutAttempt() throws { + let host = FakeHost() + host.disabled["U"] = ["com.apple.apsd"] + host.queueSpawnResults(udid: "U", [CommandResult(status: -9, timedOut: true)]) + var simctl = Simctl(runner: host) + let log = slept(&simctl) + XCTAssertEqual(try simctl.readDisabled(set: "default", udid: "U"), ["com.apple.apsd"]) + XCTAssertEqual(log.values, [1]) + } + + func testTimedOutErrorMessageSaysSo() { + let host = FakeHost() + host.queueSpawnResults( + udid: "U", Array(repeating: CommandResult(status: -9, timedOut: true), count: 5)) + var simctl = Simctl(runner: host) + simctl.spawnTimeout = 90 + _ = slept(&simctl) + XCTAssertThrowsError(try simctl.readDisabled(set: "default", udid: "U")) { error in + XCTAssertTrue( + ((error as? SimSlimError)?.message ?? "").hasPrefix( + "launchctl print-disabled: timed out after 90s")) + } + } + + func testReadLaunchdOnANonDefaultSetTargetsIt() throws { + let host = FakeHost() + host.disabled["U"] = [] + var simctl = Simctl(runner: host) + simctl.registerDeviceSet("testing") + _ = try simctl.readDisabled(set: "testing", udid: "U") + XCTAssertEqual( + host.calls.last?.arguments, + ["simctl", "--set", "testing", "spawn", "U", "launchctl", "print-disabled", "system"]) + } +} + +/// Records the pauses a retry loop asked for, without actually sleeping. +final class SleepLog: @unchecked Sendable { + private let lock = NSLock() + private var _values: [TimeInterval] = [] + func record(_ value: TimeInterval) { + lock.lock() + _values.append(value) + lock.unlock() + } + var values: [TimeInterval] { + lock.lock() + defer { lock.unlock() } + return _values + } +} diff --git a/swift/Tests/SimSlimKitTests/SlimTests.swift b/swift/Tests/SimSlimKitTests/SlimTests.swift new file mode 100644 index 0000000..10be36a --- /dev/null +++ b/swift/Tests/SimSlimKitTests/SlimTests.swift @@ -0,0 +1,661 @@ +// Copyright (c) 2026 Pavel Akhrameev (Swift port). MIT License; see LICENSE. + +import TestSupport +import XCTest + +@testable import SimSlimKit + +private final class Counter: @unchecked Sendable { + private let lock = NSLock() + private var current = 0 + private(set) var peak = 0 + func enter() { + lock.lock() + current += 1 + peak = max(peak, current) + lock.unlock() + } + func leave() { + lock.lock() + current -= 1 + lock.unlock() + } +} + +private final class Tally: @unchecked Sendable { + private let lock = NSLock() + private var counts: [String: Int] = [:] + func bump(_ key: String) -> Int { + lock.lock() + defer { lock.unlock() } + counts[key, default: 0] += 1 + return counts[key]! + } +} + +private final class Log: @unchecked Sendable { + private let lock = NSLock() + private var lines: [String] = [] + func add(_ line: String) { + lock.lock() + lines.append(line) + lock.unlock() + } + var all: [String] { + lock.lock() + defer { lock.unlock() } + return lines + } +} + +final class SlimTests: XCTestCase { + private let ios = "com.apple.CoreSimulator.SimRuntime.iOS-27-2" + private let old = "com.apple.CoreSimulator.SimRuntime.iOS-17-0" + private let udid = "AAAAAAAA-0000-0000-0000-000000000001" + private var root = "" + + override func setUpWithError() throws { + root = NSTemporaryDirectory() + "simslim-slim-\(UUID().uuidString)" + try FileManager.default.createDirectory(atPath: root, withIntermediateDirectories: true) + } + + override func tearDown() { + try? FileManager.default.removeItem(atPath: root) + } + + private var profileLabels: Set { Profile().desired() } + + private func host( + state: String = "Shutdown", runtime: String? = nil, disabled: Set? = nil + ) -> FakeHost { + let host = FakeHost(devices: [ + .init(udid: udid, name: "iPhone", runtime: runtime ?? ios, state: state) + ]) + host.storeRoot = root + "/store" + if state == "Booted" { host.disabled[udid] = disabled ?? [] } + return host + } + + private func simctl(_ host: FakeHost) -> Simctl { + var simctl = Simctl(runner: host) + simctl.retryDelays = [0, 0, 0, 0] + simctl.sleep = { _ in } + simctl.storeRoot = root + "/store" + return simctl + } + + private func storeFile() -> String { + root + "/store/com.apple.CoreSimulator.SimDevice.\(udid)/disabled.plist" + } + + private func verbs(_ host: FakeHost) -> [String] { + host.calls.compactMap { call -> String? in + guard call.executable == .xcrun else { return nil } + var args = call.arguments + if args.count > 2, args[1] == "--set" { args.removeSubrange(1...2) } + if args.count > 2, args[1] == "spawn" { return "spawn:" + args[4...].joined(separator: " ") } + return args.dropFirst().first + } + } + + private func transitions(_ host: FakeHost) -> [String] { + verbs(host).filter { + $0.hasPrefix("spawn:disable ") || $0.hasPrefix("spawn:enable ") + || $0.hasPrefix("spawn:bootout ") || $0.hasPrefix("spawn:unload ") + } + } + + // MARK: - CRLF output + + func testParsersSplitCRLFLines() { + XCTAssertEqual( + Simctl.parseDisabled("\"a\" => disabled\r\n\"b\" => disabled\r\n\"c\" => enabled\r\n"), + ["a", "b"]) + XCTAssertEqual(parseLaunchctlList("PID\tStatus\tLabel\r\n-\t0\tx\r\n-\t0\ty\r\n"), ["x", "y"]) + } + + // MARK: - DisabledStore + + func testStoreRoundTripAndMerge() throws { + let store = DisabledStore(root: root + "/store") + XCTAssertEqual( + try store.readDisabled(udid: udid), [], "a device that never booted has no store") + + try store.write(udid: udid, toDisable: ["b.service", "a.service"], toEnable: []) + XCTAssertEqual(try store.readDisabled(udid: udid), ["a.service", "b.service"]) + + // Enabling records an explicit false and keeps everything else. + try store.write(udid: udid, toDisable: ["c.service"], toEnable: ["a.service"]) + XCTAssertEqual( + try store.readEntries(udid: udid), + ["a.service": false, "b.service": true, "c.service": true]) + XCTAssertEqual(try store.readDisabled(udid: udid), ["b.service", "c.service"]) + } + + func testStoreKeepsTheRuntimesOwnEntries() throws { + let dir = root + "/store/com.apple.CoreSimulator.SimDevice.\(udid)" + try FileManager.default.createDirectory(atPath: dir, withIntermediateDirectories: true) + let runtimeWritten = """ + + + com.apple.runtime.enabled + com.apple.unmanaged.disabled + + """ + try runtimeWritten.write(toFile: dir + "/disabled.plist", atomically: true, encoding: .utf8) + + let store = DisabledStore(root: root + "/store") + try store.write(udid: udid, toDisable: ["com.apple.mine"], toEnable: []) + XCTAssertEqual( + try store.readEntries(udid: udid), + [ + "com.apple.runtime.enabled": false, "com.apple.unmanaged.disabled": true, + "com.apple.mine": true, + ]) + } + + func testStoreWriteDoesNotDropNonBooleanEntries() throws { + let dir = root + "/store/com.apple.CoreSimulator.SimDevice.\(udid)" + try FileManager.default.createDirectory(atPath: dir, withIntermediateDirectories: true) + let text = """ + + + com.apple.other7 + com.apple.runtime.enabled + + """ + try text.write(toFile: dir + "/disabled.plist", atomically: true, encoding: .utf8) + + let store = DisabledStore(root: root + "/store") + try store.write(udid: udid, toDisable: ["com.apple.mine"], toEnable: []) + + let data = try Data(contentsOf: URL(fileURLWithPath: dir + "/disabled.plist")) + let dict = try XCTUnwrap( + PropertyListSerialization.propertyList(from: data, options: [], format: nil) + as? [String: Any]) + XCTAssertEqual(dict["com.apple.other"] as? Int, 7, "an entry simslim does not own must survive") + XCTAssertEqual(dict["com.apple.mine"] as? Bool, true) + XCTAssertEqual(dict["com.apple.runtime.enabled"] as? Bool, false) + } + + func testStoreIgnoresNonBooleanValuesAndRejectsGarbage() throws { + let text = """ + + + a + count1 + nametrue + + """ + XCTAssertEqual(try DisabledStore.parse(Data(text.utf8)), ["a": true]) + XCTAssertThrowsError(try DisabledStore.parse(Data("not a plist".utf8))) + } + + func testStoreEncodesSortedAndEscaped() throws { + let data = DisabledStore.encode(["z&<>": true, "a": false]) + let text = String(decoding: data, as: UTF8.self) + XCTAssertLessThan( + text.range(of: "a")!.lowerBound, text.range(of: "z")!.lowerBound) + XCTAssertTrue(text.contains("z&<>")) + XCTAssertEqual(try DisabledStore.parse(data), ["z&<>": true, "a": false]) + XCTAssertEqual(DisabledStore.encode(["z&<>": true, "a": false]), data, "stable output") + } + + func testStoreWriteIsAtomicAndLeavesNoTemporaryFiles() throws { + let store = DisabledStore(root: root + "/store") + try store.write(udid: udid, toDisable: ["a"], toEnable: []) + try store.write(udid: udid, toDisable: ["b"], toEnable: []) + let dir = root + "/store/com.apple.CoreSimulator.SimDevice.\(udid)" + XCTAssertEqual(try FileManager.default.contentsOfDirectory(atPath: dir), ["disabled.plist"]) + let attrs = try FileManager.default.attributesOfItem(atPath: dir + "/disabled.plist") + XCTAssertEqual(attrs[.posixPermissions] as? Int, 0o644) + } + + func testStoreWriteFailureIsAnError() throws { + // A file where the device directory should be. + try FileManager.default.createDirectory( + atPath: root + "/store", withIntermediateDirectories: true) + FileManager.default.createFile( + atPath: root + "/store/com.apple.CoreSimulator.SimDevice.\(udid)", contents: Data()) + let store = DisabledStore(root: root + "/store") + XCTAssertThrowsError(try store.write(udid: udid, toDisable: ["a"], toEnable: [])) + } + + // MARK: - ensure: refusals + + func testRefusesNonEmptyProfileOnRuntimeWithoutPersistence() throws { + let host = host(state: "Booted", runtime: old) + XCTAssertThrowsError( + try simctl(host).ensure(set: "default", udid: udid, desired: profileLabels) + ) { error in + let text = "\(error)" + XCTAssertTrue(text.contains("iOS 17.0 runtime cannot persist"), text) + XCTAssertTrue(text.contains("iOS 18.5 or newer"), text) + } + // Nothing but the device lookup ran: no boot, shutdown or launchctl. + XCTAssertEqual(verbs(host), ["list"]) + } + + // MARK: - ensure: offline route + + func testShutdownDeviceIsSlimmedByTheStoreWithOneBootAndNoSpawns() throws { + let host = host() + let lines = Log() + let changed = try simctl(host).ensure( + set: "default", udid: udid, desired: profileLabels, reporter: { lines.add($0) }) + XCTAssertTrue(changed) + XCTAssertEqual(host.devices[0].state, "Booted") + XCTAssertEqual(host.disabled[udid]?.intersection(Catalog.managedSet), profileLabels) + XCTAssertTrue(transitions(host).isEmpty, "no per-label launchctl spawns: \(transitions(host))") + XCTAssertEqual(verbs(host).filter { $0 == "boot" }.count, 1) + XCTAssertFalse(verbs(host).contains("shutdown")) + XCTAssertTrue(lines.all.contains { $0.hasPrefix("Reconfiguring \(profileLabels.count)") }) + XCTAssertEqual(try DisabledStore(root: root + "/store").readDisabled(udid: udid), profileLabels) + } + + func testBootedDeviceWithADeltaShutsDownThenBootsOnce() throws { + let host = host(state: "Booted") + let changed = try simctl(host).ensure(set: "default", udid: udid, desired: profileLabels) + XCTAssertTrue(changed) + let v = verbs(host) + let shutdownIndex = try XCTUnwrap(v.firstIndex(of: "shutdown")) + let lastBoot = try XCTUnwrap(v.lastIndex(of: "boot")) + XCTAssertLessThan(shutdownIndex, lastBoot) + XCTAssertTrue(transitions(host).isEmpty) + XCTAssertEqual(host.devices[0].state, "Booted") + XCTAssertEqual(host.disabled[udid]?.intersection(Catalog.managedSet), profileLabels) + } + + func testBootedDeviceAlreadyMatchingIsLeftAlone() throws { + let host = host(state: "Booted", disabled: profileLabels) + let changed = try simctl(host).ensure(set: "default", udid: udid, desired: profileLabels) + XCTAssertFalse(changed) + XCTAssertFalse(verbs(host).contains("shutdown"), "an already-slim device is not rebooted") + XCTAssertTrue(transitions(host).isEmpty) + } + + func testStockProfileRestoresEveryManagedLabelOfflineAndOnlyThose() throws { + var all = Catalog.managedSet + all.insert("com.apple.unmanaged.service") + let host = host(state: "Booted", disabled: all) + // The store records what launchd_sim keeps for the device. + try DisabledStore(root: root + "/store").write( + udid: udid, toDisable: Array(all), toEnable: []) + let lines = Log() + let changed = try simctl(host).ensure( + set: "default", udid: udid, desired: [], reporter: { lines.add($0) }) + XCTAssertTrue(changed) + // The offline route did it: the store's explicit enables won at boot. + XCTAssertTrue(lines.all.contains { $0.hasPrefix("Reconfiguring \(Catalog.managedSet.count)") }) + XCTAssertFalse(lines.all.contains { $0.hasPrefix("Could not apply") }) + XCTAssertTrue(transitions(host).isEmpty) + XCTAssertEqual(host.disabled[udid], ["com.apple.unmanaged.service"]) + } + + func testManagedLabelsAreTheOnlyOnesEverWritten() throws { + let host = host() + try simctl(host).ensure(set: "default", udid: udid, desired: profileLabels) + let written = try DisabledStore(root: root + "/store").readEntries(udid: udid) + XCTAssertTrue(Set(written.keys).isSubset(of: Catalog.managedSet)) + } + + func testWatchOSKeepsHomedEnabledAndVisionOSKeepsMobileassetd() throws { + let watch = FakeHost(devices: [ + .init(udid: udid, name: "Watch", runtime: "com.apple.CoreSimulator.SimRuntime.watchOS-11-5") + ]) + watch.storeRoot = root + "/store" + try simctl(watch).ensure(set: "default", udid: udid, desired: profileLabels) + XCTAssertFalse(watch.disabled[udid]!.contains("com.apple.homed")) + + let vision = FakeHost(devices: [ + .init(udid: udid, name: "Vision", runtime: "com.apple.CoreSimulator.SimRuntime.xrOS-2-5") + ]) + vision.storeRoot = root + "/store2" + var visionCtl = simctl(vision) + visionCtl.storeRoot = root + "/store2" + try visionCtl.ensure(set: "default", udid: udid, desired: profileLabels) + XCTAssertFalse(vision.disabled[udid]!.contains("com.apple.mobileassetd")) + } + + // MARK: - ensure: fallback to launchctl + + func testIgnoredStoreFallsBackToLaunchctlAndStillEndsSlim() throws { + let host = host() + host.honoursStore = false + let lines = Log() + let changed = try simctl(host).ensure( + set: "default", udid: udid, desired: profileLabels, reporter: { lines.add($0) }) + XCTAssertTrue(changed) + XCTAssertTrue( + lines.all.contains { $0.hasPrefix("Could not apply the changes while the simulator was off") } + ) + XCTAssertEqual(host.disabled[udid]?.intersection(Catalog.managedSet), profileLabels) + XCTAssertEqual( + transitions(host).filter { $0.hasPrefix("spawn:disable ") }.count, profileLabels.count) + XCTAssertTrue(verbs(host).contains("shutdown"), "the fallback reboots to persist") + } + + func testOverridesLostAtRebootIsAnError() throws { + let host = host() + host.honoursStore = false + host.persistsOverrides = false // the runtime lies about persistence + XCTAssertThrowsError( + try simctl(host).ensure(set: "default", udid: udid, desired: profileLabels) + ) { error in + XCTAssertTrue("\(error)".contains("did not survive the reboot"), "\(error)") + } + } + + func testUnreadableStoreFallsBackWithoutTouchingIt() throws { + let dir = root + "/store/com.apple.CoreSimulator.SimDevice.\(udid)" + try FileManager.default.createDirectory(atPath: dir, withIntermediateDirectories: true) + for (name, text) in [ + ("truncated xml", "a"), + ("old-style text", "garbage"), + ("old-style dictionary", "{ a = b; }"), + ] { + let host = host() + try text.write(toFile: dir + "/disabled.plist", atomically: true, encoding: .utf8) + let lines = Log() + let changed = try simctl(host).ensure( + set: "default", udid: udid, desired: profileLabels, reporter: { lines.add($0) }) + XCTAssertTrue(changed, name) + XCTAssertFalse(lines.all.contains { $0.hasPrefix("Reconfiguring") }, name) + XCTAssertTrue(lines.all.contains { $0.hasPrefix("Could not apply") }, name) + XCTAssertEqual( + try String(contentsOfFile: dir + "/disabled.plist", encoding: .utf8), text, name) + XCTAssertEqual(host.disabled[udid]?.intersection(Catalog.managedSet), profileLabels, name) + } + } + + func testAnEmptyStoreFileIsAnEmptyStoreAndTakesTheOfflineRoute() throws { + let dir = root + "/store/com.apple.CoreSimulator.SimDevice.\(udid)" + try FileManager.default.createDirectory(atPath: dir, withIntermediateDirectories: true) + FileManager.default.createFile(atPath: dir + "/disabled.plist", contents: Data()) + let host = host() + let lines = Log() + try simctl(host).ensure( + set: "default", udid: udid, desired: profileLabels, reporter: { lines.add($0) }) + XCTAssertTrue(lines.all.contains { $0.hasPrefix("Reconfiguring") }) + XCTAssertFalse(lines.all.contains { $0.hasPrefix("Could not apply") }) + XCTAssertEqual(try DisabledStore(root: root + "/store").readDisabled(udid: udid), profileLabels) + } + + // MARK: - applyDelta + + func testApplyDeltaRetriesAFailedLabelOnALaterPass() throws { + let host = host(state: "Booted") + let tally = Tally() + host.failTransition = { verb, label in + guard label == "com.apple.flaky" else { return nil } + return tally.bump("\(verb) \(label)") == 1 + ? CommandResult(status: 124, stderr: Data("Domain is tearing down".utf8)) : nil + } + let lines = Log() + try simctl(host).applyDelta( + set: "default", udid: udid, toDisable: ["com.apple.flaky", "com.apple.fine"], toEnable: [], + disableAction: .overrideOnly, reporter: { lines.add($0) }) + XCTAssertEqual(host.disabled[udid], ["com.apple.flaky", "com.apple.fine"]) + XCTAssertTrue(lines.all.contains { $0.contains("retrying 1 failed services (pass 2/3)") }) + } + + func testApplyDeltaGivesUpAfterThreePasses() throws { + let host = host(state: "Booted") + host.failTransition = { _, label in + label == "com.apple.bad" ? CommandResult(status: 1, stderr: Data("nope".utf8)) : nil + } + XCTAssertThrowsError( + try simctl(host).applyDelta( + set: "default", udid: udid, toDisable: ["com.apple.bad", "com.apple.ok"], toEnable: [], + disableAction: .overrideOnly, reporter: nil) + ) { error in + let text = "\(error)" + XCTAssertTrue(text.contains("1/2 launchctl transitions failed after 3 passes"), text) + XCTAssertTrue(text.contains("disable com.apple.bad: exit status 1: nope"), text) + } + XCTAssertEqual(host.disabled[udid], ["com.apple.ok"]) + } + + func testApplyDeltaEnablesAndDisables() throws { + let host = host(state: "Booted", disabled: ["com.apple.on"]) + try simctl(host).applyDelta( + set: "default", udid: udid, toDisable: ["com.apple.off"], toEnable: ["com.apple.on"], + disableAction: .overrideOnly, reporter: nil) + XCTAssertEqual(host.disabled[udid], ["com.apple.off"]) + } + + func testLiveStopBootsOutAndToleratesAnUnloadedService() throws { + let host = host(state: "Booted") + host.loaded[udid] = ["com.apple.running"] // com.apple.gone is not loaded: bootout exits 3 + try simctl(host).applyDelta( + set: "default", udid: udid, toDisable: ["com.apple.running", "com.apple.gone"], toEnable: [], + disableAction: .liveStop, reporter: nil) + XCTAssertEqual(host.disabled[udid], ["com.apple.running", "com.apple.gone"]) + XCTAssertEqual(host.loaded[udid], []) + let outs = transitions(host).filter { $0.hasPrefix("spawn:bootout ") } + XCTAssertEqual(outs.count, 2) + } + + func testApplyDeltaUsesAtMostEightWorkers() throws { + let host = host(state: "Booted") + let counter = Counter() + host.onCall = { _, args in + guard args.contains("launchctl") else { return } + counter.enter() + Thread.sleep(forTimeInterval: 0.01) + counter.leave() + } + let labels = (0..<60).map { "com.apple.l\($0)" } + try simctl(host).applyDelta( + set: "default", udid: udid, toDisable: labels, toEnable: [], + disableAction: .overrideOnly, reporter: nil) + XCTAssertEqual(host.disabled[udid], Set(labels)) + XCTAssertLessThanOrEqual(counter.peak, 8) + XCTAssertGreaterThan(counter.peak, 1, "the pool really runs transitions concurrently") + } + + func testApplyDeltaReportsProgress() throws { + let host = host(state: "Booted") + let lines = Log() + let labels = (0..<45).map { "com.apple.l\($0)" } + try simctl(host).applyDelta( + set: "default", udid: udid, toDisable: labels, toEnable: [], + disableAction: .overrideOnly, reporter: { lines.add($0) }) + XCTAssertEqual( + lines.all, + [" 20/45 services updated", " 40/45 services updated", " 45/45 services updated"]) + } + + // MARK: - deadline + + func testAnExpiredDeadlineRunsNothing() throws { + let host = host() + var ctl = simctl(host) + ctl.deadline = Date(timeIntervalSinceNow: -1) + XCTAssertThrowsError(try ctl.ensure(set: "default", udid: udid, desired: profileLabels)) { + XCTAssertTrue("\($0)".contains("context deadline exceeded"), "\($0)") + } + XCTAssertTrue(host.calls.isEmpty) + } + + func testDeadlineCapsEachCommandsTimeout() throws { + let host = host(state: "Booted") + var ctl = simctl(host) + ctl.deadline = Date(timeIntervalSinceNow: 50) + ctl.spawnTimeout = 120 + _ = try ctl.readDisabled(set: "default", udid: udid) + let timeout = try XCTUnwrap(host.calls.last?.timeout) + XCTAssertLessThanOrEqual(timeout, 50) + XCTAssertGreaterThan(timeout, 40) + } + + func testACommandKilledByTheDeadlineIsAnErrorNotAFailureToRetry() throws { + struct Slow: CommandRunning { + let clock: Clock + func run(_ e: Executable, _ a: [String], timeout: TimeInterval?) throws -> CommandResult { + clock.advance(100) // the deadline passes while the command runs + return CommandResult(status: -9, timedOut: true) + } + } + let clock = Clock() + var ctl = Simctl(runner: Slow(clock: clock)) + ctl.now = { clock.now } + ctl.deadline = clock.now.addingTimeInterval(10) + XCTAssertThrowsError(try ctl.shutdown(set: "default", udid: udid)) { + XCTAssertEqual("\($0)", "context deadline exceeded") + } + } + + func testRetrySleepsNeverOutlastTheDeadline() throws { + let host = host(state: "Booted") + host.queueSpawnResults( + udid: udid, [CommandResult(status: 124, stderr: Data("Domain is tearing down".utf8))]) + var ctl = simctl(host) + ctl.retryDelays = [100] + ctl.deadline = Date(timeIntervalSinceNow: 5) + let slept = Log() + ctl.sleep = { slept.add("\($0)") } + _ = try ctl.readDisabled(set: "default", udid: udid) + let seconds = try XCTUnwrap(slept.all.first.flatMap(Double.init)) + XCTAssertLessThanOrEqual(seconds, 5) + } + + func testWaitShutdownTimesOut() throws { + let host = host(state: "Booted") + host.stuckBooted = true + var ctl = simctl(host) + let clock = Clock() + ctl.now = { clock.now } + ctl.sleep = { clock.advance($0) } + XCTAssertThrowsError(try ctl.waitShutdown(set: "default", udid: udid, timeout: 30)) { + XCTAssertEqual("\($0)", "timed out waiting for \(udid) to shut down") + } + } + + // MARK: - enableSlimNoReboot + + /// Creates job plists for `labels` under a fake RuntimeRoot, and registers them + /// with the fake host. `mismatched` plists carry a different Label inside. + private func installPlists( + _ host: FakeHost, labels: [String], mismatched: Set = [], missing: Set = [] + ) throws { + let dir = root + "/runtime/System/Library/LaunchDaemons" + try FileManager.default.createDirectory(atPath: dir, withIntermediateDirectories: true) + host.runtimeRoots[ios] = root + "/runtime" + for label in labels where !missing.contains(label) { + let path = "\(dir)/\(label).plist" + FileManager.default.createFile(atPath: path, contents: Data()) + host.plistLabels[path] = mismatched.contains(label) ? "com.apple.other" : label + } + } + + func testNoRebootStopsLabelsInBatchesOfSixtyFour() throws { + let host = host(state: "Booted") + let labels = profileLabels.sorted() + XCTAssertGreaterThan(labels.count, 128) + host.loaded[udid] = Set(labels) + try installPlists(host, labels: labels) + + let lines = Log() + let changed = try simctl(host).enableSlimNoReboot( + set: "default", udid: udid, profile: Profile(), reporter: { lines.add($0) }) + XCTAssertTrue(changed) + let unloads = verbs(host).filter { $0.hasPrefix("spawn:unload -w") } + XCTAssertEqual(unloads.count, (labels.count + 63) / 64) + XCTAssertTrue( + verbs(host).filter { $0.hasPrefix("spawn:disable ") || $0.hasPrefix("spawn:bootout ") } + .isEmpty, + "everything was stopped in the batch") + XCTAssertEqual(host.disabled[udid]?.intersection(Catalog.managedSet), profileLabels) + XCTAssertEqual(host.loaded[udid]?.intersection(profileLabels), []) + XCTAssertTrue( + lines.all.contains(" \(labels.count)/\(labels.count) services stopped in one batch")) + } + + func testNoRebootNeverUnloadsAPlistWhoseLabelDiffers() throws { + let host = host(state: "Booted") + let labels = profileLabels.sorted() + host.loaded[udid] = Set(labels) + let impostor = labels[0] + let absent = labels[1] + try installPlists(host, labels: labels, mismatched: [impostor], missing: [absent]) + + try simctl(host).enableSlimNoReboot(set: "default", udid: udid, profile: Profile()) + let batchArgs = host.calls.filter { $0.arguments.contains("unload") }.flatMap(\.arguments) + XCTAssertFalse(batchArgs.contains { $0.hasSuffix("/\(impostor).plist") }) + XCTAssertFalse(batchArgs.contains { $0.hasSuffix("/\(absent).plist") }) + // They still end up stopped, through the per-label path. + XCTAssertTrue(host.disabled[udid]!.isSuperset(of: [impostor, absent])) + XCTAssertFalse(host.loaded[udid]!.contains(impostor)) + let perLabel = verbs(host).filter { $0.hasPrefix("spawn:bootout ") } + XCTAssertEqual( + Set(perLabel), ["spawn:bootout system/\(impostor)", "spawn:bootout system/\(absent)"]) + } + + func testNoRebootIsIdempotent() throws { + let host = host(state: "Booted", disabled: profileLabels) + host.loaded[udid] = [] + try installPlists(host, labels: profileLabels.sorted()) + let lines = Log() + let changed = try simctl(host).enableSlimNoReboot( + set: "default", udid: udid, profile: Profile(), reporter: { lines.add($0) }) + XCTAssertFalse(changed) + XCTAssertTrue(transitions(host).isEmpty) + XCTAssertTrue(lines.all.contains(" all \(profileLabels.count) services were already stopped")) + } + + func testNoRebootStopsADisabledButStillLoadedJob() throws { + // An earlier run disabled the job but failed to boot it out. + let label = profileLabels.sorted()[0] + let host = host(state: "Booted", disabled: profileLabels) + host.loaded[udid] = [label] + try installPlists(host, labels: []) + let changed = try simctl(host).enableSlimNoReboot( + set: "default", udid: udid, profile: Profile()) + XCTAssertFalse(changed, "nothing was newly disabled") + XCTAssertEqual(host.loaded[udid], []) + XCTAssertEqual( + transitions(host), ["spawn:disable system/\(label)", "spawn:bootout system/\(label)"]) + } + + func testNoRebootLeavesExtraDisabledLabelsAlone() throws { + var disabled = profileLabels + let extra = Catalog.categories[0].labels[0] + var profile = Profile() + profile.keep = [extra] + disabled = profile.desired().union([extra]) // slim, plus one the profile keeps enabled + let host = host(state: "Booted", disabled: disabled) + host.loaded[udid] = [] + let lines = Log() + try simctl(host).enableSlimNoReboot( + set: "default", udid: udid, profile: profile, reporter: { lines.add($0) }) + XCTAssertTrue(host.disabled[udid]!.contains(extra), "only `off` re-enables") + XCTAssertTrue(lines.all.contains { $0.hasPrefix("Leaving 1 services disabled beyond") }) + } + + func testNoRebootReportsOverridesThatDidNotTake() throws { + let host = host(state: "Booted") + let victim = profileLabels.sorted()[0] + host.loaded[udid] = [] + host.failTransition = { _, label in + label == victim ? CommandResult(status: 1, stderr: Data("no".utf8)) : nil + } + XCTAssertThrowsError( + try simctl(host).enableSlimNoReboot(set: "default", udid: udid, profile: Profile())) + } +} + +private final class Clock: @unchecked Sendable { + private let lock = NSLock() + private var t = Date(timeIntervalSince1970: 1_000_000) + var now: Date { + lock.lock() + defer { lock.unlock() } + return t + } + func advance(_ seconds: TimeInterval) { + lock.lock() + t = t.addingTimeInterval(seconds) + lock.unlock() + } +} diff --git a/swift/Tests/SimSlimKitTests/StatusVerifyMeasureTests.swift b/swift/Tests/SimSlimKitTests/StatusVerifyMeasureTests.swift new file mode 100644 index 0000000..e002858 --- /dev/null +++ b/swift/Tests/SimSlimKitTests/StatusVerifyMeasureTests.swift @@ -0,0 +1,263 @@ +// Copyright (c) 2026 Pavel Akhrameev (Swift port). MIT License; see LICENSE. + +import TestSupport +import XCTest + +@testable import SimSlimKit + +final class StatusTests: XCTestCase { + func testSupportsPersistentOverrides() { + let cases: [(String, String, Bool)] = [ + ("iOS", "18.5", true), ("iOS", "18.4", false), ("iOS", "18.3", false), + ("iOS", "19.0", true), ("iOS", "27.2", true), ("iOS", "17.9", false), + ("iOS", "18", false), ("iOS", "", false), ("iOS", "x.y", false), ("iOS", "18.5.1", true), + ("", "18.5", true), // empty platform defaults to iOS + ("tvOS", "18.5", true), ("tvOS", "18.4", false), + ("watchOS", "11.5", true), ("watchOS", "11.4", false), ("watchOS", "12.0", true), + ("watchOS", "18.5", true), + ("visionOS", "2.5", true), ("visionOS", "2.4", false), ("visionOS", "3.0", true), + ("macOS", "99.9", false), + ] + for (platform, version, expected) in cases { + let device = Device(udid: "U", platform: platform, osVersion: version) + XCTAssertEqual( + device.supportsPersistentOverrides, expected, "\(platform) \(version)") + } + } + + func testMinimumPersistentVersionMatchesTheGate() { + XCTAssertEqual(Device(udid: "U", platform: "watchOS").minimumPersistentVersion, "11.5") + XCTAssertEqual(Device(udid: "U", platform: "visionOS").minimumPersistentVersion, "2.5") + XCTAssertEqual(Device(udid: "U", platform: "iOS").minimumPersistentVersion, "18.5") + XCTAssertEqual(Device(udid: "U", platform: "tvOS").minimumPersistentVersion, "18.5") + } + + func testVerdict() { + func verdict(_ disabled: Int, _ total: Int) -> String { + Status(managedDisabled: disabled, managedTotal: total, booted: true, persistent: true).verdict + } + XCTAssertEqual(verdict(0, 173), "stock") + XCTAssertEqual(verdict(1, 173), "partially slim") + XCTAssertEqual(verdict(172, 173), "partially slim") + XCTAssertEqual(verdict(173, 173), "slim") + } + + func testInitialStatusUsesThePlatformSpecificTotal() { + let ios = Status.initial( + for: Device(udid: "U", state: "Booted", platform: "iOS", osVersion: "27.2")) + let watch = Status.initial(for: Device(udid: "U", platform: "watchOS", osVersion: "11.5")) + XCTAssertEqual(ios.managedTotal, 173) + XCTAssertEqual(watch.managedTotal, 172, "homed stays enabled on watchOS") + XCTAssertTrue(ios.booted) + XCTAssertFalse(watch.booted) + XCTAssertTrue(ios.persistent) + } + + func testReadStatusCountsOnlyManagedLabels() throws { + let host = FakeHost(devices: [.init(udid: "U", name: "n", state: "Booted")]) + host.disabled["U"] = [ + "com.apple.apsd", // managed + "com.apple.searchd", // managed + "com.apple.sharingd", // managed (always-enabled): a legacy disable counts as managed + "com.apple.nanoregistryd", // forbidden and unmanaged + "com.apple.not-ours", + ] + let (status, disabled) = try Simctl(runner: host).readStatus(udid: "U") + XCTAssertEqual(status.managedDisabled, 2, "only labels in the full slim set count") + XCTAssertEqual(disabled.count, 5, "the raw disabled set is returned unfiltered") + } + + func testReadStatusRequiresABootedDevice() { + let host = FakeHost(devices: [.init(udid: "U", name: "n", state: "Shutdown")]) + XCTAssertThrowsError(try Simctl(runner: host).readStatus(udid: "U")) { error in + XCTAssertEqual( + (error as? SimSlimError)?.message, + "simulator must be booted to read its state (it is Shutdown)") + } + XCTAssertFalse( + host.calls.contains { $0.arguments.contains("spawn") }, "no spawn into a shutdown device") + } + + func testDroppedCategoriesAreGroupedInCategoryOrder() { + let dropped = Catalog.droppedCategories(disabled: [ + "com.apple.searchd", "com.apple.PosterBoard", "com.apple.chronod", "com.apple.not-ours", + ]) + XCTAssertEqual(dropped.map(\.id), ["widgets", "search"], "category order, not label order") + XCTAssertEqual(dropped[0].labels, ["com.apple.PosterBoard", "com.apple.chronod"]) + XCTAssertEqual(Catalog.droppedCategories(disabled: []), []) + XCTAssertEqual(Catalog.droppedCategories(disabled: ["com.apple.not-ours"]), []) + } +} + +final class VerifyTests: XCTestCase { + func testCompareDisabled() { + let managed: Set = ["a", "b", "c", "d"] + let result = compareDisabled( + disabled: ["a", "d", "zzz"], desired: ["a", "b"], managed: managed) + XCTAssertFalse(result.ok) + XCTAssertEqual(result.missing, ["b"]) + XCTAssertEqual(result.extra, ["d"], "unmanaged 'zzz' never counts as drift") + + let match = compareDisabled( + disabled: ["a", "b", "zzz"], desired: ["a", "b"], managed: managed) + XCTAssertTrue(match.ok) + XCTAssertTrue(match.missing.isEmpty && match.extra.isEmpty) + } + + func testVerifyAgainstTheFullProfile() throws { + let host = FakeHost(devices: [.init(udid: "U", name: "n", state: "Booted")]) + host.disabled["U"] = Profile().desired() + let simctl = Simctl(runner: host) + let ok = try simctl.verifyProfile(udid: "U", profile: Profile()) + XCTAssertTrue(ok.ok) + XCTAssertEqual(ok.udid, "U") + + host.disabled["U"] = Profile().desired().subtracting(["com.apple.apsd"]) + let drift = try simctl.verifyProfile(udid: "U", profile: Profile()) + XCTAssertFalse(drift.ok) + XCTAssertEqual(drift.missing, ["com.apple.apsd"]) + } + + func testVerifyUsesThePlatformSpecificDesiredSet() throws { + // On watchOS homed must stay enabled, so a device that is slim except for homed matches. + let watch = "com.apple.CoreSimulator.SimRuntime.watchOS-11-5" + let host = FakeHost(devices: [.init(udid: "W", name: "w", runtime: watch, state: "Booted")]) + host.disabled["W"] = Profile().desired().subtracting(["com.apple.homed"]) + XCTAssertTrue(try Simctl(runner: host).verifyProfile(udid: "W", profile: Profile()).ok) + } + + func testVerifyRequiresBooted() { + let host = FakeHost(devices: [.init(udid: "U", name: "n")]) + XCTAssertThrowsError(try Simctl(runner: host).verifyProfile(udid: "U", profile: Profile())) + } + + func testVerifyResultOmitsEmptyLists() throws { + let data = try JSONEncoder().encode(VerifyResult(udid: "U", ok: true, missing: [], extra: [])) + let object = try XCTUnwrap(JSONSerialization.jsonObject(with: data) as? [String: Any]) + XCTAssertEqual(Set(object.keys), ["udid", "ok"]) + } +} + +final class MeasureTests: XCTestCase { + func testParseBytes() { + let cases: [(String, Int64)] = [ + ("45M", 45 * 1_048_576), ("45M+", 45 * 1_048_576), ("45M-", 45 * 1_048_576), + ("1.5G", 1_610_612_736), ("900K", 900 * 1024), ("12B", 12), ("12", 12), ("0", 0), + ("", 0), ("+", 0), ("abc", 0), ("1.5.2M", 0), ("1e30", 0), ("1e30G", 0), ("1e400", 0), + ] + for (text, expected) in cases { + XCTAssertEqual(Simctl.parseBytes(text), expected, "parseBytes(\"\(text)\")") + } + } + + func testParseTopMemory() { + let output = """ + Processes: 400 total, 3 running + Load Avg: 1.0, 1.0, 1.0 + PID MEM + 101 45M + 102 1.5G+ + 103 900K- + 104 12B + abc 5M + 105 notasize + 7 + """ + XCTAssertEqual( + Simctl.parseTopMemory(output), + [101: 45 * 1_048_576, 102: 1_610_612_736, 103: 900 * 1024, 104: 12] as [Int: Int64]) + } + + func testParsePSKeepsParentLinksCPUAndBasename() { + let output = """ + PID PPID %CPU COMM + 1 0 0.0 /sbin/launchd + 200 1 1.5 /Library/Developer/CoreSimulator/Volumes/iOS 27.2/launchd_sim + 201 200 12.5 /Applications/Xcode.app/Contents/Developer/SpringBoard + 202 200 0.0 backboardd + garbage line + """ + let snapshot = Simctl.parsePS(output) + XCTAssertEqual(snapshot.children[200], [201, 202]) + XCTAssertEqual(snapshot.cpu[201], 12.5) + XCTAssertEqual(snapshot.comm[200], "launchd_sim", "spaces in the path are tolerated") + XCTAssertEqual(snapshot.comm[201], "SpringBoard") + XCTAssertEqual(snapshot.comm[202], "backboardd") + XCTAssertNil(snapshot.comm[0]) + } + + func testTreePIDsCoversTheWholeTreeOnlyAndSurvivesCycles() { + let children = [1: [2, 3], 2: [4], 3: [], 9: [10], 4: [2]] // 4 -> 2 is a cycle + XCTAssertEqual(Simctl.treePIDs(root: 1, children: children), [1, 2, 3, 4]) + XCTAssertEqual(Simctl.treePIDs(root: 9, children: children), [9, 10]) + XCTAssertEqual(Simctl.treePIDs(root: 77, children: children), [77]) + } + + private func host() -> FakeHost { + let host = FakeHost() + host.launchdPIDs = ["AAAA": 200, "BBBB": 300] + host.psOutput = """ + PID PPID %CPU COMM + 200 1 1.0 /x/launchd_sim + 201 200 2.0 /x/SpringBoard + 300 1 4.0 /x/launchd_sim + 301 300 0.5 /x/backboardd + 999 1 50.0 /x/unrelated + """ + host.topOutput = """ + PID MEM + 200 10M + 201 20M + 300 1G + 301 5M + 999 100M + """ + return host + } + + func testMeasureSumsOnlyThatSimulatorsTree() throws { + let measurement = try Simctl(runner: host()).measure(udid: "AAAA") + XCTAssertEqual(measurement.processes, 2) + XCTAssertEqual(measurement.bytes, 30 * 1_048_576) + XCTAssertEqual(measurement.cpu, 3.0, accuracy: 0.0001) + } + + func testMeasureManyTakesOneSnapshotAndReportsPerDeviceErrors() { + let fake = host() + let (measurements, errors) = Simctl(runner: fake).measureMany(udids: ["AAAA", "BBBB", "CCCC"]) + XCTAssertEqual(measurements["AAAA"]?.bytes, 30 * 1_048_576) + XCTAssertEqual(measurements["BBBB"]?.bytes, 1_073_741_824 + 5 * 1_048_576) + XCTAssertNil(measurements["CCCC"]) + XCTAssertEqual(errors["CCCC"], "simulator CCCC does not appear to be booted") + XCTAssertEqual(fake.calls.filter { $0.executable == .ps }.count, 1, "one ps for every device") + XCTAssertEqual(fake.calls.filter { $0.executable == .top }.count, 1, "one top for every device") + } + + func testMeasureManyWithNothingBootedSpawnsNoPsOrTop() { + let fake = FakeHost() + let (measurements, errors) = Simctl(runner: fake).measureMany(udids: ["X"]) + XCTAssertTrue(measurements.isEmpty) + XCTAssertEqual(errors.count, 1) + XCTAssertFalse(fake.calls.contains { $0.executable == .ps || $0.executable == .top }) + } + + func testMeasureOfANotBootedSimulatorFails() { + XCTAssertThrowsError(try Simctl(runner: FakeHost()).measure(udid: "X")) { error in + XCTAssertEqual( + (error as? SimSlimError)?.message, "simulator X does not appear to be booted") + } + } + + func testPgrepMatchesTheBootstrapPath() throws { + let fake = host() + _ = try Simctl(runner: fake).measure(udid: "AAAA") + let pgrep = try XCTUnwrap(fake.calls.first { $0.executable == .pgrep }) + XCTAssertEqual(pgrep.arguments, ["-f", "AAAA/data/var/run/launchd_bootstrap"]) + } + + func testMemoryMeasurementJSONKeys() throws { + let data = try JSONEncoder().encode(MemoryMeasurement(processes: 2, bytes: 3, cpu: 1.5)) + let object = try XCTUnwrap(JSONSerialization.jsonObject(with: data) as? [String: Any]) + XCTAssertEqual(Set(object.keys), ["processes", "bytes", "cpu"]) + } +} diff --git a/swift/Tests/SimSlimKitTests/SubprocessRunnerTests.swift b/swift/Tests/SimSlimKitTests/SubprocessRunnerTests.swift new file mode 100644 index 0000000..d3f6978 --- /dev/null +++ b/swift/Tests/SimSlimKitTests/SubprocessRunnerTests.swift @@ -0,0 +1,78 @@ +// Copyright (c) 2026 Pavel Akhrameev (Swift port). MIT License; see LICENSE. + +import XCTest + +@testable import SimSlimKit + +/// Behavior of the real process runner, using harmless system tools mapped over +/// the closed Executable list (only possible from tests, via `resolve`). +final class SubprocessRunnerTests: XCTestCase { + private func runner( + _ path: String, waitDelay: TimeInterval = 5 + ) -> SystemCommandRunner { + SystemCommandRunner(waitDelay: waitDelay, resolve: { _ in path }) + } + + func testCapturesStdoutStderrAndStatusSeparately() throws { + let result = try runner("/bin/sh").run( + .xcrun, ["-c", "echo out; echo err 1>&2; exit 3"]) + XCTAssertEqual(result.status, 3) + XCTAssertEqual(result.stdoutText, "out\n") + XCTAssertEqual(result.stderrText, "err\n") + XCTAssertEqual(result.combinedText, "out\nerr") + XCTAssertFalse(result.timedOut) + XCTAssertFalse(result.succeeded) + } + + func testLargeOutputDoesNotDeadlock() throws { + // Far more than a pipe buffer on both streams. + let script = + "head -c 3000000 /dev/zero | tr '\\0' a; head -c 3000000 /dev/zero | tr '\\0' b 1>&2" + let result = try runner("/bin/sh").run(.xcrun, ["-c", script], timeout: 30) + XCTAssertEqual(result.stdout.count, 3_000_000) + XCTAssertEqual(result.stderr.count, 3_000_000) + XCTAssertTrue(result.succeeded) + } + + func testTimeoutKillsTheProcess() throws { + let start = Date() + let result = try runner("/bin/sleep").run(.xcrun, ["30"], timeout: 0.3) + XCTAssertTrue(result.timedOut) + XCTAssertFalse(result.succeeded) + XCTAssertLessThan(Date().timeIntervalSince(start), 5, "the runner waited for the sleep") + XCTAssertLessThan(result.status, 0, "a killed process reports the negated signal") + } + + func testFastProcessIsNotReportedAsTimedOut() throws { + let result = try runner("/bin/sh").run(.xcrun, ["-c", "exit 0"], timeout: 30) + XCTAssertTrue(result.succeeded) + XCTAssertFalse(result.timedOut) + } + + func testPipeHeldOpenByGrandchildIsAbandonedAfterWaitDelay() throws { + // The shell exits at once but its background child keeps stdout open for 5s, + // like the simctl child a killed xcrun leaves behind. Without the wait delay + // this call would block for those 5s. + let start = Date() + let result = try runner("/bin/sh", waitDelay: 0.4).run( + .xcrun, ["-c", "sleep 5 & echo out"], timeout: 30) + XCTAssertEqual(result.stdoutText, "out\n") + XCTAssertTrue(result.succeeded) + XCTAssertLessThan(Date().timeIntervalSince(start), 3) + } + + func testMissingExecutableThrowsAReadableError() { + XCTAssertThrowsError(try runner("/nonexistent/simslim-tool").run(.xcrun, [])) { error in + XCTAssertTrue( + (error as? SimSlimError)?.message.hasPrefix("cannot run /nonexistent/simslim-tool") == true, + "\(error)") + } + } + + func testStdinIsClosed() throws { + // A child that reads stdin must see EOF immediately, not hang on our terminal. + let result = try runner("/bin/cat").run(.xcrun, [], timeout: 10) + XCTAssertTrue(result.succeeded) + XCTAssertTrue(result.stdout.isEmpty) + } +} diff --git a/swift/Tests/SimSlimKitTests/SubprocessTests.swift b/swift/Tests/SimSlimKitTests/SubprocessTests.swift new file mode 100644 index 0000000..a04e81c --- /dev/null +++ b/swift/Tests/SimSlimKitTests/SubprocessTests.swift @@ -0,0 +1,33 @@ +// Copyright (c) 2026 Pavel Akhrameev (Swift port). MIT License; see LICENSE. + +import XCTest + +@testable import SimSlimKit + +final class SubprocessTests: XCTestCase { + func testEveryExecutablePathIsAbsolute() { + for executable in Executable.allCases { + XCTAssertTrue(executable.rawValue.hasPrefix("/"), "\(executable) must be an absolute path") + } + } + + func testEveryExecutableExistsOnThisMac() { + for executable in Executable.allCases { + XCTAssertTrue( + FileManager.default.isExecutableFile(atPath: executable.rawValue), + "\(executable.rawValue) is missing or not executable") + } + } + + func testSystemRunnerCapturesOutputAndStatus() throws { + // plutil -help prints usage to stdout and exits 0. + let ok = try SystemCommandRunner().run(.plutil, ["-help"]) + XCTAssertEqual(ok.status, 0) + XCTAssertFalse(ok.stdoutText.isEmpty) + + // A missing file is a non-zero exit with a message, not a thrown error. + let missing = try SystemCommandRunner().run(.plutil, ["-lint", "/nonexistent/simslim-test"]) + XCTAssertNotEqual(missing.status, 0) + XCTAssertFalse((missing.stdoutText + missing.stderrText).isEmpty) + } +} diff --git a/swift/Tests/SimSlimKitTests/WatchTests.swift b/swift/Tests/SimSlimKitTests/WatchTests.swift new file mode 100644 index 0000000..4b91ac2 --- /dev/null +++ b/swift/Tests/SimSlimKitTests/WatchTests.swift @@ -0,0 +1,740 @@ +// Copyright (c) 2026 Pavel Akhrameev (Swift port). MIT License; see LICENSE. + +import TestSupport +import XCTest + +@testable import SimSlimKit + +private final class Events: @unchecked Sendable { + private let lock = NSLock() + private var items: [WatchEvent] = [] + private var texts: [String] = [] + func add(_ event: WatchEvent) { + lock.lock() + items.append(event) + lock.unlock() + } + func addText(_ text: String) { + lock.lock() + texts.append(text) + lock.unlock() + } + var all: [WatchEvent] { + lock.lock() + defer { lock.unlock() } + return items + } + var kinds: [String] { all.map(\.event) } + var lines: [String] { + lock.lock() + defer { lock.unlock() } + return texts + } +} + +private final class Flag: @unchecked Sendable { + private let lock = NSLock() + private var value = false + var isSet: Bool { + lock.lock() + defer { lock.unlock() } + return value + } + func set() { + lock.lock() + value = true + lock.unlock() + } +} + +private final class Calls: @unchecked Sendable { + private let lock = NSLock() + private var items: [String] = [] + func add(_ item: String) { + lock.lock() + items.append(item) + lock.unlock() + } + var all: [String] { + lock.lock() + defer { lock.unlock() } + return items + } +} + +final class WatchTests: XCTestCase { + private let ios = "com.apple.CoreSimulator.SimRuntime.iOS-27-2" + private let old = "com.apple.CoreSimulator.SimRuntime.iOS-17-0" + private var root = "" + + override func setUpWithError() throws { + root = NSTemporaryDirectory() + "simslim-watch-\(UUID().uuidString)" + try FileManager.default.createDirectory(atPath: root, withIntermediateDirectories: true) + } + + override func tearDown() { + try? FileManager.default.removeItem(atPath: root) + } + + private func udid(_ n: Int) -> String { String(format: "AAAAAAAA-0000-0000-0000-%012d", n) } + + private func waitFor(_ what: String, timeout: TimeInterval = 5, _ condition: () -> Bool) { + let limit = Date().addingTimeInterval(timeout) + while !condition() && Date() < limit { Thread.sleep(forTimeInterval: 0.01) } + XCTAssertTrue(condition(), "timed out waiting for \(what)") + } + + private func makeWatcher( + _ host: FakeHost, events: Events, slim: Watcher.Slimmer? = nil, + preslim: Watcher.Preslimmer? = nil + ) -> Watcher { + var ctl = Simctl(runner: host) + ctl.retryDelays = [0] + ctl.sleep = { _ in } + ctl.storeRoot = root + "/store" + let watcher = Watcher( + simctl: ctl, profile: Profile(), home: root + "/home", + report: { events.addText($0) }, events: { events.add($0) }) + if let slim { watcher.slim = slim } + watcher.preslim = preslim + return watcher + } + + private func booted(_ n: Int, runtime: String? = nil) -> FakeHost.FakeDevice { + .init(udid: udid(n), name: "d\(n)", runtime: runtime ?? ios, state: "Booted") + } + + private func shutdown(_ n: Int, runtime: String? = nil) -> FakeHost.FakeDevice { + .init(udid: udid(n), name: "d\(n)", runtime: runtime ?? ios, state: "Shutdown") + } + + // MARK: - after-boot passes + + func testABootedDeviceIsSlimmedOncePerBoot() { + let host = FakeHost(devices: [booted(1)]) + let events = Events() + let calls = Calls() + let watcher = makeWatcher( + host, events: events, + slim: { _, set, id, _, _ in + calls.add("\(set) \(id)") + return true + }) + watcher.scan() + watcher.waitForWork() + watcher.scan() + watcher.waitForWork() + XCTAssertEqual(calls.all, ["default \(udid(1))"], "the second scan leaves it alone") + XCTAssertEqual(events.kinds, [WatchEventKind.slimming, WatchEventKind.slimmed]) + XCTAssertEqual(events.all[0], WatchEvent(event: "slimming", udid: udid(1), set: "default")) + } + + func testAFailedPassIsRetriedByTheNextScan() { + let host = FakeHost(devices: [booted(1)]) + let events = Events() + let attempts = Calls() + let watcher = makeWatcher( + host, events: events, + slim: { _, _, _, _, _ in + attempts.add("x") + if attempts.all.count == 1 { throw SimSlimError("transient launchctl failure") } + return true + }) + watcher.scan() + watcher.waitForWork() + XCTAssertEqual(events.kinds, ["slimming", "failed"]) + XCTAssertEqual(events.all[1].error, "transient launchctl failure") + watcher.scan() + watcher.waitForWork() + XCTAssertEqual(events.kinds, ["slimming", "failed", "slimming", "slimmed"]) + } + + func testAPassIsCancelledWhenItsDeviceShutsDownAndNeverReportsSlimmed() { + let host = FakeHost(devices: [booted(1)]) + let events = Events() + let started = Flag() + let watcher = makeWatcher( + host, events: events, + slim: { ctl, _, _, _, _ in + started.set() + while ctl.cancelled?() != true { Thread.sleep(forTimeInterval: 0.005) } + throw SimSlimError("context canceled") + }) + watcher.scan() + waitFor("pass to start") { started.isSet } + host.devices[0].state = "Shutdown" + watcher.scan() + watcher.waitForWork() + XCTAssertEqual(events.kinds, ["slimming", "stopped"]) + XCTAssertFalse(events.kinds.contains("slimmed")) + XCTAssertTrue(events.lines.contains("watch: \(udid(1)) shut down; stopped its slim")) + } + + func testTheNextBootGetsAFreshPass() { + let host = FakeHost(devices: [booted(1)]) + let events = Events() + let watcher = makeWatcher(host, events: events, slim: { _, _, _, _, _ in true }) + watcher.scan() + watcher.waitForWork() + host.devices[0].state = "Shutdown" + watcher.scan() + host.devices[0].state = "Booted" + watcher.scan() + watcher.waitForWork() + XCTAssertEqual(events.kinds, ["slimming", "slimmed", "slimming", "slimmed"]) + } + + func testADeletedDeviceCancelsItsPassAndIsForgotten() { + let host = FakeHost(devices: [booted(1)]) + let events = Events() + let started = Flag() + let watcher = makeWatcher( + host, events: events, + slim: { ctl, _, _, _, _ in + started.set() + while ctl.cancelled?() != true { Thread.sleep(forTimeInterval: 0.005) } + throw SimSlimError("context canceled") + }) + watcher.scan() + waitFor("pass to start") { started.isSet } + host.devices = [] + watcher.scan() + watcher.waitForWork() + XCTAssertEqual(events.kinds, ["slimming", "stopped"]) + } + + func testEachDeviceSlimsInItsOwnThreadSoOneSlowPassDoesNotBlockTheOthers() { + let host = FakeHost(devices: [booted(1), booted(2)]) + let events = Events() + let release = Flag() + let watcher = makeWatcher( + host, events: events, + slim: { _, _, id, _, _ in + if id == "AAAAAAAA-0000-0000-0000-000000000001" { + while !release.isSet { Thread.sleep(forTimeInterval: 0.005) } + } + return true + }) + watcher.scan() + waitFor("the fast device to finish") { + events.all.contains { $0.event == "slimmed" && $0.udid == self.udid(2) } + } + XCTAssertFalse(events.all.contains { $0.event == "slimmed" && $0.udid == udid(1) }) + release.set() + watcher.waitForWork() + XCTAssertEqual(events.all.filter { $0.event == "slimmed" }.count, 2) + } + + func testAFailedListingIsReportedAndTheLoopCarriesOn() { + let host = FakeHost(devices: [booted(1)]) + host.listFailure = "CoreSimulatorService is not running" + let events = Events() + let watcher = makeWatcher(host, events: events) + watcher.scan() + XCTAssertTrue(events.lines.contains { $0.hasPrefix("watch: list devices: ") }) + XCTAssertEqual(events.kinds, []) + } + + func testProgressLinesCarryTheUDID() { + let host = FakeHost(devices: [booted(1)]) + let events = Events() + let watcher = makeWatcher( + host, events: events, + slim: { _, _, _, _, reporter in + reporter?("Stopping 173 background services") + return true + }) + watcher.scan() + watcher.waitForWork() + XCTAssertTrue( + events.lines.contains("watch: \(udid(1)): Stopping 173 background services")) + } + + // MARK: - slimming before boot + + func testAShutdownDeviceIsSeededOncePerShutdown() { + let host = FakeHost(devices: [shutdown(1)]) + let events = Events() + let seeds = Calls() + let watcher = makeWatcher( + host, events: events, + preslim: { d, _ in + seeds.add(d.udid) + return 173 + }) + watcher.scan() + watcher.scan() + XCTAssertEqual(seeds.all, [udid(1)]) + XCTAssertEqual( + events.all, + [WatchEvent(event: "slimmed_before_boot", udid: udid(1), set: "default", services: 173)]) + // It boots (a booted device may rewrite its store), then shuts down again. + host.devices[0].state = "Booted" + watcher.scan() + watcher.waitForWork() + host.devices[0].state = "Shutdown" + watcher.scan() + XCTAssertEqual(seeds.all, [udid(1), udid(1)]) + } + + func testASeedThatFailsIsRetriedOnTheNextScan() { + let host = FakeHost(devices: [shutdown(1)]) + let events = Events() + let seeds = Calls() + let watcher = makeWatcher( + host, events: events, + preslim: { _, _ in + seeds.add("x") + if seeds.all.count == 1 { throw SimSlimError("disk full") } + return 5 + }) + watcher.scan() + XCTAssertTrue(events.lines.contains("watch: \(udid(1)): slim before boot: disk full")) + watcher.scan() + XCTAssertEqual(events.kinds, ["slimmed_before_boot"]) + } + + func testASeedWithNothingToWriteIsSilent() { + let host = FakeHost(devices: [shutdown(1)]) + let events = Events() + let watcher = makeWatcher(host, events: events, preslim: { _, _ in 0 }) + watcher.scan() + XCTAssertEqual(events.kinds, []) + XCTAssertEqual(events.lines, []) + } + + func testASeedThatLandsAfterTheBootBeganIsNotAnnounced() throws { + let dir = root + "/devices/\(udid(1))" + try FileManager.default.createDirectory( + atPath: dir + "/data", withIntermediateDirectories: true) + try devicePlist(udid: udid(1), runtime: ios, state: 3).write( + toFile: dir + "/device.plist", atomically: true, encoding: .utf8) + let events = Events() + let watcher = makeWatcher(FakeHost(), events: events, preslim: { _, _ in 12 }) + var device = Device( + udid: udid(1), state: "Shutdown", platform: "iOS", osVersion: "27.2", set: "default", + dataPath: dir + "/data", runtimeID: ios) + watcher.seed(device) + XCTAssertEqual(events.kinds, [], "launchd_sim already started") + XCTAssertTrue( + events.lines.contains { $0.contains("booted before its slim (12 services) landed") }) + + // The plist still says shut down: announced. + try devicePlist(udid: udid(1), runtime: ios, state: 1).write( + toFile: dir + "/device.plist", atomically: true, encoding: .utf8) + device.udid = udid(2) + watcher.seed(device) + XCTAssertEqual(events.kinds, ["slimmed_before_boot"]) + } + + func testPreslimWritesOnlyMissingDisablesAndLeavesTheRestAlone() throws { + let store = DisabledStore(root: root + "/store") + let id = udid(1) + try store.write( + udid: id, toDisable: ["com.apple.unmanaged", "com.apple.extra.disabled"], toEnable: []) + let someManaged = Profile().desired().sorted()[0] + try store.write(udid: id, toDisable: [someManaged], toEnable: []) + let device = Device( + udid: id, state: "Shutdown", platform: "iOS", osVersion: "27.2", set: "default") + let count = try preslimDevice(device, profile: Profile(), storeRoot: root + "/store") + XCTAssertEqual(count, Profile().desired().count - 1) + let disabled = try store.readDisabled(udid: id) + XCTAssertTrue(disabled.isSuperset(of: Profile().desired())) + XCTAssertTrue(disabled.contains("com.apple.unmanaged"), "unmanaged entries are untouched") + XCTAssertEqual(try preslimDevice(device, profile: Profile(), storeRoot: root + "/store"), 0) + } + + func testPreslimNeverEnablesAnything() throws { + let store = DisabledStore(root: root + "/store") + let id = udid(1) + // Disabled beyond the profile: stays disabled. + var profile = Profile() + let kept = Catalog.categories[0].labels[0] + profile.keep = [kept] + try store.write(udid: id, toDisable: [kept], toEnable: []) + let device = Device( + udid: id, state: "Shutdown", platform: "iOS", osVersion: "27.2", set: "default") + _ = try preslimDevice(device, profile: profile, storeRoot: root + "/store") + XCTAssertTrue(try store.readDisabled(udid: id).contains(kept)) + } + + func testPreslimSkipsBootedDevicesAndRuntimesWithoutPersistence() throws { + let booted = Device( + udid: udid(1), state: "Booted", platform: "iOS", osVersion: "27.2", set: "default") + let oldRuntime = Device( + udid: udid(2), state: "Shutdown", platform: "iOS", osVersion: "17.0", set: "default") + XCTAssertEqual(try preslimDevice(booted, profile: Profile(), storeRoot: root + "/store"), 0) + XCTAssertEqual(try preslimDevice(oldRuntime, profile: Profile(), storeRoot: root + "/store"), 0) + XCTAssertFalse(FileManager.default.fileExists(atPath: root + "/store")) + } + + func testPreslimKeepsHomedEnabledOnWatchOS() throws { + let watch = Device( + udid: udid(1), state: "Shutdown", platform: "watchOS", osVersion: "11.5", set: "default") + _ = try preslimDevice(watch, profile: Profile(), storeRoot: root + "/store") + let disabled = try DisabledStore(root: root + "/store").readDisabled(udid: udid(1)) + XCTAssertFalse(disabled.contains("com.apple.homed")) + } + + func testAReappearingUDIDIsSeededAgainBecauseDeletedDevicesAreForgotten() { + let host = FakeHost(devices: [shutdown(1)]) + let seeds = Calls() + let watcher = makeWatcher( + host, events: Events(), + preslim: { d, _ in + seeds.add(d.udid) + return 1 + }) + watcher.scan() + host.devices = [] + watcher.scan() // pruned + host.devices = [shutdown(1)] + watcher.scan() + XCTAssertEqual(seeds.all, [udid(1), udid(1)]) + } + + func testABootedOrBootingDeviceIsNeverSeeded() { + let seeds = Calls() + let watcher = makeWatcher( + FakeHost(), events: Events(), + preslim: { d, _ in + seeds.add(d.udid) + return 1 + }) + for state in ["Booted", "Booting", "Shutting Down"] { + watcher.seed( + Device(udid: udid(1), state: state, platform: "iOS", osVersion: "27.2", set: "default")) + } + XCTAssertEqual(seeds.all, []) + } + + func testACancelledOperationRunsNoCommand() { + let host = FakeHost(devices: [booted(1)]) + var ctl = Simctl(runner: host) + ctl.cancelled = { true } + XCTAssertThrowsError(try ctl.readDisabled(set: "default", udid: udid(1))) { + XCTAssertEqual("\($0)", "launchctl print-disabled: context canceled") + } + XCTAssertTrue(host.calls.isEmpty) + // A slim stops at its next step, saying why. + ctl.cancelled = { true } + XCTAssertThrowsError( + try ctl.applyDelta( + set: "default", udid: udid(1), toDisable: ["com.apple.x"], toEnable: [], + disableAction: .overrideOnly, reporter: nil) + ) { + XCTAssertTrue("\($0)".hasSuffix("context canceled"), "\($0)") + } + XCTAssertTrue(host.calls.isEmpty) + } + + // MARK: - device.plist + + private func devicePlist(udid: String, runtime: String, state: Int, stateAsString: Bool = false) + -> String + { + let value = stateAsString ? "\(state)" : "\(state)" + return """ + + + UDID\(udid) + runtime\(runtime) + state\(value) + nameiPhone + + """ + } + + func testReadDevicePlist() throws { + let dir = root + "/" + udid(1) + try FileManager.default.createDirectory(atPath: dir, withIntermediateDirectories: true) + for (state, asString, expected) in [ + (1, false, "Shutdown"), (3, false, "Booted"), (1, true, "Shutdown"), (2, true, "Booted"), + ] { + try devicePlist(udid: udid(1), runtime: ios, state: state, stateAsString: asString) + .write(toFile: dir + "/device.plist", atomically: true, encoding: .utf8) + let device = try readDevicePlist(DeviceDir(path: dir, set: "testing")) + XCTAssertEqual(device.state, expected) + XCTAssertEqual(device.udid, udid(1)) + XCTAssertEqual(device.platform, "iOS") + XCTAssertEqual(device.osVersion, "27.2") + XCTAssertEqual(device.set, "testing") + XCTAssertEqual(device.dataPath, dir + "/data") + XCTAssertEqual(device.runtimeID, ios) + } + } + + func testReadDevicePlistRejectsAUDIDThatIsNotItsDirectory() throws { + // The UDID names the disabled-store path, so a traversal string or another + // device's UDID in a planted device.plist must never be accepted. + let dir = root + "/" + udid(1) + try FileManager.default.createDirectory(atPath: dir, withIntermediateDirectories: true) + for bad in ["x/../../../tmp/evil", "../" + udid(1), udid(2), "not-a-udid"] { + try devicePlist(udid: bad, runtime: ios, state: 1) + .write(toFile: dir + "/device.plist", atomically: true, encoding: .utf8) + XCTAssertThrowsError(try readDevicePlist(DeviceDir(path: dir, set: "default")), bad) + } + XCTAssertFalse(isUDID("x/../../../tmp/evil")) + XCTAssertTrue(isUDID(udid(1))) + } + + func testDisabledStoreKeepsAUDIDInsideItsRoot() { + let store = DisabledStore(root: "/private/var/tmp") + XCTAssertEqual( + store.directory(udid: "a/../../b"), + "/private/var/tmp/com.apple.CoreSimulator.SimDevice.a_.._.._b") + } + + func testReadDevicePlistRejectsWhatSimslimDoesNotSlim() throws { + let dir = root + "/" + udid(1) + try FileManager.default.createDirectory(atPath: dir, withIntermediateDirectories: true) + let cases = [ + devicePlist( + udid: udid(1), runtime: "com.apple.CoreSimulator.SimRuntime.macOS-15-0", state: 1), + devicePlist(udid: "", runtime: ios, state: 1), + "not a plist", + ] + for text in cases { + try text.write(toFile: dir + "/device.plist", atomically: true, encoding: .utf8) + XCTAssertThrowsError(try readDevicePlist(DeviceDir(path: dir, set: "default")), text) + } + XCTAssertThrowsError(try readDevicePlist(DeviceDir(path: root + "/nowhere", set: "default"))) + } + + func testSeedNewWaitsForDevicePlistThenSeeds() throws { + let dir = root + "/devices/\(udid(1))" + try FileManager.default.createDirectory(atPath: dir, withIntermediateDirectories: true) + let events = Events() + let seeds = Calls() + let watcher = makeWatcher( + FakeHost(), events: events, + preslim: { d, _ in + seeds.add("\(d.udid) \(d.state) \(d.set)") + return 1 + }) + let plist = devicePlist(udid: udid(1), runtime: ios, state: 1) + DispatchQueue.global().asyncAfter(deadline: .now() + 0.15) { + try? plist.write(toFile: dir + "/device.plist", atomically: true, encoding: .utf8) + } + watcher.seedNew(DeviceDir(path: dir, set: "default")) + XCTAssertEqual(seeds.all, ["\(udid(1)) Shutdown default"]) + } + + func testSeedNewGivesUpOnADirectoryThatIsNotADevice() throws { + let dir = root + "/devices/not-a-device" + try FileManager.default.createDirectory(atPath: dir, withIntermediateDirectories: true) + let seeds = Calls() + let watcher = makeWatcher( + FakeHost(), events: Events(), + preslim: { d, _ in + seeds.add(d.udid) + return 1 + }) + let started = Date() + watcher.seedNew(DeviceDir(path: dir, set: "default")) + XCTAssertEqual(seeds.all, []) + XCTAssertLessThan(Date().timeIntervalSince(started), 4) + } + + // MARK: - events and sets + + func testEventJSONLinesFollowTheGoFieldOrderAndOmitEmptyFields() { + XCTAssertEqual( + WatchEvent(event: "slimmed", udid: "U", set: "default").jsonLine, + #"{"event":"slimmed","udid":"U","set":"default"}"#) + XCTAssertEqual( + WatchEvent(event: "slimmed_before_boot", udid: "U", set: "testing", services: 173).jsonLine, + #"{"event":"slimmed_before_boot","udid":"U","set":"testing","services":173}"#) + XCTAssertEqual( + WatchEvent(event: "failed", udid: "U", set: "/a/b", error: "say \"no\"\nnow").jsonLine, + #"{"event":"failed","udid":"U","set":"/a/b","error":"say \"no\"\nnow"}"#) + } + + func testDeviceSetDirectories() { + var ctl = Simctl(runner: FakeHost()) + ctl.registerDeviceSet("/custom/set") + XCTAssertEqual( + deviceSetDirs(ctl, home: "/Users/me"), + [ + "/Users/me/Library/Developer/CoreSimulator/Devices": "default", + "/Users/me/Library/Developer/XCTestDevices": "testing", + "/custom/set": "/custom/set", + ]) + } + + // MARK: - kqueue + + private func collect( + _ dirs: [String: String], during body: () throws -> Void, expecting count: Int + ) rethrows -> [DeviceDir] { + let found = Calls() + let stop = Flag() + let done = DispatchSemaphore(value: 0) + DispatchQueue.global().async { + watchDeviceDirs( + setDirs: dirs, pollInterval: 0.05, stop: { stop.isSet }, + created: { found.add($0.set + "|" + $0.path) }) + done.signal() + } + Thread.sleep(forTimeInterval: 0.2) // let the baseline be taken + try body() + let limit = Date().addingTimeInterval(5) + while found.all.count < count && Date() < limit { Thread.sleep(forTimeInterval: 0.01) } + Thread.sleep(forTimeInterval: 0.2) // let anything unexpected show up + stop.set() + done.wait() + return found.all.map { entry in + let parts = entry.split(separator: "|", maxSplits: 1).map(String.init) + return DeviceDir(path: parts[1], set: parts[0]) + } + } + + func testKqueueReportsNewDeviceDirectoriesButNotTheBaseline() throws { + let set = root + "/Devices" + try FileManager.default.createDirectory( + atPath: set + "/EXISTING", withIntermediateDirectories: true) + let found = try collect( + [set: "default"], + during: { + try FileManager.default.createDirectory( + atPath: set + "/NEW-1", withIntermediateDirectories: true) + FileManager.default.createFile(atPath: set + "/a-file", contents: Data()) + }, expecting: 1) + XCTAssertEqual(found, [DeviceDir(path: set + "/NEW-1", set: "default")]) + } + + func testKqueueReportsABatchOfClones() throws { + let set = root + "/Devices" + try FileManager.default.createDirectory(atPath: set, withIntermediateDirectories: true) + let found = try collect( + [set: "testing"], + during: { + for n in 0..<5 { + try FileManager.default.createDirectory( + atPath: set + "/CLONE-\(n)", withIntermediateDirectories: true) + } + }, expecting: 5) + XCTAssertEqual(Set(found.map(\.path)), Set((0..<5).map { set + "/CLONE-\($0)" })) + XCTAssertEqual(found.count, 5, "each directory is reported once") + } + + func testKqueueAttachesASetDirectoryThatAppearsLater() throws { + let set = root + "/XCTestDevices" + let found = try collect( + [set: "testing"], + during: { + try FileManager.default.createDirectory(atPath: set, withIntermediateDirectories: true) + Thread.sleep(forTimeInterval: 0.3) + try FileManager.default.createDirectory( + atPath: set + "/CLONE", withIntermediateDirectories: true) + }, expecting: 1) + XCTAssertTrue(found.contains(DeviceDir(path: set + "/CLONE", set: "testing")), "\(found)") + } + + func testKqueueReattachesWhenTheSetDirectoryIsReplaced() throws { + let set = root + "/Devices" + try FileManager.default.createDirectory(atPath: set + "/OLD", withIntermediateDirectories: true) + let found = try collect( + [set: "default"], + during: { + try FileManager.default.removeItem(atPath: set) + Thread.sleep(forTimeInterval: 0.3) + try FileManager.default.createDirectory( + atPath: set + "/FRESH", withIntermediateDirectories: true) + }, expecting: 1) + XCTAssertTrue(found.contains(DeviceDir(path: set + "/FRESH", set: "default")), "\(found)") + } + + func testKqueueReportsADeletedAndRecreatedDeviceAgain() throws { + let set = root + "/Devices" + try FileManager.default.createDirectory(atPath: set, withIntermediateDirectories: true) + let found = try collect( + [set: "default"], + during: { + try FileManager.default.createDirectory( + atPath: set + "/X", withIntermediateDirectories: true) + Thread.sleep(forTimeInterval: 0.3) + try FileManager.default.removeItem(atPath: set + "/X") + Thread.sleep(forTimeInterval: 0.3) + try FileManager.default.createDirectory( + atPath: set + "/X", withIntermediateDirectories: true) + }, expecting: 2) + XCTAssertEqual(found.count, 2) + } + + func testKqueueStopsPromptly() { + let stop = Flag() + let done = DispatchSemaphore(value: 0) + DispatchQueue.global().async { + watchDeviceDirs(setDirs: [:], pollInterval: 0.05, stop: { stop.isSet }, created: { _ in }) + done.signal() + } + stop.set() + XCTAssertEqual(done.wait(timeout: .now() + 2), .success) + } + + // MARK: - run + + func testRunSlimsABootedDeviceAndAFreshCloneThenStops() throws { + let home = root + "/home" + let devices = home + "/Library/Developer/CoreSimulator/Devices" + try FileManager.default.createDirectory(atPath: devices, withIntermediateDirectories: true) + let host = FakeHost(devices: [booted(1)]) + let events = Events() + let seeds = Calls() + let watcher = makeWatcher( + host, events: events, slim: { _, _, _, _, _ in true }, + preslim: { d, _ in + seeds.add(d.udid) + return 3 + }) + let stop = Flag() + let finished = DispatchSemaphore(value: 0) + Thread.detachNewThread { + watcher.run(interval: 0.2, stop: { stop.isSet }) + finished.signal() + } + waitFor("the booted device to be slimmed") { events.kinds.contains("slimmed") } + + // `simctl create` makes the directory, then writes device.plist. + let clone = devices + "/\(udid(9))" + try FileManager.default.createDirectory(atPath: clone, withIntermediateDirectories: true) + try devicePlist(udid: udid(9), runtime: ios, state: 1) + .write(toFile: clone + "/device.plist", atomically: true, encoding: .utf8) + waitFor("the new device to be seeded before any scan lists it") { + seeds.all.contains(self.udid(9)) + } + waitFor("the seed to be announced") { + events.all.contains { $0.event == "slimmed_before_boot" && $0.udid == self.udid(9) } + } + + stop.set() + XCTAssertEqual(finished.wait(timeout: .now() + 10), .success, "run returns once stopped") + } + + func testRunReturnsOnlyAfterItsSlimsHaveStopped() throws { + let host = FakeHost(devices: [booted(1)]) + let events = Events() + let started = Flag() + let exited = Flag() + let watcher = makeWatcher( + host, events: events, + slim: { ctl, _, _, _, _ in + started.set() + while ctl.cancelled?() != true { Thread.sleep(forTimeInterval: 0.005) } + Thread.sleep(forTimeInterval: 0.2) + exited.set() + throw SimSlimError("context canceled") + }) + let stop = Flag() + let finished = DispatchSemaphore(value: 0) + Thread.detachNewThread { + watcher.run(interval: 0.2, stop: { stop.isSet }) + XCTAssertTrue(exited.isSet, "no slim outlives the call") + finished.signal() + } + waitFor("the slim to start") { started.isSet } + stop.set() + XCTAssertEqual(finished.wait(timeout: .now() + 10), .success) + } +} diff --git a/swift/Tests/TestSupport/FakeHost.swift b/swift/Tests/TestSupport/FakeHost.swift new file mode 100644 index 0000000..a203f2d --- /dev/null +++ b/swift/Tests/TestSupport/FakeHost.swift @@ -0,0 +1,453 @@ +// Copyright (c) 2026 Pavel Akhrameev (Swift port). MIT License; see LICENSE. + +import Foundation +import SimSlimKit + +/// A simulated host for tests: it answers the `xcrun simctl`, `pgrep`, `ps` and +/// `top` calls simslim makes, from data the test provides, and records every +/// call. No real process is ever started. +public final class FakeHost: CommandRunning, @unchecked Sendable { + public struct FakeDevice { + public var udid: String + public var name: String + public var runtime: String + public var state: String + public var isAvailable: Bool + + public init( + udid: String, name: String, runtime: String = "com.apple.CoreSimulator.SimRuntime.iOS-27-2", + state: String = "Shutdown", isAvailable: Bool = true + ) { + self.udid = udid + self.name = name + self.runtime = runtime + self.state = state + self.isAvailable = isAvailable + } + } + + public struct Call: Equatable { + public var executable: Executable + public var arguments: [String] + public var timeout: TimeInterval? + } + + private let lock = NSLock() + private var _calls: [Call] = [] + private var spawnQueues: [String: [CommandResult]] = [:] + + /// Devices in the default set. + public var devices: [FakeDevice] + /// Devices per extra set token (for example "testing"); a set absent here + /// fails to list, like a set that does not exist. + public var sets: [String: [FakeDevice]] = [:] + /// `launchctl print-disabled` state per UDID, as `label => disabled` lines. + public var disabled: [String: Set] = [:] + /// pid of each booted simulator's launchd, as pgrep reports it. + public var launchdPIDs: [String: Int] = [:] + public var psOutput = "" + public var topOutput = "" + /// When set, `simctl list` for the default set fails with this stderr. + public var listFailure: String? + + // MARK: Mutable simulator behaviour + + /// Directory standing in for /private/var/tmp: a boot reads + /// `com.apple.CoreSimulator.SimDevice./disabled.plist` from it. + public var storeRoot: String? + /// Whether a boot honours that file (a runtime may ignore it). + public var honoursStore = true + /// Whether disable overrides survive a shutdown (iOS before 18.5 forgets them). + public var persistsOverrides = true + /// Labels loaded in each booted simulator's launchd. + public var loaded: [String: Set] = [:] + /// Job plist path to the Label inside it, as plutil reports it. + public var plistLabels: [String: String] = [:] + /// runtime identifier to RuntimeRoot, for `simctl list runtimes -j`. + public var runtimeRoots: [String: String] = [:] + /// Decides a failure for a transition: (verb, label) -> result, or nil to succeed. + public var failTransition: (@Sendable (String, String) -> CommandResult?)? + /// Fails `simctl boot` / `shutdown` / `bootstatus` with this stderr when set. + public var bootFailure: String? + public var shutdownFailure: String? + /// Fails `simctl bootstatus` but leaves the device Booted, as a boot that + /// started and never became ready. + public var bootstatusFailure: String? + /// When set, a device's `dataPath` is `//data` instead of a + /// path that does not exist, so a test can create (or deliberately not create) + /// the directory. + public var dataRoot: String? + /// Makes `simctl list` report no data path for any device. + public var emptyDataPath = false + /// `du -sk` answers by path, in KiB; a path absent here makes `du` fail. + public var duKiB: [String: Int] = [:] + /// Fails `simctl rename` / `erase` / `delete` with this stderr when set. + public var managementFailure: String? + /// UDIDs `simctl clone` hands out, in order. + public var cloneUDIDs: [String] = [] + /// Fails `simctl clone` with this stderr when set. + public var cloneFailure: String? + /// Makes `simctl clone` put the new device in this set instead of the source's. + public var cloneIntoSet: String? + /// Replaces what `simctl clone` prints, to exercise a malformed answer. + public var cloneOutput: String? + /// Answers `lsof -p `; nil gives each pid one harmless open file. + public var lsofResult: (@Sendable ([Int]) -> CommandResult)? + /// Makes the device ignore shutdown, to exercise the shutdown timeout. + public var stuckBooted = false + /// Called at the start of every command, with the arguments; lets a test + /// observe ordering or inject behaviour. + public var onCall: (@Sendable (Executable, [String]) -> Void)? + + public init(devices: [FakeDevice] = []) { + self.devices = devices + } + + public var calls: [Call] { + lock.lock() + defer { lock.unlock() } + return _calls + } + + /// Queues results returned, in order, by the next `print-disabled` spawns for a + /// UDID before the normal answer resumes: used to simulate launchd error 124. + public func queueSpawnResults(udid: String, _ results: [CommandResult]) { + lock.lock() + spawnQueues[udid, default: []].append(contentsOf: results) + lock.unlock() + } + + public func run(_ executable: Executable, _ arguments: [String], timeout: TimeInterval?) throws + -> CommandResult + { + lock.lock() + _calls.append(Call(executable: executable, arguments: arguments, timeout: timeout)) + lock.unlock() + onCall?(executable, arguments) + + switch executable { + case .plutil: return plutil(arguments) + case .xcrun: return xcrun(arguments) + case .pgrep: return pgrep(arguments) + case .ps: return CommandResult(status: 0, stdout: Data(psOutput.utf8)) + case .top: return CommandResult(status: 0, stdout: Data(topOutput.utf8)) + case .lsof: + let pids = (arguments.last ?? "").split(separator: ",").compactMap { Int($0) } + if let lsofResult { return lsofResult(pids) } + let text = pids.map { "p\($0)\nn/dev/null\n" }.joined() + return CommandResult(status: 0, stdout: Data(text.utf8)) + case .du: + guard arguments.count == 2, arguments[0] == "-sk", let kib = duKiB[arguments[1]] else { + return CommandResult( + status: 1, stderr: Data("du: \(arguments.last ?? ""): No such file or directory".utf8)) + } + return CommandResult(status: 0, stdout: Data("\(kib)\t\(arguments[1])\n".utf8)) + default: + return CommandResult(status: 127, stderr: Data("FakeHost: unexpected \(executable)".utf8)) + } + } + + // MARK: - Answers + + private func xcrun(_ args: [String]) -> CommandResult { + guard args.first == "simctl" else { return failure("unexpected xcrun \(args)") } + var rest = Array(args.dropFirst()) + var token = "" + if rest.first == "--set", rest.count >= 2 { + token = rest[1] + rest = Array(rest.dropFirst(2)) + } + + if rest == ["list", "devices", "-j"] { return list(token: token) } + if rest.count == 5, rest[0] == "spawn", rest[2] == "launchctl", rest[3] == "print-disabled", + rest[4] == "system" + { + return printDisabled(udid: rest[1]) + } + if let result = mutating(rest, token: token) { return result } + return failure("FakeHost: unhandled simctl \(rest)") + } + + // MARK: - State changes + + /// Like simctl, a device is only visible through the `--set` it lives in. + private func setState(_ udid: String, _ state: String, token: String) -> Bool { + if token.isEmpty { + guard let i = devices.firstIndex(where: { $0.udid == udid }) else { return false } + devices[i].state = state + return true + } + guard let i = sets[token]?.firstIndex(where: { $0.udid == udid }) else { return false } + sets[token]![i].state = state + return true + } + + private func withDevice(_ udid: String, token: String, _ change: (inout FakeDevice) -> Void) + -> CommandResult + { + if token.isEmpty { + guard let i = devices.firstIndex(where: { $0.udid == udid }) else { + return failure("Invalid device") + } + change(&devices[i]) + } else { + guard let i = sets[token]?.firstIndex(where: { $0.udid == udid }) else { + return failure("Invalid device") + } + change(&sets[token]![i]) + } + return CommandResult(status: 0) + } + + private func stateOf(_ udid: String, token: String) -> String? { + (token.isEmpty ? devices : sets[token] ?? []).first { $0.udid == udid }?.state + } + + /// The boolean entries launchd_sim would read from the store at start. + private func storeEntries(_ udid: String) -> [String: Bool] { + guard let storeRoot else { return [:] } + let path = "\(storeRoot)/com.apple.CoreSimulator.SimDevice.\(udid)/disabled.plist" + guard let data = FileManager.default.contents(atPath: path), + let object = try? PropertyListSerialization.propertyList( + from: data, options: [], format: nil), + let dict = object as? [String: Any] + else { return [:] } + return dict.compactMapValues { $0 as? Bool } + } + + private func mutating(_ rest: [String], token: String) -> CommandResult? { + lock.lock() + defer { lock.unlock() } + guard let verb = rest.first else { return nil } + switch verb { + case "boot" where rest.count == 2: + let udid = rest[1] + if let bootFailure { return CommandResult(status: 1, stderr: Data(bootFailure.utf8)) } + guard let state = stateOf(udid, token: token) else { + return failure("Invalid device: \(udid)") + } + if state == "Booted" { + return CommandResult( + status: 149, stderr: Data("Unable to boot device in current state: Booted".utf8)) + } + _ = setState(udid, "Booted", token: token) + var live = persistsOverrides ? (disabled[udid] ?? []) : [] + if honoursStore { + // The store is authoritative: an explicit true disables, an explicit + // false enables even what was disabled before. + for (label, off) in storeEntries(udid) { + if off { live.insert(label) } else { live.remove(label) } + } + } + disabled[udid] = live + loaded[udid] = loaded[udid] ?? Self.defaultLoaded + loaded[udid]!.subtract(live) + return CommandResult(status: 0) + case "bootstatus" where rest.count == 3: + if let bootstatusFailure { + return CommandResult(status: 1, stderr: Data(bootstatusFailure.utf8)) + } + return stateOf(rest[1], token: token) == "Booted" + ? CommandResult(status: 0) : CommandResult(status: 1, stderr: Data("not booted".utf8)) + case "shutdown" where rest.count == 2: + let udid = rest[1] + if let shutdownFailure { return CommandResult(status: 1, stderr: Data(shutdownFailure.utf8)) } + guard let state = stateOf(udid, token: token) else { + return failure("Invalid device: \(udid)") + } + if state != "Booted" { + return CommandResult( + status: 149, stderr: Data("Unable to shutdown device in current state: Shutdown".utf8)) + } + if !stuckBooted { _ = setState(udid, "Shutdown", token: token) } + return CommandResult(status: 0) + case "rename" where rest.count == 3: + if let managementFailure { + return CommandResult(status: 1, stderr: Data(managementFailure.utf8)) + } + guard stateOf(rest[1], token: token) != nil else { + return failure("Invalid device: \(rest[1])") + } + return withDevice(rest[1], token: token) { $0.name = rest[2] } + case "erase" where rest.count == 2: + if let managementFailure { + return CommandResult(status: 1, stderr: Data(managementFailure.utf8)) + } + guard let state = stateOf(rest[1], token: token) else { + return failure("Invalid device: \(rest[1])") + } + if state != "Shutdown" { + return CommandResult( + status: 164, + stderr: Data("Unable to erase contents and settings in current state: \(state)".utf8)) + } + return CommandResult(status: 0) + case "delete" where rest.count == 2: + if let managementFailure { + return CommandResult(status: 1, stderr: Data(managementFailure.utf8)) + } + guard stateOf(rest[1], token: token) != nil else { + return failure("Invalid device: \(rest[1])") + } + if token.isEmpty { + devices.removeAll { $0.udid == rest[1] } + } else { + sets[token]?.removeAll { $0.udid == rest[1] } + } + return CommandResult(status: 0) + case "clone" where rest.count == 3: + if let cloneFailure { return CommandResult(status: 1, stderr: Data(cloneFailure.utf8)) } + guard let source = deviceNamed(rest[1], token: token) else { + return failure("Invalid device: \(rest[1])") + } + guard !cloneUDIDs.isEmpty else { return failure("no clone UDID queued") } + let udid = cloneUDIDs.removeFirst() + var copy = source + copy.udid = udid + copy.name = rest[2] + copy.state = "Shutdown" + if let cloneIntoSet { + sets[cloneIntoSet, default: []].append(copy) + } else if token.isEmpty { + devices.append(copy) + } else { + sets[token, default: []].append(copy) + } + if let dataRoot { + try? FileManager.default.copyItem( + atPath: "\(dataRoot)/\(source.udid)", toPath: "\(dataRoot)/\(udid)") + } + return CommandResult(status: 0, stdout: Data((cloneOutput ?? udid + "\n").utf8)) + case "list" where rest == ["list", "runtimes", "-j"]: + let runtimes = runtimeRoots.map { ["identifier": $0.key, "runtimeRoot": $0.value] } + let data = try! JSONSerialization.data(withJSONObject: ["runtimes": runtimes]) + return CommandResult(status: 0, stdout: data) + case "spawn" where rest.count >= 4 && rest[2] == "launchctl": + return launchctl(udid: rest[1], token: token, Array(rest.dropFirst(3))) + default: + return nil + } + } + + /// Labels loaded in a freshly booted simulator. + public static var defaultLoaded: Set { [] } + + private func launchctl(udid: String, token: String, _ args: [String]) -> CommandResult? { + guard stateOf(udid, token: token) == "Booted" else { + return CommandResult(status: 1, stderr: Data("Unable to spawn: not booted".utf8)) + } + switch args[0] { + case "list": + var text = "PID\tStatus\tLabel\n" + for label in (loaded[udid] ?? []).sorted() { text += "-\t0\t\(label)\n" } + return CommandResult(status: 0, stdout: Data(text.utf8)) + case "disable", "enable", "bootout": + guard args.count == 2, args[1].hasPrefix("system/") else { return nil } + let label = String(args[1].dropFirst("system/".count)) + if let fail = failTransition?(args[0], label) { return fail } + switch args[0] { + case "disable": disabled[udid, default: []].insert(label) + case "enable": disabled[udid, default: []].remove(label) + default: + if loaded[udid]?.remove(label) == nil { + return CommandResult(status: 3, stderr: Data("No such process".utf8)) + } + } + return CommandResult(status: 0) + case "unload" where args.count >= 3 && args[1] == "-w": + for path in args.dropFirst(2) { + guard let label = plistLabels[path] else { continue } + if let fail = failTransition?("unload", label) { + _ = fail + continue + } + disabled[udid, default: []].insert(label) + loaded[udid]?.remove(label) + } + return CommandResult(status: 0) + case "load" where args.count >= 3 && args[1] == "-w": + // Lifts each job's override and loads it, unless the test makes it fail. + for path in args.dropFirst(2) { + guard let label = plistLabels[path] else { continue } + if failTransition?("load", label) != nil { continue } + disabled[udid, default: []].remove(label) + loaded[udid, default: []].insert(label) + } + return CommandResult(status: 0) + case "bootstrap" where args.count == 3 && args[1] == "system": + guard let label = plistLabels[args[2]] else { return CommandResult(status: 113) } + if failTransition?("bootstrap", label) != nil { return CommandResult(status: 5) } + if disabled[udid]?.contains(label) == true { return CommandResult(status: 5) } + loaded[udid, default: []].insert(label) + return CommandResult(status: 0) + default: + return nil + } + } + + private func deviceNamed(_ udid: String, token: String) -> FakeDevice? { + (token.isEmpty ? devices : (sets[token] ?? [])).first { $0.udid == udid } + } + + private func plutil(_ args: [String]) -> CommandResult { + // plutil -extract Label raw -o - + guard args.count == 6, let label = plistLabels[args[5]] else { + return CommandResult(status: 1, stderr: Data("plutil: no such file".utf8)) + } + return CommandResult(status: 0, stdout: Data((label + "\n").utf8)) + } + + private func list(token: String) -> CommandResult { + let source: [FakeDevice] + if token.isEmpty { + if let listFailure { return CommandResult(status: 1, stderr: Data(listFailure.utf8)) } + source = devices + } else if let set = sets[token] { + source = set + } else { + return CommandResult(status: 1, stderr: Data("Invalid device set: \(token)".utf8)) + } + + var byRuntime: [String: [[String: Any]]] = [:] + for device in source { + byRuntime[device.runtime, default: []].append([ + "udid": device.udid, "name": device.name, "state": device.state, + "isAvailable": device.isAvailable, + "dataPath": emptyDataPath ? "" : "\(dataRoot ?? "/fake")/\(device.udid)/data", + ]) + } + let data = try! JSONSerialization.data(withJSONObject: ["devices": byRuntime]) + return CommandResult(status: 0, stdout: data) + } + + private func printDisabled(udid: String) -> CommandResult { + lock.lock() + if var queue = spawnQueues[udid], !queue.isEmpty { + let next = queue.removeFirst() + spawnQueues[udid] = queue + lock.unlock() + return next + } + lock.unlock() + + guard let labels = disabled[udid] else { + return CommandResult(status: 1, stderr: Data("Unable to find device \(udid)".utf8)) + } + var text = "disabled services = {\n" + for label in labels.sorted() { text += "\t\"\(label)\" => disabled\n" } + text += "\t\"com.apple.some.enabled.service\" => enabled\n}\n" + return CommandResult(status: 0, stdout: Data(text.utf8)) + } + + private func pgrep(_ args: [String]) -> CommandResult { + guard args.count == 2, args[0] == "-f" else { return failure("unexpected pgrep \(args)") } + for (udid, pid) in launchdPIDs where args[1].hasPrefix(udid) { + return CommandResult(status: 0, stdout: Data("\(pid)\n".utf8)) + } + return CommandResult(status: 1) + } + + private func failure(_ message: String) -> CommandResult { + CommandResult(status: 99, stderr: Data(message.utf8)) + } +} diff --git a/swift/expected-libs.txt b/swift/expected-libs.txt new file mode 100644 index 0000000..d66aa34 --- /dev/null +++ b/swift/expected-libs.txt @@ -0,0 +1,11 @@ +/System/Library/Frameworks/CoreFoundation.framework/Versions/A/CoreFoundation +/System/Library/Frameworks/Foundation.framework/Versions/C/Foundation +/usr/lib/libobjc.A.dylib +/usr/lib/libSystem.B.dylib +/usr/lib/swift/libswiftCore.dylib +/usr/lib/swift/libswiftCoreFoundation.dylib +/usr/lib/swift/libswiftDarwin.dylib +/usr/lib/swift/libswiftDispatch.dylib +/usr/lib/swift/libswiftIOKit.dylib +/usr/lib/swift/libswiftObjectiveC.dylib +/usr/lib/swift/libswiftXPC.dylib diff --git a/verify.go b/verify.go deleted file mode 100644 index e8bca80..0000000 --- a/verify.go +++ /dev/null @@ -1,59 +0,0 @@ -package simslim - -import ( - "context" - "fmt" - "sort" -) - -// VerifyResult reports how a booted simulator's launchd disable overrides -// compare to a profile's desired set. Only managed labels are considered. -type VerifyResult struct { - UDID string `json:"udid"` - OK bool `json:"ok"` - Missing []string `json:"missing,omitempty"` // profile wants these disabled; they are enabled - Extra []string `json:"extra,omitempty"` // managed labels disabled beyond the profile -} - -// VerifyProfile checks, without mutating anything, that a booted simulator's -// disable overrides match the profile exactly. The overrides are per-simulator -// state that is easy to lose silently when a device is erased or recreated, so -// VerifyProfile detects the drift and callers can re-run `on` (which is -// idempotent) to repair it. SimSlim-created clones preserve this state. -func VerifyProfile(ctx context.Context, udid string, p Profile) (VerifyResult, error) { - d, err := FindDevice(ctx, udid, "") - if err != nil { - return VerifyResult{}, err - } - if d.State != "Booted" { - return VerifyResult{}, fmt.Errorf("simulator must be booted to read its state (it is %s)", d.State) - } - disabled, err := readDisabled(ctx, d.Set, d.UDID) - if err != nil { - return VerifyResult{}, err - } - r := compareDisabled(disabled, p.DesiredForDevice(d), managedSet()) - r.UDID = udid - return r, nil -} - -// compareDisabled diffs the currently disabled labels against the desired set, -// restricted to the managed universe (unmanaged labels are never simslim's -// business and never count as drift). -func compareDisabled(disabled, desired, managed map[string]bool) VerifyResult { - var r VerifyResult - for l := range desired { - if !disabled[l] { - r.Missing = append(r.Missing, l) - } - } - for l := range disabled { - if managed[l] && !desired[l] { - r.Extra = append(r.Extra, l) - } - } - sort.Strings(r.Missing) - sort.Strings(r.Extra) - r.OK = len(r.Missing) == 0 && len(r.Extra) == 0 - return r -} diff --git a/verify_test.go b/verify_test.go deleted file mode 100644 index a06c36e..0000000 --- a/verify_test.go +++ /dev/null @@ -1,64 +0,0 @@ -package simslim - -import ( - "reflect" - "testing" -) - -func TestCompareDisabled(t *testing.T) { - managed := map[string]bool{"a": true, "b": true, "c": true, "d": true} - tests := []struct { - name string - disabled map[string]bool - desired map[string]bool - want VerifyResult - }{ - { - name: "exact match", - disabled: map[string]bool{"a": true, "b": true}, - desired: map[string]bool{"a": true, "b": true}, - want: VerifyResult{OK: true}, - }, - { - name: "erase wiped everything", - disabled: map[string]bool{}, - desired: map[string]bool{"a": true, "b": true}, - want: VerifyResult{Missing: []string{"a", "b"}}, - }, - { - name: "partial drift both directions", - disabled: map[string]bool{"a": true, "c": true}, - desired: map[string]bool{"a": true, "b": true}, - want: VerifyResult{Missing: []string{"b"}, Extra: []string{"c"}}, - }, - { - name: "unmanaged disabled labels are not drift", - disabled: map[string]bool{"a": true, "com.example.other": true}, - desired: map[string]bool{"a": true}, - want: VerifyResult{OK: true}, - }, - { - name: "stock device with empty profile", - disabled: map[string]bool{}, - desired: map[string]bool{}, - want: VerifyResult{OK: true}, - }, - } - for _, tt := range tests { - t.Run(tt.name, func(t *testing.T) { - got := compareDisabled(tt.disabled, tt.desired, managed) - if !reflect.DeepEqual(got, tt.want) { - t.Errorf("compareDisabled() = %+v, want %+v", got, tt.want) - } - }) - } -} - -func TestCompareDisabledMissingSorted(t *testing.T) { - managed := map[string]bool{"z": true, "a": true, "m": true} - got := compareDisabled(map[string]bool{}, map[string]bool{"z": true, "a": true, "m": true}, managed) - want := []string{"a", "m", "z"} - if !reflect.DeepEqual(got.Missing, want) { - t.Errorf("Missing = %v, want %v", got.Missing, want) - } -} diff --git a/watch.go b/watch.go deleted file mode 100644 index 4c6afe8..0000000 --- a/watch.go +++ /dev/null @@ -1,408 +0,0 @@ -package simslim - -import ( - "context" - "encoding/xml" - "errors" - "fmt" - "io" - "os" - "path/filepath" - "sort" - "sync" - "time" -) - -// DefaultWatchInterval is how often Watch rescans the device sets. -const DefaultWatchInterval = 3 * time.Second - -// newDevicePlistWait bounds how long Watch waits for a new device directory's -// device.plist, which `simctl create` writes just after the directory. -const newDevicePlistWait = 2 * time.Second - -// slimStrategy is the per-device slimming applied by Watch. It is a field so -// tests can substitute a fake for EnableSlimNoReboot. -type slimStrategy func(ctx context.Context, set, udid string, p Profile, report Reporter) (bool, error) - -// preslimStrategy seeds a shut-down device before it boots. It is a field so -// tests can substitute a fake for preslimDevice. -type preslimStrategy func(d Device, p Profile) (int, error) - -// Watch slims every simulator so that none starts the profile's daemons, then -// leaves it alone until it boots again. -// A shut-down simulator on a runtime that persists overrides is slimmed before -// it boots: Watch writes the profile's disable overrides into its launchd store, -// so its next boot, its very first included, starts none of those daemons. New -// devices are caught by a kqueue watch on the device-set directories, ahead of -// a tool that creates and boots at once. Every simulator is still slimmed no-reboot -// as it boots: that reads the device back, and it is the only hook for a device -// that booted before its store was seeded, on an older runtime, or as an -// xcodebuild parallel-testing clone (cloned stock, since overrides do not -// survive `simctl clone`, and booted at once). Watch runs until ctx is cancelled -// (Ctrl-C), scanning the default, testing, and any --set device sets. It slims -// each booted device in its own goroutine so one slow reconfigure does not delay -// catching the next clone, and returns once those goroutines are done. -func Watch(ctx context.Context, p Profile, interval time.Duration, report Reporter) error { - return WatchWithEvents(ctx, p, interval, report, nil) -} - -// The WatchEvent kinds. A wrapper that boots a device and then changes its -// services waits for WatchSlimmed (or WatchFailed): after it, the watcher does -// not touch that device again until the device shuts down. -const ( - WatchSlimming = "slimming" // an after-boot pass started - WatchSlimmed = "slimmed" // the pass for the current boot finished - WatchFailed = "failed" // the pass failed; the next scan retries it - WatchStopped = "stopped" // the device shut down, so its pass was cancelled - WatchSlimmedBeforeBoot = "slimmed_before_boot" // disables were written into a shut-down device's store -) - -// WatchEvent is the stable, machine-readable form of a watcher log line. -type WatchEvent struct { - Event string `json:"event"` - UDID string `json:"udid"` - Set string `json:"set"` - Services int `json:"services,omitempty"` // disables written, for slimmed_before_boot - Error string `json:"error,omitempty"` // for failed -} - -// WatchWithEvents is Watch that also hands every WatchEvent to events, which -// may be called from several goroutines at once. A nil events behaves as Watch. -func WatchWithEvents(ctx context.Context, p Profile, interval time.Duration, report Reporter, events func(WatchEvent)) error { - return watch(ctx, p, interval, report, events, EnableSlimNoReboot) -} - -func watch(ctx context.Context, p Profile, interval time.Duration, report Reporter, events func(WatchEvent), slim slimStrategy) error { - if interval <= 0 { - interval = DefaultWatchInterval - } - w := &watcher{p: p, report: report, events: events, slim: slim, preslim: preslimDevice, passes: map[string]*slimPass{}, seeded: map[string]bool{}} - // The CLI exits right after this returns, but an importer keeps running, so - // no slim may outlive the call. A cancelled ctx aborts an in-flight slim - // inside its next simctl call, which keeps the wait short. - defer w.wg.Wait() - created := make(chan struct{}, 1) - w.wg.Add(1) - go func() { - defer w.wg.Done() - watchDeviceDirs(ctx, deviceSetDirs(), interval, func(dir deviceDir) { - // seedNew waits for device.plist, so each new device gets its own - // goroutine: a batch of parallel-testing clones seeds at once. - w.wg.Add(1) - go func() { - defer w.wg.Done() - w.seedNew(ctx, dir) - select { - case created <- struct{}{}: - default: // a scan is already due - } - }() - }) - }() - ticker := time.NewTicker(interval) - defer ticker.Stop() - for { - w.scan(ctx) - select { - case <-ctx.Done(): - return nil - case <-ticker.C: - case <-created: - } - } -} - -// preslimDevice writes the profile's missing disable overrides into a shut-down -// device's launchd store and reports how many it added. Like the no-reboot slim -// Watch applies after boot, it only ever adds disables: a service someone -// disabled beyond the profile stays disabled, and nothing is re-enabled. A -// device that is not shut down, or whose runtime does not persist overrides, -// is left alone; the after-boot slim covers it. -func preslimDevice(d Device, p Profile) (int, error) { - if d.State != "Shutdown" || !d.SupportsPersistentOverrides() { - return 0, nil - } - current, err := readDisabledStore(d.UDID) - if err != nil { - return 0, err - } - toDisable, _ := delta(current, p.DesiredForDevice(d), managedSet()) - if len(toDisable) == 0 { - return 0, nil - } - if err := writeDisabledStore(d.UDID, toDisable, nil); err != nil { - return 0, err - } - return len(toDisable), nil -} - -// deviceDir is one device's directory, named by its UDID, in a scanned set. -type deviceDir struct { - path string - set string -} - -// deviceSetDirs maps each scanned set's device directory to the set's name: -// CoreSimulator's default set, the parallel-testing set, and any --set path. -func deviceSetDirs() map[string]string { - home, err := os.UserHomeDir() - if err != nil { - return nil - } - dirs := map[string]string{} - for _, set := range knownDeviceSets() { - switch set.token { - case "": - dirs[filepath.Join(home, "Library", "Developer", "CoreSimulator", "Devices")] = set.name - case "testing": - dirs[filepath.Join(home, "Library", "Developer", "XCTestDevices")] = set.name - default: - dirs[set.token] = set.name - } - } - return dirs -} - -// readDevicePlist reads the device CoreSimulator describes in a device -// directory's device.plist: its UDID, runtime and state (1 is Shutdown). -func readDevicePlist(dir deviceDir) (Device, error) { - f, err := os.Open(filepath.Join(dir.path, "device.plist")) - if err != nil { - return Device{}, err - } - defer f.Close() - values := map[string]string{} - decoder := xml.NewDecoder(f) - key := "" - for { - token, err := decoder.Token() - if errors.Is(err, io.EOF) { - break - } - if err != nil { - return Device{}, fmt.Errorf("parse device.plist: %w", err) - } - start, ok := token.(xml.StartElement) - if !ok { - continue - } - var text string - switch start.Name.Local { - case "key": - if err := decoder.DecodeElement(&key, &start); err != nil { - return Device{}, fmt.Errorf("parse device.plist: %w", err) - } - case "string", "integer": - if err := decoder.DecodeElement(&text, &start); err != nil { - return Device{}, fmt.Errorf("parse device.plist: %w", err) - } - values[key] = text - } - } - platform, version := parseRuntime(values["runtime"]) - if values["UDID"] == "" || platform == "" { - return Device{}, fmt.Errorf("device.plist names no UDID or supported runtime") - } - state := "Booted" - if values["state"] == "1" { - state = "Shutdown" - } - return Device{UDID: values["UDID"], State: state, Platform: platform, OSVersion: version, Set: dir.set, DataPath: filepath.Join(dir.path, "data"), RuntimeID: values["runtime"]}, nil -} - -// seedNew slims a just-created device before its first boot, straight from its -// directory and without a `simctl list`, which on a loaded host would still be -// running when a script that boots right after creating has started launchd_sim. -func (w *watcher) seedNew(ctx context.Context, dir deviceDir) { - deadline := time.Now().Add(newDevicePlistWait) - d, err := readDevicePlist(dir) - for err != nil && time.Now().Before(deadline) { - select { - case <-ctx.Done(): - return - case <-time.After(10 * time.Millisecond): - } - d, err = readDevicePlist(dir) - } - if err != nil { - return // not a device, or not one simslim slims; the scan decides - } - w.seed(d) -} - -// watcher holds in passes the booted UDIDs already slimmed or in flight, and in -// seeded the shut-down UDIDs whose store already holds the profile. The scan -// loop, the slim goroutines and the seed goroutines all touch them, so mu -// guards both. -type watcher struct { - p Profile - report Reporter - events func(WatchEvent) - slim slimStrategy - preslim preslimStrategy - wg sync.WaitGroup - mu sync.Mutex - passes map[string]*slimPass - seeded map[string]bool -} - -// slimPass is one boot's after-boot slim. Its cancel stops it once that boot -// ends, so it cannot keep retrying into the device's next boot. -type slimPass struct { - cancel context.CancelFunc -} - -func (w *watcher) emit(e WatchEvent) { - if w.events != nil { - w.events(e) - } -} - -func (w *watcher) scan(ctx context.Context) { - devices, err := ListDevices(ctx) - if err != nil { - w.report.report(fmt.Sprintf("watch: list devices: %v", err)) - return - } - sort.Slice(devices, func(i, j int) bool { return devices[i].UDID < devices[j].UDID }) - w.prune(devices) - for _, d := range devices { - if d.State != "Booted" { - // On iOS below 18.5 the no-reboot slim dies with the boot session, - // so a device that shut down comes back stock and needs slimming - // again. Re-slimming an already-slim device is a cheap no-op. - w.forget(d.UDID) - w.seed(d) - continue - } - // A booted device may change its own store (and `simslim off` may - // clear it), so check it again the next time it is shut down. - w.mu.Lock() - delete(w.seeded, d.UDID) - w.mu.Unlock() - pctx, pass := w.claim(ctx, d.UDID) - if pass == nil { - continue - } - w.wg.Add(1) - go func(d Device) { - defer w.wg.Done() - defer pass.cancel() - w.report.report(fmt.Sprintf("watch: slimming %s (set %s)", d.UDID, d.Set)) - w.emit(WatchEvent{Event: WatchSlimming, UDID: d.UDID, Set: d.Set}) - _, err := w.slim(pctx, d.Set, d.UDID, w.p, prefixed(w.report, d.UDID)) - w.finish(d, pass, err) - }(d) - } -} - -// seed slims a shut-down device ahead of its next boot, once per shutdown. A -// failure is retried on the next scan, and the after-boot slim still covers -// the device if it boots first. -func (w *watcher) seed(d Device) { - if w.preslim == nil { - return - } - // A device caught Shutting Down or Booting is seeded once it reads Shutdown. - if d.State != "Shutdown" { - return - } - w.mu.Lock() - defer w.mu.Unlock() // serializes the store writes of seedNew and scan - if w.seeded[d.UDID] { - return - } - n, err := w.preslim(d, w.p) - if err != nil { - w.report.report(fmt.Sprintf("watch: %s: slim before boot: %v", d.UDID, err)) - return - } - w.seeded[d.UDID] = true - if n == 0 { - return - } - // launchd_sim reads the store once, when it starts: a seed that lands after - // the boot began only counts from the next boot. - if now, err := readDevicePlist(deviceDir{path: filepath.Dir(d.DataPath), set: d.Set}); d.DataPath != "" && err == nil && now.State != "Shutdown" { - w.report.report(fmt.Sprintf("watch: %s booted before its slim (%d services) landed; slimming it as it boots", d.UDID, n)) - return - } - w.report.report(fmt.Sprintf("watch: slimmed %s before boot (%d services disabled, set %s)", d.UDID, n, d.Set)) - w.emit(WatchEvent{Event: WatchSlimmedBeforeBoot, UDID: d.UDID, Set: d.Set, Services: n}) -} - -// finish reports a pass's outcome. It holds mu so a superseded pass, whose boot -// ended, can never announce slimmed after a newer boot's pass has started. -func (w *watcher) finish(d Device, pass *slimPass, err error) { - w.mu.Lock() - defer w.mu.Unlock() - switch { - case w.passes[d.UDID] != pass: - w.report.report(fmt.Sprintf("watch: %s shut down; stopped its slim", d.UDID)) - w.emit(WatchEvent{Event: WatchStopped, UDID: d.UDID, Set: d.Set}) - case err != nil: - // A transient launchctl failure would otherwise leave this clone stock - // for the whole test run. The next scan retries it, and a torn-down - // clone drops out of simctl list, so this does not loop. - delete(w.passes, d.UDID) - w.report.report(fmt.Sprintf("watch: %s: %v", d.UDID, err)) - w.emit(WatchEvent{Event: WatchFailed, UDID: d.UDID, Set: d.Set, Error: err.Error()}) - default: - w.report.report(fmt.Sprintf("watch: slimmed %s", d.UDID)) - w.emit(WatchEvent{Event: WatchSlimmed, UDID: d.UDID, Set: d.Set}) - } -} - -// claim starts a pass for a booted UDID, returning a nil pass when one is -// already done or in flight for this boot. -func (w *watcher) claim(ctx context.Context, udid string) (context.Context, *slimPass) { - w.mu.Lock() - defer w.mu.Unlock() - if w.passes[udid] != nil { - return nil, nil - } - pctx, cancel := context.WithCancel(ctx) - pass := &slimPass{cancel: cancel} - w.passes[udid] = pass - return pctx, pass -} - -// prune drops the UDIDs of deleted devices, such as finished parallel-testing -// clones, so passes and seeded do not grow by one entry per clone. A device -// created after the listing started is only seeded again, which is a no-op. -func (w *watcher) prune(devices []Device) { - listed := make(map[string]bool, len(devices)) - for _, d := range devices { - listed[d.UDID] = true - } - w.mu.Lock() - defer w.mu.Unlock() - for udid, pass := range w.passes { - if !listed[udid] { - pass.cancel() - delete(w.passes, udid) - } - } - for udid := range w.seeded { - if !listed[udid] { - delete(w.seeded, udid) - } - } -} - -// forget ends a device's boot: its pass, if still running, is cancelled, and -// its next boot gets a pass of its own. -func (w *watcher) forget(udid string) { - w.mu.Lock() - if pass := w.passes[udid]; pass != nil { - pass.cancel() - delete(w.passes, udid) - } - w.mu.Unlock() -} - -// prefixed tags a device's own progress lines with its UDID, so the interleaved -// output of concurrent slims stays attributable. -func prefixed(report Reporter, udid string) Reporter { - return func(msg string) { report.report(fmt.Sprintf("watch: %s: %s", udid, msg)) } -} diff --git a/watch_dirs_darwin.go b/watch_dirs_darwin.go deleted file mode 100644 index 412abac..0000000 --- a/watch_dirs_darwin.go +++ /dev/null @@ -1,114 +0,0 @@ -package simslim - -import ( - "context" - "os" - "path/filepath" - "syscall" - "time" -) - -// watchDeviceDirs calls created for each directory that appears in one of -// setDirs, until ctx is cancelled. A kqueue NOTE_WRITE on each set directory -// wakes it within a millisecond of `simctl create`, and costs nothing while -// idle. A set directory that does not exist yet (XCTestDevices before the first -// parallel-testing run) is attached again every retry; its devices count as new -// from then on. A deleted device directory is forgotten, so known holds only -// the devices that exist. -func watchDeviceDirs(ctx context.Context, setDirs map[string]string, retry time.Duration, created func(deviceDir)) { - kq, err := syscall.Kqueue() - if err != nil { - return // the scan still catches every device, only later - } - defer syscall.Close(kq) - // An EVFILT_USER event wakes the blocked kevent when ctx is cancelled. - wake := []syscall.Kevent_t{{Ident: 0, Filter: syscall.EVFILT_USER, Flags: syscall.EV_ADD | syscall.EV_CLEAR}} - if _, err := syscall.Kevent(kq, wake, nil, nil); err != nil { - return - } - woken := make(chan struct{}) - stop := context.AfterFunc(ctx, func() { - trigger := []syscall.Kevent_t{{Ident: 0, Filter: syscall.EVFILT_USER, Fflags: syscall.NOTE_TRIGGER}} - syscall.Kevent(kq, trigger, nil, nil) - close(woken) - }) - defer func() { - if !stop() { - <-woken // kq stays open until the trigger is done with it - } - }() - - fds := map[string]int{} // attached set directory -> its fd - dirs := map[uint64]string{} // fd -> attached set directory - known := map[string]map[string]bool{} // set directory -> its device directories - defer func() { - for _, fd := range fds { - syscall.Close(fd) - } - }() - // list records dir's device directories, reporting the new ones unless this - // is the baseline taken at startup: those are the first scan's business. - list := func(dir string, report bool) { - entries, err := os.ReadDir(dir) - if err != nil { - return - } - was := known[dir] - now := map[string]bool{} - for _, e := range entries { - if !e.IsDir() { - continue - } - now[e.Name()] = true - if report && !was[e.Name()] { - created(deviceDir{path: filepath.Join(dir, e.Name()), set: setDirs[dir]}) - } - } - known[dir] = now - } - attach := func(report bool) { - for dir := range setDirs { - if _, ok := fds[dir]; ok { - continue - } - fd, err := syscall.Open(dir, syscall.O_EVTONLY|syscall.O_DIRECTORY, 0) - if err != nil { - continue - } - ev := []syscall.Kevent_t{{Ident: uint64(fd), Filter: syscall.EVFILT_VNODE, Flags: syscall.EV_ADD | syscall.EV_CLEAR, Fflags: syscall.NOTE_WRITE | syscall.NOTE_DELETE | syscall.NOTE_RENAME}} - if _, err := syscall.Kevent(kq, ev, nil, nil); err != nil { - syscall.Close(fd) - continue - } - fds[dir] = fd - dirs[uint64(fd)] = dir - list(dir, report) - } - } - attach(false) - timeout := syscall.NsecToTimespec(retry.Nanoseconds()) - events := make([]syscall.Kevent_t, len(setDirs)+1) - for ctx.Err() == nil { - n, err := syscall.Kevent(kq, nil, events, &timeout) - if err != nil && err != syscall.EINTR { - return - } - for _, ev := range events[:max(n, 0)] { - dir, ok := dirs[ev.Ident] - if ev.Filter != syscall.EVFILT_VNODE || !ok { - continue - } - if ev.Fflags&(syscall.NOTE_DELETE|syscall.NOTE_RENAME) != 0 { - // The set directory itself went away; attach it again once - // it is back, and report what it holds then. - syscall.Close(fds[dir]) - delete(fds, dir) - delete(dirs, ev.Ident) - delete(known, dir) - continue - } - list(dir, true) - } - attach(true) - } -} diff --git a/watch_dirs_darwin_test.go b/watch_dirs_darwin_test.go deleted file mode 100644 index 551ef44..0000000 --- a/watch_dirs_darwin_test.go +++ /dev/null @@ -1,72 +0,0 @@ -package simslim - -import ( - "context" - "os" - "path/filepath" - "testing" - "time" -) - -// TestWatchDeviceDirs verifies a device created after the watch starts is -// reported with its set and the devices already there are not, a deleted -// device is forgotten, and a set directory created later is attached on retry. -func TestWatchDeviceDirs(t *testing.T) { - dir := t.TempDir() - missing := filepath.Join(t.TempDir(), "missing") - if err := os.Mkdir(filepath.Join(dir, "OLD"), 0o755); err != nil { - t.Fatal(err) - } - ctx, cancel := context.WithCancel(context.Background()) - created := make(chan deviceDir, 4) - done := make(chan struct{}) - go func() { - watchDeviceDirs(ctx, map[string]string{dir: "default", missing: "testing"}, 10*time.Millisecond, func(d deviceDir) { created <- d }) - close(done) - }() - expect := func(want deviceDir) { - t.Helper() - select { - case d := <-created: - if d != want { - t.Fatalf("reported %v, want %v", d, want) - } - case <-time.After(2 * time.Second): - t.Fatalf("%v was not reported", want) - } - } - - select { - case d := <-created: - t.Fatalf("an existing device was reported: %v", d) - case <-time.After(50 * time.Millisecond): - } - newDir := filepath.Join(dir, "NEW") - if err := os.Mkdir(newDir, 0o755); err != nil { - t.Fatal(err) - } - expect(deviceDir{path: newDir, set: "default"}) - - // Deleted and created again, the device is new again: it was forgotten. - if err := os.Remove(newDir); err != nil { - t.Fatal(err) - } - time.Sleep(50 * time.Millisecond) - if err := os.Mkdir(newDir, 0o755); err != nil { - t.Fatal(err) - } - expect(deviceDir{path: newDir, set: "default"}) - - // The missing set directory appears with a device already in it. - if err := os.MkdirAll(filepath.Join(missing, "CLONE"), 0o755); err != nil { - t.Fatal(err) - } - expect(deviceDir{path: filepath.Join(missing, "CLONE"), set: "testing"}) - - cancel() - select { - case <-done: - case <-time.After(time.Second): - t.Fatal("the watch did not stop when ctx was cancelled") - } -} diff --git a/watch_dirs_other.go b/watch_dirs_other.go deleted file mode 100644 index ec6eeaa..0000000 --- a/watch_dirs_other.go +++ /dev/null @@ -1,14 +0,0 @@ -//go:build !darwin - -package simslim - -import ( - "context" - "time" -) - -// watchDeviceDirs has no kqueue to watch with off macOS, where simslim does not -// run anyway; the scan alone finds new devices. -func watchDeviceDirs(ctx context.Context, setDirs map[string]string, retry time.Duration, created func(deviceDir)) { - <-ctx.Done() -} diff --git a/watch_test.go b/watch_test.go deleted file mode 100644 index f46a255..0000000 --- a/watch_test.go +++ /dev/null @@ -1,541 +0,0 @@ -package simslim - -import ( - "context" - "errors" - "os" - "path/filepath" - "reflect" - "slices" - "strings" - "sync" - "testing" - "time" -) - -const ( - bootedClone = `{"devices":{"com.apple.CoreSimulator.SimRuntime.iOS-26-1":[{"udid":"AAAA","name":"clone-1","state":"Booted","isAvailable":true,"dataPath":"/tmp/a"}]}}` - shutdownClone = `{"devices":{"com.apple.CoreSimulator.SimRuntime.iOS-26-1":[{"udid":"AAAA","name":"clone-1","state":"Shutdown","isAvailable":true,"dataPath":"/tmp/a"}]}}` - bootedAndStoppedPair = `{"devices":{"com.apple.CoreSimulator.SimRuntime.iOS-26-1":[{"udid":"AAAA","name":"clone-1","state":"Booted","isAvailable":true,"dataPath":"/tmp/a"},{"udid":"BBBB","name":"clone-2","state":"Shutdown","isAvailable":true,"dataPath":"/tmp/b"}]}}` -) - -// fakeDeviceList puts a fake xcrun on PATH that serves the device list from a -// file, and returns the function that rewrites it so a test can change a -// device's state between scans. -func fakeDeviceList(t *testing.T, devices string) func(string) { - t.Helper() - dir := t.TempDir() - statePath := filepath.Join(dir, "devices.json") - xcrunPath := filepath.Join(dir, "xcrun") - script := `#!/bin/sh -if [ "$*" = "simctl list devices -j" ]; then - cat "$SIMSLIM_FAKE_DEVICES" - exit 0 -fi -exit 0 -` - if err := os.WriteFile(xcrunPath, []byte(script), 0o755); err != nil { - t.Fatal(err) - } - t.Setenv("PATH", dir+string(os.PathListSeparator)+os.Getenv("PATH")) - t.Setenv("SIMSLIM_FAKE_DEVICES", statePath) - rewrite := func(devices string) { - t.Helper() - if err := os.WriteFile(statePath, []byte(devices), 0o644); err != nil { - t.Fatal(err) - } - } - rewrite(devices) - return rewrite -} - -func newTestWatcher(slim slimStrategy, report Reporter) *watcher { - return &watcher{report: report, slim: slim, passes: map[string]*slimPass{}, seeded: map[string]bool{}} -} - -// TestWatchSlimsEachBootedDeviceOnce verifies the scan slims a booted device -// exactly once and never touches a shutdown one, so a steady poll does not -// re-slim clones it already handled. -func TestWatchSlimsEachBootedDeviceOnce(t *testing.T) { - fakeDeviceList(t, bootedAndStoppedPair) - - var mu sync.Mutex - slimmed := map[string]int{} - fake := func(_ context.Context, _, udid string, _ Profile, _ Reporter) (bool, error) { - mu.Lock() - slimmed[udid]++ - mu.Unlock() - return true, nil - } - - w := newTestWatcher(fake, nil) - for i := 0; i < 3; i++ { // repeated scans must not re-slim - w.scan(context.Background()) - w.wg.Wait() - } - - mu.Lock() - defer mu.Unlock() - if slimmed["AAAA"] != 1 { - t.Fatalf("booted device slimmed %d times, want 1", slimmed["AAAA"]) - } - if slimmed["BBBB"] != 0 { - t.Fatalf("shutdown device slimmed %d times, want 0", slimmed["BBBB"]) - } -} - -// TestWatchReslimsDeviceAfterShutdown covers the boot session the no-reboot -// slim lives in: on iOS below 18.5 a device that shuts down comes back stock, -// so watch must slim it again instead of skipping it for the rest of the run. -func TestWatchReslimsDeviceAfterShutdown(t *testing.T) { - rewrite := fakeDeviceList(t, bootedClone) - - var mu sync.Mutex - slims := 0 - fake := func(_ context.Context, _, _ string, _ Profile, _ Reporter) (bool, error) { - mu.Lock() - slims++ - mu.Unlock() - return true, nil - } - - w := newTestWatcher(fake, nil) - for _, devices := range []string{bootedClone, shutdownClone, bootedClone} { - rewrite(devices) - w.scan(context.Background()) - w.wg.Wait() - } - - mu.Lock() - defer mu.Unlock() - if slims != 2 { - t.Fatalf("device slimmed %d times across a shutdown and a second boot, want 2", slims) - } -} - -// TestWatchRetriesSlimAfterError verifies a failed slim is retried on the next -// scan: a transient launchctl failure must not leave that clone stock for the -// whole test run. A slim that succeeds is still never repeated. -func TestWatchRetriesSlimAfterError(t *testing.T) { - fakeDeviceList(t, bootedClone) - - var mu sync.Mutex - attempts := 0 - fake := func(_ context.Context, _, _ string, _ Profile, _ Reporter) (bool, error) { - mu.Lock() - attempts++ - first := attempts == 1 - mu.Unlock() - if first { - return false, errors.New("launchctl disable failed") - } - return true, nil - } - - w := newTestWatcher(fake, nil) - for i := 0; i < 3; i++ { - w.scan(context.Background()) - w.wg.Wait() - } - - mu.Lock() - defer mu.Unlock() - if attempts != 2 { - t.Fatalf("slim attempted %d times, want 2 (one failure, one retry)", attempts) - } -} - -// TestWatchPrefixesDeviceProgress verifies the per-device messages of the slim -// reach the caller, tagged with the UDID they came from. -func TestWatchPrefixesDeviceProgress(t *testing.T) { - fakeDeviceList(t, bootedClone) - - var mu sync.Mutex - var lines []string - report := Reporter(func(msg string) { - mu.Lock() - lines = append(lines, msg) - mu.Unlock() - }) - fake := func(_ context.Context, _, _ string, _ Profile, deviceReport Reporter) (bool, error) { - deviceReport.report("Leaving 3 services disabled beyond this profile.") - return true, nil - } - - w := newTestWatcher(fake, report) - w.scan(context.Background()) - w.wg.Wait() - - mu.Lock() - defer mu.Unlock() - const want = "watch: AAAA: Leaving 3 services disabled beyond this profile." - if !slices.Contains(lines, want) { - t.Fatalf("reported lines = %q, want one %q", lines, want) - } -} - -// TestWatchWaitsForInFlightSlims verifies Watch does not return while a slim is -// still running, so an importer holds no goroutine it cannot see. -func TestWatchWaitsForInFlightSlims(t *testing.T) { - fakeDeviceList(t, bootedClone) - - started := make(chan struct{}, 1) - release := make(chan struct{}) - fake := func(_ context.Context, _, _ string, _ Profile, _ Reporter) (bool, error) { - started <- struct{}{} - <-release - return true, nil - } - - ctx, cancel := context.WithCancel(context.Background()) - defer cancel() - returned := make(chan error, 1) - go func() { returned <- watch(ctx, Profile{}, time.Millisecond, nil, nil, fake) }() - - <-started - cancel() - select { - case <-returned: - t.Fatal("watch returned while a slim was still in flight") - case <-time.After(50 * time.Millisecond): - } - - close(release) - select { - case err := <-returned: - if err != nil { - t.Fatalf("watch() = %v, want nil", err) - } - case <-time.After(2 * time.Second): - t.Fatal("watch did not return after the in-flight slim finished") - } -} - -// TestWatchSeedsShutdownDeviceBeforeBoot verifies a shut-down device is slimmed -// ahead of its boot once, not on every scan, is handed to the after-boot slim -// when it boots, and is checked again after its next shutdown. -func TestWatchSeedsShutdownDeviceBeforeBoot(t *testing.T) { - rewrite := fakeDeviceList(t, shutdownClone) - - var mu sync.Mutex - slims := 0 - fake := func(_ context.Context, _, _ string, _ Profile, _ Reporter) (bool, error) { - mu.Lock() - slims++ - mu.Unlock() - return true, nil - } - var seeds []string - w := newTestWatcher(fake, nil) - w.preslim = func(d Device, _ Profile) (int, error) { - seeds = append(seeds, d.UDID+" "+d.State) - return 3, nil - } - for _, devices := range []string{shutdownClone, shutdownClone, bootedClone, shutdownClone, shutdownClone} { - rewrite(devices) - w.scan(context.Background()) - w.wg.Wait() - } - - if want := []string{"AAAA Shutdown", "AAAA Shutdown"}; !slices.Equal(seeds, want) { - t.Fatalf("seeded %q, want %q (once per shutdown)", seeds, want) - } - mu.Lock() - defer mu.Unlock() - if slims != 1 { - t.Fatalf("after-boot slim ran %d times, want 1", slims) - } -} - -// TestWatchRetriesSeedAfterError verifies a store that could not be written is -// tried again on the next scan. -func TestWatchRetriesSeedAfterError(t *testing.T) { - fakeDeviceList(t, shutdownClone) - - attempts := 0 - w := newTestWatcher(nil, nil) - w.preslim = func(Device, Profile) (int, error) { - attempts++ - if attempts == 1 { - return 0, errors.New("read-only store") - } - return 0, nil - } - for i := 0; i < 3; i++ { - w.scan(context.Background()) - } - if attempts != 2 { - t.Fatalf("seed attempted %d times, want 2 (one failure, one retry)", attempts) - } -} - -// TestPreslimDeviceAddsOnlyDisables verifies the store gains the profile's -// disables and nothing else: an excepted service someone disabled stays -// disabled, the runtime's own entries survive, and a second pass is a no-op. -func TestPreslimDeviceAddsOnlyDisables(t *testing.T) { - root := useTempStoreRoot(t) - p, err := BuildProfile("", "store,icloud", "") - if err != nil { - t.Fatal(err) - } - var excepted string - for _, c := range Categories { - if c.ID == "store" { - excepted = c.Labels[0] - } - } - if err := writeDisabledStore("AAAA", []string{excepted}, []string{"com.example.runtime-own"}); err != nil { - t.Fatal(err) - } - d := Device{UDID: "AAAA", State: "Shutdown", Platform: "iOS", OSVersion: "26.5"} - - n, err := preslimDevice(d, p) - if err != nil { - t.Fatalf("preslimDevice() error = %v", err) - } - desired := p.DesiredForDevice(d) - if n != len(desired) { - t.Fatalf("preslimDevice() added %d, want %d", n, len(desired)) - } - entries, err := readStoreEntries("AAAA") - if err != nil { - t.Fatal(err) - } - for label := range desired { - if !entries[label] { - t.Errorf("%s not disabled in the store", label) - } - } - if !entries[excepted] { - t.Errorf("excepted %s was re-enabled; only `simslim off` may do that", excepted) - } - if off, ok := entries["com.example.runtime-own"]; !ok || off { - t.Errorf("runtime's own enable entry = %v, %v; want kept as enabled", off, ok) - } - if n, err := preslimDevice(d, p); err != nil || n != 0 { - t.Fatalf("second preslimDevice() = %d, %v; want 0, nil", n, err) - } - if _, err := os.Stat(filepath.Join(root, "com.apple.CoreSimulator.SimDevice.AAAA", "disabled.plist")); err != nil { - t.Fatalf("store not at the launchd_sim path: %v", err) - } -} - -// TestPreslimDeviceLeavesOtherDevicesAlone verifies a booted device and a -// runtime that cannot persist overrides get no store. -func TestPreslimDeviceLeavesOtherDevicesAlone(t *testing.T) { - useTempStoreRoot(t) - for _, d := range []Device{ - {UDID: "BOOTED", State: "Booted", OSVersion: "26.5"}, - {UDID: "OLD", State: "Shutdown", OSVersion: "18.3"}, - } { - if n, err := preslimDevice(d, Profile{}); err != nil || n != 0 { - t.Fatalf("preslimDevice(%s) = %d, %v; want 0, nil", d.UDID, n, err) - } - if _, err := os.Stat(disabledStorePath(d.UDID)); !errors.Is(err, os.ErrNotExist) { - t.Fatalf("store written for %s: %v", d.UDID, err) - } - } -} - -const newDevicePlist = ` - - - - UDID - CCCC - deviceType - com.apple.CoreSimulator.SimDeviceType.iPhone-17 - isDeleted - - name - sim-1-a - runtime - com.apple.CoreSimulator.SimRuntime.iOS-26-5 - state - 1 - - -` - -// TestSeedNewReadsDevicePlist verifies a new device is slimmed from its own -// device.plist, without a simctl listing, once the file appears. -func TestSeedNewReadsDevicePlist(t *testing.T) { - dir := filepath.Join(t.TempDir(), "CCCC") - if err := os.Mkdir(dir, 0o755); err != nil { - t.Fatal(err) - } - var seeds []Device - w := newTestWatcher(nil, nil) - w.preslim = func(d Device, _ Profile) (int, error) { - seeds = append(seeds, d) - return 0, nil - } - go func() { - time.Sleep(30 * time.Millisecond) // simctl create writes device.plist after the directory - os.WriteFile(filepath.Join(dir, "device.plist"), []byte(newDevicePlist), 0o644) - }() - w.seedNew(context.Background(), deviceDir{path: dir, set: "default"}) - - want := Device{UDID: "CCCC", State: "Shutdown", Platform: "iOS", OSVersion: "26.5", Set: "default", DataPath: filepath.Join(dir, "data"), RuntimeID: "com.apple.CoreSimulator.SimRuntime.iOS-26-5"} - if len(seeds) != 1 || seeds[0] != want { - t.Fatalf("seeded %+v, want [%+v]", seeds, want) - } -} - -// TestWatcherPruneDropsDeletedDevices verifies a deleted device, such as a -// finished parallel-testing clone, leaves neither a pass nor seeded, and -// cancels a pass still running for it. -func TestWatcherPruneDropsDeletedDevices(t *testing.T) { - gone, cancelGone := context.WithCancel(context.Background()) - keep := &slimPass{cancel: func() {}} - w := &watcher{ - passes: map[string]*slimPass{"KEEP": keep, "GONE": {cancel: cancelGone}}, - seeded: map[string]bool{"KEEP2": true, "GONE2": true}, - } - w.prune([]Device{{UDID: "KEEP"}, {UDID: "KEEP2"}}) - if want := map[string]*slimPass{"KEEP": keep}; !reflect.DeepEqual(w.passes, want) { - t.Fatalf("passes = %v, want %v", w.passes, want) - } - if gone.Err() == nil { - t.Fatal("a deleted device's pass was not cancelled") - } - if want := map[string]bool{"KEEP2": true}; !reflect.DeepEqual(w.seeded, want) { - t.Fatalf("seeded = %v, want %v", w.seeded, want) - } -} - -// eventLog collects watcher events; the watcher calls it from several goroutines. -type eventLog struct { - mu sync.Mutex - events []string -} - -func (l *eventLog) add(e WatchEvent) { - l.mu.Lock() - l.events = append(l.events, e.Event+" "+e.UDID) - l.mu.Unlock() -} - -func (l *eventLog) list() []string { - l.mu.Lock() - defer l.mu.Unlock() - return slices.Clone(l.events) -} - -// TestWatchCancelsPassWhenDeviceShutsDown covers a device shut down mid-pass and -// booted again: the old pass must stop instead of retrying into the new boot, -// where it would disable services a wrapper enabled after the new pass. -func TestWatchCancelsPassWhenDeviceShutsDown(t *testing.T) { - rewrite := fakeDeviceList(t, bootedClone) - - started := make(chan struct{}) - var mu sync.Mutex - calls := 0 - fake := func(ctx context.Context, _, _ string, _ Profile, _ Reporter) (bool, error) { - mu.Lock() - calls++ - first := calls == 1 - mu.Unlock() - if first { - close(started) - <-ctx.Done() // a slow first pass, like one retrying launchctl - return false, ctx.Err() - } - return true, nil - } - - var log eventLog - w := newTestWatcher(fake, nil) - w.events = log.add - w.scan(context.Background()) - <-started - rewrite(shutdownClone) - w.scan(context.Background()) - w.wg.Wait() // returns only because the shutdown cancelled the first pass - rewrite(bootedClone) - w.scan(context.Background()) - w.wg.Wait() - - want := []string{"slimming AAAA", "stopped AAAA", "slimming AAAA", "slimmed AAAA"} - if got := log.list(); !reflect.DeepEqual(got, want) { - t.Fatalf("events = %q, want %q", got, want) - } -} - -// TestWatchStalePassKeepsNewBootClaimed verifies a pass that outlived its boot -// and then fails neither reports failed nor drops the newer boot's claim, which -// would start a third pass on a device the newer pass already slimmed. -func TestWatchStalePassKeepsNewBootClaimed(t *testing.T) { - rewrite := fakeDeviceList(t, bootedClone) - - started := make(chan struct{}) - release := make(chan struct{}) - var mu sync.Mutex - calls := 0 - fake := func(_ context.Context, _, _ string, _ Profile, _ Reporter) (bool, error) { - mu.Lock() - calls++ - first := calls == 1 - mu.Unlock() - if first { - close(started) - <-release // ignores its cancel until a spawn returns - return false, errors.New("launchctl disable failed") - } - return true, nil - } - - var log eventLog - w := newTestWatcher(fake, nil) - w.events = log.add - w.scan(context.Background()) - <-started - rewrite(shutdownClone) - w.scan(context.Background()) - rewrite(bootedClone) - w.scan(context.Background()) - for !slices.Contains(log.list(), "slimmed AAAA") { - time.Sleep(time.Millisecond) - } - close(release) - w.wg.Wait() - w.scan(context.Background()) - w.wg.Wait() - - mu.Lock() - defer mu.Unlock() - if calls != 2 { - t.Fatalf("slim ran %d times, want 2 (one per boot)", calls) - } - want := []string{"slimming AAAA", "slimming AAAA", "slimmed AAAA", "stopped AAAA"} - if got := log.list(); !reflect.DeepEqual(got, want) { - t.Fatalf("events = %q, want %q", got, want) - } -} - -// TestWatchSeedsDeviceScannedMidShutdown covers a scan that lands while -// `simctl shutdown` is still running: the device is not seeded yet, so the next -// scan, which sees it Shutdown, must seed it instead of skipping it. -func TestWatchSeedsDeviceScannedMidShutdown(t *testing.T) { - rewrite := fakeDeviceList(t, strings.Replace(shutdownClone, `"Shutdown"`, `"Shutting Down"`, 1)) - - var mu sync.Mutex - var states []string - w := newTestWatcher(nil, nil) - w.preslim = func(d Device, _ Profile) (int, error) { - mu.Lock() - states = append(states, d.State) - mu.Unlock() - return 1, nil - } - w.scan(context.Background()) - rewrite(shutdownClone) - w.scan(context.Background()) - w.scan(context.Background()) - - mu.Lock() - defer mu.Unlock() - if want := []string{"Shutdown"}; !reflect.DeepEqual(states, want) { - t.Fatalf("seeded in states %q, want %q (once, after the shutdown finished)", states, want) - } -}