diff --git a/src/drivers/android/AGENTS.md b/src/drivers/android/AGENTS.md index 5d64ab70e..1bbbe6835 100644 --- a/src/drivers/android/AGENTS.md +++ b/src/drivers/android/AGENTS.md @@ -70,11 +70,13 @@ Boot — `makeReady` (per-device lock): Reclaim — `reclaim`: - `full` → shut down; wipe on the next `makeReady`. Returns `shutdown` / `wipe`. -- `standard`, hash still matches → `emu avd snapshot load` → readiness → mark. Returns `ready` / `snapshot`. +- `standard`, hash still matches → ownership probe (below), then `emu avd snapshot load` → readiness → mark. Returns `ready` / `snapshot`. - Hash changed or load failed → as `full`. - Physical → uninstall every user app not on the enrollment list. Returns `ready` / `uninstall`. -`shutdown`: `adb emu kill`, wait, SIGKILL. `destroy`: kills only an emulator this process +Ownership gate: before any `emu kill` or snapshot load, `adb emu avd path` (5 s timeout, asked every time, never cached) must name this device's own AVD directory; unreachable, timed out or another path → nothing is sent (a snapshot reclaim then shuts down and wipes). + +`shutdown`: gate, then `adb emu kill`, wait, SIGKILL. `destroy`: kills only an emulator this process started, then `avdmanager delete avd`, frees the port. `listManaged`: `/*.avd` + `adb devices` + `ro.boot.qemu.avd_name` per serial; only root members count. @@ -143,8 +145,6 @@ Reads only: the user's AVD home, devices.xml, the SDK. server with no record is `occupied`: find it with `lsof`, or move `drivers.android.adbServerPort` (one per instance). - **A physical command can restart a 5037 server of another protocol (ADR 0022 §5).** One started between the gate and the command is restarted by adb's client. Run every adb on the host from one platform-tools. -- **Port checks are partial.** After a restart `shutdown` sends `emu kill` to the stored serial - unchecked; reclaim's `snapshot load` goes to the serial before readiness checks it. A port - handed out but not yet booted reads free to another instance. +- **Port checks are partial.** A port handed out but not yet booted reads free to another instance. - **Android diagnostics are dropped.** `onDiagnostic` (`snapshot-cold-boot`, unreadable devices.xml) is not wired in `daemon/main.ts`. diff --git a/src/drivers/android/index.test.ts b/src/drivers/android/index.test.ts index c2818bc6b..7ed374d5d 100644 --- a/src/drivers/android/index.test.ts +++ b/src/drivers/android/index.test.ts @@ -541,7 +541,10 @@ describe("AndroidDriver", () => { */ it("leaves no timer armed once each shutdown has seen its emulator exit", async () => { const harness = await provisionedHarness({ - afterwards: [processResult(binaries.adb, ["-s", "emulator-5586", "emu", "kill"])], + afterwards: [ + avdPathExpectation("emulator-5586"), + processResult(binaries.adb, ["-s", "emulator-5586", "emu", "kill"]), + ], }); const ready = await harness.driver.makeReady(harness.device); const launch = harness.runner.calls.findLastIndex( @@ -559,7 +562,10 @@ describe("AndroidDriver", () => { it("kills an emulator that has not exited within the readiness timeout of a shutdown", async () => { const harness = await provisionedHarness({ - afterwards: [processResult(binaries.adb, ["-s", "emulator-5586", "emu", "kill"])], + afterwards: [ + avdPathExpectation("emulator-5586"), + processResult(binaries.adb, ["-s", "emulator-5586", "emu", "kill"]), + ], readinessTimeoutMs: 2_000, }); const ready = await harness.driver.makeReady(harness.device); @@ -584,7 +590,10 @@ describe("AndroidDriver", () => { it("leaves no timer armed when waiting for the emulator to exit fails", async () => { const harness = await provisionedHarness({ - afterwards: [processResult(binaries.adb, ["-s", "emulator-5586", "emu", "kill"])], + afterwards: [ + avdPathExpectation("emulator-5586"), + processResult(binaries.adb, ["-s", "emulator-5586", "emu", "kill"]), + ], }); const ready = await harness.driver.makeReady(harness.device); const launch = harness.runner.calls.findLastIndex( @@ -763,6 +772,7 @@ describe("AndroidDriver", () => { const restartedRunner = new ScriptedProcessRunner([ processResult(binaries.emulator, ["-version"], "Android emulator version 36.1.9"), + avdPathExpectation("emulator-5586"), processResult( binaries.adb, ["-s", "emulator-5586", "emu", "avd", "snapshot", "load", "simlock_clean_baseline"], @@ -3880,6 +3890,94 @@ describe("AndroidDriver emulator registration", () => { }); describe("AndroidDriver console ports across a restart", () => { + it.each(["shutdown", "full reclaim", "standard reclaim"] as const)( + "%s after a restart sends neither kill nor snapshot load to another device on the stored serial (#284)", + async (operation) => { + const spec = { + physical: false, + model: "Pixel 5", + osVersion: "34", + platform: "android", + } as const; + const filesystem = await androidFilesystem(); + const host = new EmulatorHost(filesystem); + const before = await createDriver(filesystem, host.runner(), { ids: ["one"] }); + await before.resolveSpec(spec); + const stopped = await before.makeReady(await before.provision(spec)); + await before.shutdown(stopped); + + const runner = new RecordingRunner(host.runner()); + const after = await createDriver(filesystem, runner, { ids: ["two"] }); + await after.resolveSpec(spec); + const running = await after.makeReady(await after.provision(spec)); + expect(running.address).toBe(stopped.address); + expect(host.avdAnswering(running.address)).toBe("simlock_two"); + const callStart = runner.calls.length; + + const action = + operation === "shutdown" + ? after.shutdown(stopped) + : after.reclaim(stopped, { + clean: operation === "full reclaim" ? "full" : "standard", + }); + await action.then(() => undefined, driverCrashMessage); + + expect({ + running: host.avdAnswering(running.address), + mutations: runner.calls + .slice(callStart) + .filter( + (call) => + call.command === binaries.adb && + call.args[1] === running.address && + (call.args.slice(2).join(" ") === "emu kill" || + call.args.slice(2, 6).join(" ") === "emu avd snapshot load"), + ) + .map((call) => call.args), + }).toEqual({ running: "simlock_two", mutations: [] }); + }, + ); + + it("sends no kill when the stored serial's identity cannot be read, and gives the probe a timeout (#284)", async () => { + const spec = { + physical: false, + model: "Pixel 5", + osVersion: "34", + platform: "android", + } as const; + const filesystem = await androidFilesystem(); + const host = new EmulatorHost(filesystem); + const before = await createDriver(filesystem, host.runner(), { ids: ["one"] }); + await before.resolveSpec(spec); + const stopped = await before.makeReady(await before.provision(spec)); + await before.shutdown(stopped); + + const inner = host.runner(); + let unreachable = false; + const runner = new RecordingRunner({ + run: async (command, args, options) => + unreachable && command === binaries.adb && args.slice(2).join(" ") === "emu avd path" + ? { code: 1, stderr: "unreachable", stdout: "" } + : await inner.run(command, args, options), + spawn: (...args) => inner.spawn(...args), + spawnStreaming: (...args) => inner.spawnStreaming(...args), + }); + const after = await createDriver(filesystem, runner, { ids: ["two"] }); + await after.resolveSpec(spec); + const running = await after.makeReady(await after.provision(spec)); + unreachable = true; + const callStart = runner.calls.length; + + await after.shutdown(stopped).catch(() => undefined); + + const calls = runner.calls.slice(callStart); + expect(calls.filter((call) => call.args.slice(2).join(" ") === "emu kill")).toEqual([]); + expect(host.avdAnswering(running.address)).toBe("simlock_two"); + expect( + calls.find((call) => call.args.slice(2).join(" ") === "emu avd path")?.options.timeoutMs, + ).toBeGreaterThan(0); + }); + it("readies a stopped device and one provisioned after a restart each at an address its own emulator answers (#52)", async () => { const spec = { physical: false, @@ -4011,6 +4109,7 @@ describe("AndroidDriver console port reservations", () => { "simlock_clean_baseline", ]), processResult(binaries.adb, ["-s", "emulator-5586", "emu", "avd", "snapshot", "list"], ""), + avdPathExpectation("emulator-5586"), processResult(binaries.adb, ["-s", "emulator-5586", "emu", "kill"]), processResult(binaries.avdmanager, ["delete", "avd", "-n", "simlock_one"]), ]); @@ -4039,6 +4138,7 @@ describe("AndroidDriver console port reservations", () => { await destroyed.catch(() => undefined); expect(runner.calls.slice(before).map((call) => call.args)).toEqual([ + ["-s", "emulator-5586", "emu", "avd", "path"], ["-s", "emulator-5586", "emu", "kill"], ["delete", "avd", "-n", "simlock_one"], ]); @@ -4550,6 +4650,7 @@ async function provisionedHarness( if (options.forBaselineReclaim === true) { expectations.push( processResult(binaries.emulator, ["-version"], "Android emulator version 36.1.9"), + avdPathExpectation("emulator-5586"), processResult( binaries.adb, ["-s", "emulator-5586", "emu", "avd", "snapshot", "load", "simlock_clean_baseline"], @@ -5851,6 +5952,7 @@ function baselineBuildExpectations(options: { "simlock_clean_baseline\n", ), processResult(binaries.emulator, ["-version"], "Android emulator version 36.1.9"), + avdPathExpectation("emulator-5586"), processResult(binaries.adb, ["-s", "emulator-5586", "emu", "kill"]), { hangs: true, @@ -6088,6 +6190,7 @@ const ADB_ANSWERS = new Map([ ["shell getprop init.svc.bootanim", "stopped\n"], ["emu avd snapshot save simlock_clean_baseline", "OK\n"], ["emu avd snapshot list", "simlock_clean_baseline\n"], + ["emu avd snapshot load simlock_clean_baseline", "OK\n"], ]); function consolePortOf(serial: string | undefined): number { diff --git a/src/drivers/android/index.ts b/src/drivers/android/index.ts index 93b5c997f..8a5a17d3a 100644 --- a/src/drivers/android/index.ts +++ b/src/drivers/android/index.ts @@ -119,6 +119,7 @@ const LICENSE_ACCEPT_ANSWERS = 100; // already settles shortly after `exit`, but this keeps a pathologically slow reap // from ever turning a "we already killed it" cleanup into an unbounded await. const SIGKILL_REAP_TIMEOUT_MS = 5_000; +const OWNERSHIP_PROBE_TIMEOUT_MS = 5_000; const SNAPSHOT_BOOT_ESTIMATE_MS = 4_000; // why: Conservative estimate for a system-image download+install -- reserved by `ComponentInstaller` // before `sdkmanager --install` ever starts, so a full disk fails fast instead of filling up @@ -235,12 +236,6 @@ interface DeviceState { */ port: number | undefined; snapshotExpected: boolean; - /** - * why: Set when the last readiness wait found another AVD's emulator answering on this device's - * serial, cleared when one finds the device's own: while set, nothing is sent to the serial, - * because whoever answers it is not this device. - */ - serialHeldByAnother?: boolean; } interface SystemImage { @@ -1016,6 +1011,14 @@ export class AndroidDriver implements Driver { return { state: "shutdown", strategy: "wipe" }; } + // why: After a restart the serial is from the registry and may answer as another device's + // emulator (#284), so the snapshot load goes only to an emulator proved to be this one's. + if (!(await this.#serialIsOwn(data))) { + await this.#shutdown(data, state); + state.needsWipe = true; + state.baselineCaptured = false; + return { state: "shutdown", strategy: "wipe" }; + } const restored = await this.#runOrThrow(this.#sdk.adb, [ "-s", data.serial, @@ -1859,19 +1862,17 @@ export class AndroidDriver implements Driver { * port is already held exits without answering, so the one that answers is whoever holds * the port -- another device, another Simlock instance, the user's own emulator. Refusing * here, before a mark or a baseline capture touches it, is what keeps a port collision from - * readying a device at another device's address; `serialHeldByAnother` then keeps the - * shutdown and destroy that follow a failed boot from sending it `emu kill`. The reported + * readying a device at another device's address; `#serialIsOwn` then keeps the + * shutdown and destroy that follow a failed boot from sending it `emu kill`, by asking the + * serial again each time. The reported * path is compared whole, and through `realpath` when the two spellings differ (an ancestor * symlink such as macOS's `/var` -> `/private/var`); anything unreadable fails closed. */ async #confirmAvdAnswers(data: AndroidDriverData): Promise { - const state = this.#stateFor(data); - state.serialHeldByAnother = true; const expected = `${this.#deviceRoot}/${data.avdName}.avd`; const result = await this.#runOrThrow(this.#sdk.adb, ["-s", data.serial, "emu", "avd", "path"]); const answered = answeredAvdPath(result.stdout); - if (answered === expected || (await this.#sameDirectory(answered, expected))) { - state.serialHeldByAnother = false; + if (await this.#isOwnAvdPath(answered, expected)) { return; } throw new DriverCrashError( @@ -1879,6 +1880,33 @@ export class AndroidDriver implements Driver { ); } + /** + * why: The gate before any emulator mutation (`emu kill`, snapshot load): asks the emulator on the + * serial for its AVD path, bounded by a timeout, on every call -- the answer is never kept, + * because the serial can change hands between calls. An unreachable, timed-out or unreadable + * answer is "not ours" (fail closed), so nothing is sent. + */ + async #serialIsOwn(data: AndroidDriverData): Promise { + try { + const result = await this.#processRunner.run( + this.#sdk.adb, + ["-s", data.serial, "emu", "avd", "path"], + { env: this.#env(), timeoutMs: OWNERSHIP_PROBE_TIMEOUT_MS }, + ); + if (result.code !== 0) return false; + return await this.#isOwnAvdPath( + answeredAvdPath(result.stdout), + `${this.#deviceRoot}/${data.avdName}.avd`, + ); + } catch { + return false; + } + } + + async #isOwnAvdPath(answered: string, expected: string): Promise { + return answered === expected || (await this.#sameDirectory(answered, expected)); + } + async #sameDirectory(left: string, right: string): Promise { if (!isAbsolute(left)) return false; try { @@ -2008,7 +2036,7 @@ export class AndroidDriver implements Driver { } async #shutdown(data: AndroidDriverData, state: DeviceState): Promise { - if (data.port > 0 && state.serialHeldByAnother !== true) { + if (data.port > 0 && (await this.#serialIsOwn(data))) { await this.#processRunner.run(this.#sdk.adb, ["-s", data.serial, "emu", "kill"], { env: this.#env(), });