diff --git a/CLAUDE.md b/CLAUDE.md index 738c59f..9d735e9 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -109,6 +109,14 @@ 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 `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 +(`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 +caught by the no-reboot slim at boot, which stays as the read-back and fallback. **Live enable/disable.** `live.go` holds `EnableServices`/`DisableServices` (`simslim enable`/`disable`), which act on a booted simulator only and keep no diff --git a/README.md b/README.md index 65260fe..0d7b0ba 100644 --- a/README.md +++ b/README.md @@ -323,14 +323,33 @@ simslim enable icloud --save dev.json # on now, and in dev.json simslim watch --profile dev.json # keeps iCloud on at every boot ``` -### Slimming parallel-testing clones - -`xcodebuild` parallel testing creates a fresh clone per worker in its own device -set, runs the tests, and deletes the clones when the run ends. The clones are -created stock, and disable overrides do not survive `simctl clone`, so there is -no device to slim ahead of time. `simslim watch` closes that gap: it polls the -device sets and slims each simulator no-reboot the moment it boots, then leaves -it alone until it boots again. A clone slimmed a few seconds into a multi-minute +### Slimming every new simulator, from its first boot + +`simslim watch` keeps every simulator slim without a command per device. A +simulator that is shut down, on a runtime that persists overrides (iOS/tvOS +18.5, watchOS 11.5, visionOS 2.5 or newer), is slimmed before it boots: watch +writes the profile's disable overrides into its launchd store, so its next boot +starts none of those daemons. That includes a simulator's very first boot: +watch follows the device-set directories with kqueue and seeds a new device from +its own `device.plist` within milliseconds of `simctl create`, without waiting +for `simctl list`. A boot that starts before the seed lands is slimmed as it +boots instead, and comes up slim from its next boot. A script that creates and +boots a simulator should not race watch: run +`simslim on --preserve-boot-state` between `simctl create` and the boot, +which slims the device and leaves it shut down. +Watch only ever adds disables there, as it does after boot: a service disabled +beyond the profile stays disabled until `simslim off`. + +This changes what watch does on startup: it now writes the slim profile into +every shut-down simulator in the watched sets, not only the ones that boot while +it runs. Run `simslim off ` to bring one back to stock. + +Every simulator is also slimmed no-reboot the moment it boots, which reads the +device back and covers whatever booted before watch could seed it. That is the +only hook for `xcodebuild` parallel-testing clones: parallel testing creates a +fresh clone per worker in its own device set, runs the tests, and deletes the +clones when the run ends. The clones are created stock, and disable overrides do +not survive `simctl clone`. A clone slimmed a few seconds into a multi-minute run keeps its freed memory for the rest of the run. A failed slim is retried on the next scan, and a device that shut down and booted again is slimmed again, because on older runtimes a no-reboot slim ends with the boot session. diff --git a/cmd/simslim/main.go b/cmd/simslim/main.go index 59b8508..d908399 100644 --- a/cmd/simslim/main.go +++ b/cmd/simslim/main.go @@ -833,10 +833,11 @@ func onNoReboot(ctx context.Context, device simslim.Device, p simslim.Profile, r return nil } -// cmdWatch slims every simulator no-reboot as it boots, until Ctrl-C. It is 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. +// 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 { @@ -844,7 +845,7 @@ func cmdWatch(ctx context.Context, cmd *cli.Command) error { } 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 no-reboot as it boots. Ctrl-C to stop.\n", strings.Join(sets, ", ")) + 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) } @@ -1098,8 +1099,11 @@ COMMANDS 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 no-reboot as it boots, until Ctrl-C. - The hook for xcodebuild parallel-testing clones, which are + 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 diff --git a/watch.go b/watch.go index d8879f3..3979599 100644 --- a/watch.go +++ b/watch.go @@ -2,7 +2,12 @@ package simslim import ( "context" + "encoding/xml" + "errors" "fmt" + "io" + "os" + "path/filepath" "sort" "sync" "time" @@ -11,18 +16,31 @@ import ( // 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) -// Watch slims each simulator no-reboot as it boots, then leaves it alone until -// it boots again. -// xcodebuild creates parallel-testing clones stock and deletes them per run, so -// no device exists to pre-slim: the only hook is to catch each clone once it -// boots. A clone slimmed a few seconds into a multi-minute run frees its -// background daemons for the rest of the run. Watch runs until ctx is cancelled +// 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 device in its own goroutine so one slow reconfigure does not delay +// 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 watch(ctx, p, interval, report, EnableSlimNoReboot) @@ -32,11 +50,29 @@ func watch(ctx context.Context, p Profile, interval time.Duration, report Report if interval <= 0 { interval = DefaultWatchInterval } - w := &watcher{p: p, report: report, slim: slim, seen: map[string]bool{}} + w := &watcher{p: p, report: report, slim: slim, preslim: preslimDevice, seen: map[string]bool{}, 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 { @@ -45,19 +81,141 @@ func watch(ctx context.Context, p Profile, interval time.Duration, report Report 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 the UDIDs already slimmed or in flight. The scan loop and the -// slim goroutines both mutate seen, so mu guards every access to it. +// watcher holds the 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 - slim slimStrategy - wg sync.WaitGroup - mu sync.Mutex - seen map[string]bool + p Profile + report Reporter + slim slimStrategy + preslim preslimStrategy + wg sync.WaitGroup + mu sync.Mutex + seen map[string]bool + seeded map[string]bool } func (w *watcher) scan(ctx context.Context) { @@ -67,14 +225,21 @@ func (w *watcher) scan(ctx context.Context) { 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() if !w.claim(d.UDID) { continue } @@ -95,6 +260,36 @@ func (w *watcher) scan(ctx context.Context) { } } +// 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 + } + 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)) +} + // claim reserves a UDID for this scan, reporting false when it is already // slimmed or in flight. func (w *watcher) claim(udid string) bool { @@ -107,6 +302,28 @@ func (w *watcher) claim(udid string) bool { return true } +// prune drops the UDIDs of deleted devices, such as finished parallel-testing +// clones, so seen 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 := range w.seen { + if !listed[udid] { + delete(w.seen, udid) + } + } + for udid := range w.seeded { + if !listed[udid] { + delete(w.seeded, udid) + } + } +} + func (w *watcher) forget(udid string) { w.mu.Lock() delete(w.seen, udid) diff --git a/watch_dirs_darwin.go b/watch_dirs_darwin.go new file mode 100644 index 0000000..412abac --- /dev/null +++ b/watch_dirs_darwin.go @@ -0,0 +1,114 @@ +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 new file mode 100644 index 0000000..551ef44 --- /dev/null +++ b/watch_dirs_darwin_test.go @@ -0,0 +1,72 @@ +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 new file mode 100644 index 0000000..ec6eeaa --- /dev/null +++ b/watch_dirs_other.go @@ -0,0 +1,14 @@ +//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 index 0bcbe95..eb83a34 100644 --- a/watch_test.go +++ b/watch_test.go @@ -5,6 +5,7 @@ import ( "errors" "os" "path/filepath" + "reflect" "slices" "sync" "testing" @@ -48,7 +49,7 @@ exit 0 } func newTestWatcher(slim slimStrategy, report Reporter) *watcher { - return &watcher{report: report, slim: slim, seen: map[string]bool{}} + return &watcher{report: report, slim: slim, seen: map[string]bool{}, seeded: map[string]bool{}} } // TestWatchSlimsEachBootedDeviceOnce verifies the scan slims a booted device @@ -208,3 +209,190 @@ func TestWatchWaitsForInFlightSlims(t *testing.T) { 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 seen nor seeded. +func TestWatcherPruneDropsDeletedDevices(t *testing.T) { + w := &watcher{ + seen: map[string]bool{"KEEP": true, "GONE": true}, + seeded: map[string]bool{"KEEP2": true, "GONE2": true}, + } + w.prune([]Device{{UDID: "KEEP"}, {UDID: "KEEP2"}}) + if want := map[string]bool{"KEEP": true}; !reflect.DeepEqual(w.seen, want) { + t.Fatalf("seen = %v, want %v", w.seen, want) + } + if want := map[string]bool{"KEEP2": true}; !reflect.DeepEqual(w.seeded, want) { + t.Fatalf("seeded = %v, want %v", w.seeded, want) + } +}