diff --git a/src/core/AGENTS.md b/src/core/AGENTS.md index d7e164bfb..b1d8f6343 100644 --- a/src/core/AGENTS.md +++ b/src/core/AGENTS.md @@ -106,7 +106,7 @@ Events: → `absent` `device.absence-detected`; `absent` → `reclaiming` `devic 9. **Physical** — `PhysicalEnrollment.add` refuses Simlock's own devices, reads `inspectPhysical`, writes `ready` with `enrolledApps`, or re-enrols under `enrollment`; `remove` unenrols. Busy: `DeviceBusyError`. 10. **Ownership** — `loadInstanceId` creates `instance.json` once (exclusive create, `0600`). `ensureOwnedRoot` - stages a root with `.simlock-owned.json` (instance id, platform), mode `0700`; doubt is `OwnedRootError`. + stages a root with `.simlock-owned.json` (instance id, platform), mode `0700`; doubt is `OwnedRootError`. With no `uid` (Windows) it checks neither owner nor mode, and a rename refused `EPERM` onto a root now there is a lost race. 11. **Components** — `ComponentInstaller`, the only caller of `installComponent`/`removeComponent`. One FIFO per platform; a call for the same component joins. At the front: `stillNeeded` → `findComponent` → `DiskSpaceGuard.reserve` (one guard, both platforms) → driver → record (lock) → diff --git a/src/core/device-root.test.ts b/src/core/device-root.test.ts index 9924f068c..91a7f635d 100644 --- a/src/core/device-root.test.ts +++ b/src/core/device-root.test.ts @@ -175,6 +175,31 @@ describe("ensureOwnedRoot", () => { await expect(filesystem.readdir(parent)).resolves.toEqual(["ios"]); }); + it.each(["EPERM", "EACCES"])( + "keeps a root another process published first when Windows refuses the rename with %s", + async (code) => { + const filesystem = new RefusingRenameFilesystem( + uid, + async (target) => { + await target.mkdirp(root); + await target.writeFileAtomic(markerPath, marker()); + }, + code, + ); + + await expect(ensure(filesystem)).resolves.toBe(root); + await expect(filesystem.readFile(markerPath)).resolves.toBe(marker()); + await expect(filesystem.readdir(parent)).resolves.toEqual(["ios"]); + }, + ); + + it("still refuses a root whose rename was refused with EPERM when nothing else published it", async () => { + const filesystem = new RefusingRenameFilesystem(uid, async () => undefined); + + await expect(refusal(filesystem)).resolves.toBe("unreadable"); + await expect(filesystem.exists(root)).resolves.toBe(false); + }); + it.each([ ["a relative one", "devices/ios"], ["one written against the home directory", "~/devices/ios"], @@ -275,6 +300,16 @@ describe("ensureOwnedRoot", () => { ).resolves.toBe(root); }); + it("accepts a root with any mode when the platform has no uids, since it has no mode bits either", async () => { + const filesystem = createFilesystem(); + await ensure(filesystem); + filesystem.defineAttributes(root, { mode: 0o666 }); + + await expect( + ensureOwnedRoot({ filesystem, idGenerator, instanceId, path: root, platform: "ios" }), + ).resolves.toBe(root); + }); + it.each([0o750, 0o770, 0o701])("refuses a root reachable beyond its owner (%s)", async (mode) => { const filesystem = createFilesystem(); await ensure(filesystem); @@ -461,6 +496,27 @@ class UmaskedFilesystem extends MemoryFilesystem { } } +/** why: Windows refuses renaming onto an existing directory with EPERM or EACCES; `before` decides whether another process published the root first. */ +class RefusingRenameFilesystem extends MemoryFilesystem { + constructor( + owner: number, + private readonly before: (target: MemoryFilesystem) => Promise, + private readonly code = "EPERM", + ) { + super(undefined, owner); + } + + async rename(from: string, to: string): Promise { + if (to !== root) return super.rename(from, to); + await this.before(this); + const error: NodeJS.ErrnoException = new Error( + `${this.code}: operation not permitted, rename '${from}' -> '${to}'`, + ); + error.code = this.code; + throw error; + } +} + /** * Reports the root as absent exactly once, so the first `mkdir` loses a race it could not * have seen coming -- the window every check-then-create has. diff --git a/src/core/device-root.ts b/src/core/device-root.ts index 5ae9de56d..71dd585aa 100644 --- a/src/core/device-root.ts +++ b/src/core/device-root.ts @@ -126,7 +126,7 @@ async function createRoot(context: RootContext): Promise { } catch (error: unknown) { await discard(filesystem, staging); - if (isOccupiedPathError(error)) { + if (isOccupiedPathError(error) || (await lostRaceOnWindows(context, error))) { return false; } @@ -171,7 +171,9 @@ async function validateRootDirectory(context: RootContext): Promise { throw rejected(context, "wrong-owner", `it is owned by uid ${details.uid}, not ${uid}`); } - if ((details.mode & 0o077) !== 0) { + // why: a platform with no uids (Windows) has no POSIX mode bits either: Node reports every + // writable directory there as 0o666, so the check would refuse every root it ever made. + if (uid !== undefined && (details.mode & 0o077) !== 0) { throw rejected( context, "wrong-permissions", @@ -375,6 +377,18 @@ function isMissingPathError(error: unknown): boolean { return errorCode(error) === "ENOENT"; } +/** + * why: Windows refuses to rename a directory onto one that exists with `EPERM` (or `EACCES`), not + * `EEXIST`, so two daemons starting at once would leave the loser refusing its own root. The same + * codes also mean a real permission problem, so the refusal is a lost race only when the root is + * there now; the caller then validates it like any root another process made first. + */ +async function lostRaceOnWindows(context: RootContext, error: unknown): Promise { + const code = errorCode(error); + if (code !== "EPERM" && code !== "EACCES") return false; + return (await pathDetails(context, context.root, "it")) !== undefined; +} + /** * why: `rename` reports an occupied destination three ways depending on the kernel and on what * is sitting there: a non-empty directory, a directory replaced by a file, or a plain diff --git a/src/drivers/android/AGENTS.md b/src/drivers/android/AGENTS.md index a2f506fa6..b9b7c5e81 100644 --- a/src/drivers/android/AGENTS.md +++ b/src/drivers/android/AGENTS.md @@ -28,7 +28,8 @@ Parent: [drivers](../AGENTS.md). Flows: [device selection](../../../docs/interna Start — `AndroidDriver.create`: -1. `locateSdk`: first of `ANDROID_HOME`, `ANDROID_SDK_ROOT`, `~/Library/Android/sdk` with +1. `locateSdk`: first of `ANDROID_HOME`, `ANDROID_SDK_ROOT`, `~/Library/Android/sdk` (on Windows + `%LOCALAPPDATA%\Android\Sdk`, and the tools are `adb.exe`, `emulator.exe`, `avdmanager.bat`, `sdkmanager.bat`) with `avdmanager` + `sdkmanager` (newest `cmdline-tools/*/bin`, else `tools/bin`), `emulator`, `platform-tools/adb`. None → `SdkMissingError`: Android absent, no rejection. 2. `ensureOwnedRoot`: the AVD home, default `$SIMLOCK_HOME/devices/android`. diff --git a/src/drivers/android/physical-handler.test.ts b/src/drivers/android/physical-handler.test.ts index 53cfd2977..82f4afff4 100644 --- a/src/drivers/android/physical-handler.test.ts +++ b/src/drivers/android/physical-handler.test.ts @@ -1604,3 +1604,70 @@ function sdkTool(name: "avdmanager" | "sdkmanager"): string { function scripted(command: string, args: readonly (string | RegExp)[], stdout = "") { return { match: { args, command }, result: { code: 0, stderr: "", stdout } }; } + +describe("Android physical handler on Windows", () => { + // why: adb on Windows lists no `usb:` path, which the driver surface cannot fake per host; + // the handler is built straight with `platform: "win32"`. + async function windowsHandler(listing: string, platform: NodeJS.Platform = "win32") { + const runner = new PhoneAdb([]); + runner.devicesOutput = listing; + const probe = new FakeTcpProbe([]); + probe.replyWith(VERSION_REPLY_41); + return new AndroidPhysicalHandler({ + adb, + baseEnv: { ANDROID_HOME: sdk }, + filesystem: await androidFilesystem(), + isBareShell: () => false, + platform, + processRunner: runner, + tcpProbe: probe, + }); + } + + const WINDOWS_LINE = `${PHONE} device product:a70qxtc model:SM_A705MN device:a70q transport_id:1`; + + it("enrols a phone adb lists with no usb: path, as adb on Windows lists every USB device", async () => { + const handler = await windowsHandler(devicesListing(WINDOWS_LINE)); + + await expect(handler.inspectPhysical(PHONE)).resolves.toMatchObject({ + driverDeviceId: PHONE, + enrollable: true, + }); + }); + + it("still refuses the same listing off Windows, where a USB device always has a usb: path", async () => { + const handler = await windowsHandler(devicesListing(WINDOWS_LINE), "linux"); + + await expect(handler.inspectPhysical(PHONE)).resolves.toMatchObject({ + enrollable: false, + reason: "network-only", + }); + }); + + it.each([ + ["win32", { driverDeviceId: PHONE, osVersion: "34", present: true }], + ["linux", { driverDeviceId: PHONE, present: false, reason: "not-present" }], + ] as const)( + "lists an enrolled phone with no usb: path on %s as the USB rule of that host says", + async (platform, expected) => { + const handler = await windowsHandler(devicesListing(WINDOWS_LINE), platform); + + await expect(handler.listPresentPhysical([PHONE])).resolves.toEqual([expected]); + }, + ); + + it.each([ + ["a host:port", "192.168.1.5:5555"], + ["an mDNS service", "adb-R58M123ABC-x1Yz2W._adb-tls-connect._tcp"], + ["an emulator", "emulator-5554"], + ])("refuses %s serial on Windows as network-only", async (_kind, serial) => { + const handler = await windowsHandler( + devicesListing(`${serial} device product:o1s transport_id:5`), + ); + + await expect(handler.inspectPhysical(serial)).resolves.toMatchObject({ + enrollable: false, + reason: "network-only", + }); + }); +}); diff --git a/src/drivers/android/physical-handler.ts b/src/drivers/android/physical-handler.ts index f68dcd748..b5fc1a40e 100644 --- a/src/drivers/android/physical-handler.ts +++ b/src/drivers/android/physical-handler.ts @@ -71,14 +71,18 @@ export class AndroidPhysicalHandler { readonly #env: NodeJS.ProcessEnv; readonly #processRunner: ProcessRunner; readonly #isBareShell: (args: readonly string[]) => boolean; + readonly #platform: NodeJS.Platform; constructor( options: Omit & { readonly baseEnv: NodeJS.ProcessEnv; // why: the driver's own test, so one place decides what the interactive shell is. readonly isBareShell: (args: readonly string[]) => boolean; + // why: how a USB transport is told apart depends on the host's adb; injected so Windows can be tested anywhere. + readonly platform?: NodeJS.Platform; }, ) { + this.#platform = options.platform ?? process.platform; this.#isBareShell = options.isBareShell; this.#adb = options.adb; this.#processRunner = options.processRunner; @@ -135,7 +139,7 @@ export class AndroidPhysicalHandler { if (listing.kind !== "ok") return this.#refusal(listing, "the device list (adb devices -l)"); const unusable = unenrollable( - parseDevices(listing.stdout).filter((entry) => entry.serial === id), + parseDevices(listing.stdout, this.#platform).filter((entry) => entry.serial === id), ); if (unusable !== undefined) return unusable; return this.#readDevice(id); @@ -166,7 +170,7 @@ export class AndroidPhysicalHandler { async listPresentPhysical(enrolledIds: readonly string[]): Promise { const listing = await this.#run(["devices", "-l"], READ_TIMEOUT_MS); - const entries = listing.kind === "ok" ? parseDevices(listing.stdout) : []; + const entries = listing.kind === "ok" ? parseDevices(listing.stdout, this.#platform) : []; const answers: PresentPhysical[] = []; for (const driverDeviceId of enrolledIds) { const usb = entries.filter((entry) => entry.serial === driverDeviceId && entry.usb); @@ -323,17 +327,29 @@ function failure(read: string, ran: Ran): Error { : new Error(`physical reclaim could not read ${read}`); } -function parseDevices(output: string): ListedTransport[] { +function parseDevices(output: string, platform: NodeJS.Platform): ListedTransport[] { const entries: ListedTransport[] = []; for (const line of output.split("\n")) { const tokens = line.trim().split(/\s+/); const [serial, state] = tokens; if (serial === undefined || state === undefined) continue; - entries.push({ serial, state, usb: tokens.some((token) => token.startsWith("usb:")) }); + const usb = + tokens.some((token) => token.startsWith("usb:")) || + (platform === "win32" && !isNetworkOrEmulatorSerial(serial)); + entries.push({ serial, state, usb }); } return entries; } +/** + * why: adb on Windows lists no `usb:` path for any transport, so there the serial tells the kinds + * apart: a network transport is `host:port` or an mDNS service name (`..._adb-tls-connect._tcp`), + * an emulator is `emulator-`, and anything else is a USB device. + */ +function isNetworkOrEmulatorSerial(serial: string): boolean { + return /:\d+$/.test(serial) || serial.includes("._tcp") || /^emulator-\d+$/.test(serial); +} + function unenrollable(matching: readonly ListedTransport[]): Refusal | undefined { const usb = matching.filter((entry) => entry.usb); if (usb.some((entry) => entry.state === "device")) return undefined; diff --git a/src/drivers/android/prerequisites.test.ts b/src/drivers/android/prerequisites.test.ts index 6eeabe28d..3993cb49d 100644 --- a/src/drivers/android/prerequisites.test.ts +++ b/src/drivers/android/prerequisites.test.ts @@ -43,6 +43,7 @@ function check(filesystem: MemoryFilesystem, runner: ScriptedProcessRunner) { env: { ANDROID_HOME: sdk }, filesystem, homeDirectory: home, + platform: "linux", processRunner: runner, }); } @@ -117,6 +118,7 @@ describe("androidPrerequisites", () => { env: { ANDROID_HOME: "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/nowhere/home", ANDROID_SDK_ROOT: "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/nowhere/root" }, filesystem: new MemoryFilesystem(), homeDirectory: home, + platform: "linux", processRunner: runner, }); @@ -153,6 +155,7 @@ describe("androidPrerequisites", () => { env: { ANDROID_HOME: "/stale-sdk" }, filesystem, homeDirectory: home, + platform: "linux", processRunner: runner, }); @@ -165,6 +168,7 @@ describe("androidPrerequisites", () => { env: { ANDROID_HOME: "/nowhere", ANDROID_SDK_ROOT: sdk }, filesystem, homeDirectory: home, + platform: "linux", processRunner: new ScriptedProcessRunner([SDKMANAGER_RUNS]), }); @@ -215,3 +219,77 @@ describe("androidPrerequisites", () => { await expect(check(await sdkFilesystem(), runner).check()).rejects.toThrow(/did not finish/); }); }); + +describe("androidPrerequisites on Windows", () => { + const winSdk = "/Users/me/AppData/Local/Android/Sdk"; + // why: differs from the home-directory fallback, so only a read LOCALAPPDATA finds this one. + const localSdk = "/Volumes/Data/Local/Android/Sdk"; + const winSdkmanager = `${winSdk}/cmdline-tools/latest/bin/sdkmanager.bat`; + const sdkmanagerIn = (root: string) => `${root}/cmdline-tools/latest/bin/sdkmanager.bat`; + + /** why: Android Studio installs `.exe` binaries and `.bat` tools on Windows, never the bare names. */ + async function windowsSdk(root = winSdk): Promise { + const filesystem = new MemoryFilesystem(); + await filesystem.mkdirp(root); + await writeFile(filesystem, sdkmanagerIn(root)); + await writeFile(filesystem, `${root}/cmdline-tools/latest/bin/avdmanager.bat`); + await writeFile(filesystem, `${root}/emulator/emulator.exe`); + await writeFile(filesystem, `${root}/platform-tools/adb.exe`); + return filesystem; + } + + function windowsCheck( + filesystem: MemoryFilesystem, + runner: ScriptedProcessRunner, + env: Readonly>, + ) { + return androidPrerequisites({ + env, + filesystem, + homeDirectory: "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/Users/me", + platform: "win32", + processRunner: runner, + }); + } + + const WINDOWS_SDKMANAGER_RUNS: ScriptedProcessExpectation = { + match: { args: ["--version"], command: winSdkmanager }, + result: { code: 0, stderr: "", stdout: "12.0\n" }, + }; + + it.each([ + ["ANDROID_HOME", { ANDROID_HOME: winSdk }, winSdk], + ["Android Studio's %LOCALAPPDATA% default", { LOCALAPPDATA: "/Volumes/Data/Local" }, localSdk], + ])( + "finds a complete SDK of .exe and .bat tools through %s and runs its sdkmanager.bat", + async (_source, env, root) => { + const sdkmanager = sdkmanagerIn(root); + const runner = new ScriptedProcessRunner([ + { ...WINDOWS_SDKMANAGER_RUNS, match: { args: ["--version"], command: sdkmanager } }, + ]); + + await expect(windowsCheck(await windowsSdk(root), runner, env).check()).resolves.toEqual([]); + expect(runner.calls.map((call) => [call.command, ...call.args])).toEqual([ + [sdkmanager, "--version"], + ]); + }, + ); + + it("reads a Windows SDK holding only the extensionless names as missing every tool", async () => { + const filesystem = new MemoryFilesystem(); + await filesystem.mkdirp(winSdk); + await writeFile(filesystem, `${winSdk}/cmdline-tools/latest/bin/sdkmanager`); + await writeFile(filesystem, `${winSdk}/cmdline-tools/latest/bin/avdmanager`); + await writeFile(filesystem, `${winSdk}/emulator/emulator`); + await writeFile(filesystem, `${winSdk}/platform-tools/adb`); + const runner = new ScriptedProcessRunner([]); + + const missing = await windowsCheck(filesystem, runner, { ANDROID_HOME: winSdk }).check(); + + expect(missing.map((finding) => finding.prerequisite)).toEqual([ + "android-cmdline-tools", + "android-emulator", + "android-platform-tools", + ]); + }); +}); diff --git a/src/drivers/android/prerequisites.ts b/src/drivers/android/prerequisites.ts index d2120789f..4a0f36e21 100644 --- a/src/drivers/android/prerequisites.ts +++ b/src/drivers/android/prerequisites.ts @@ -9,6 +9,8 @@ interface AndroidPrerequisitesOptions { readonly env: Readonly>; readonly filesystem: Filesystem; readonly homeDirectory: string; + /** why: the SDK's file names depend on the host (`adb.exe` on Windows); injected so either can be tested anywhere. */ + readonly platform?: NodeJS.Platform; readonly processRunner: ProcessRunner; } @@ -27,7 +29,13 @@ export function androidPrerequisites(options: AndroidPrerequisitesOptions): Prer async function missingAndroidPrerequisites( options: AndroidPrerequisitesOptions, ): Promise { - const location = await locateSdk(options.env, options.homeDirectory, options.filesystem); + const platform = options.platform ?? process.platform; + const location = await locateSdk( + options.env, + options.homeDirectory, + options.filesystem, + platform, + ); if (location.kind === "absent") { // One finding, not one per tool: with no SDK at all, every tool is missing for the same reason. return [ @@ -44,7 +52,7 @@ async function missingAndroidPrerequisites( // The SDK discovery runs, when it found one; otherwise the first root there is. const root = location.kind === "complete" ? location.paths.root : location.root; const missing: MissingPrerequisite[] = []; - const tools = await sdkToolBin(root, options.filesystem); + const tools = await sdkToolBin(root, options.filesystem, platform); if (tools === undefined) { missing.push({ message: `The Android SDK command-line tools (sdkmanager, avdmanager) are not in ${root}.`, @@ -54,14 +62,14 @@ async function missingAndroidPrerequisites( `${root}/cmdline-tools/latest; sdkmanager cannot install itself.`, }); } - if (!(await options.filesystem.exists(emulatorPath(root)))) { + if (!(await options.filesystem.exists(emulatorPath(root, platform)))) { missing.push({ message: `The Android emulator package is not installed in ${root}.`, prerequisite: "android-emulator", remedy: "Run `sdkmanager --install emulator`.", }); } - if (!(await options.filesystem.exists(adbPath(root)))) { + if (!(await options.filesystem.exists(adbPath(root, platform)))) { missing.push({ message: `The Android platform-tools package (adb) is not installed in ${root}.`, prerequisite: "android-platform-tools", diff --git a/src/drivers/android/sdk-paths.ts b/src/drivers/android/sdk-paths.ts index 121039666..44b41ba0f 100644 --- a/src/drivers/android/sdk-paths.ts +++ b/src/drivers/android/sdk-paths.ts @@ -13,14 +13,42 @@ export interface AndroidSdkPaths { readonly sdkmanager: string; } +/** + * why: The SDK's command-line tools are `.bat` scripts on Windows and its binaries `.exe`; a path + * without the extension is not a file there, so a complete SDK would read as missing every tool. + */ +function withWindowsExtension( + path: string, + platform: NodeJS.Platform, + extension: ".bat" | ".exe", +): string { + return platform === "win32" ? `${path}${extension}` : path; +} + +/** why: Android Studio installs the SDK under `%LOCALAPPDATA%` on Windows, so a machine with no `ANDROID_HOME` still finds it there. */ +function defaultSdkRoot( + env: Readonly>, + homeDirectory: string, + platform: NodeJS.Platform, +): string { + if (platform !== "win32") return `${homeDirectory}/Library/Android/sdk`; + const localAppData = env.LOCALAPPDATA; + return localAppData === undefined || localAppData === "" + ? `${homeDirectory}/AppData/Local/Android/Sdk` + : `${localAppData}/Android/Sdk`; +} + /** The SDK roots searched, in order: `ANDROID_HOME`, `ANDROID_SDK_ROOT`, then Android Studio's default. */ function sdkSearchRoots( env: Readonly>, homeDirectory: string, + platform: NodeJS.Platform, ): string[] { - return [env.ANDROID_HOME, env.ANDROID_SDK_ROOT, `${homeDirectory}/Library/Android/sdk`].filter( - (root): root is string => root !== undefined && root !== "", - ); + return [ + env.ANDROID_HOME, + env.ANDROID_SDK_ROOT, + defaultSdkRoot(env, homeDirectory, platform), + ].filter((root): root is string => root !== undefined && root !== ""); } /** @@ -38,14 +66,15 @@ export async function locateSdk( env: Readonly>, homeDirectory: string, filesystem: Filesystem, + platform: NodeJS.Platform = process.platform, ): Promise { - const searched = sdkSearchRoots(env, homeDirectory); + const searched = sdkSearchRoots(env, homeDirectory, platform); const directories: string[] = []; for (const root of searched) { if (await isDirectory(filesystem, root)) directories.push(root); } for (const root of directories) { - const paths = await sdkPathsAt(root, filesystem); + const paths = await sdkPathsAt(root, filesystem, platform); if (paths !== undefined) return { kind: "complete", paths }; } const first = directories[0]; @@ -63,22 +92,23 @@ async function isDirectory(filesystem: Filesystem, path: string): Promise { - const tools = await sdkToolBin(root, filesystem); - const emulator = emulatorPath(root); - const adb = adbPath(root); + const tools = await sdkToolBin(root, filesystem, platform); + const emulator = emulatorPath(root, platform); + const adb = adbPath(root, platform); if ( tools === undefined || !(await filesystem.exists(emulator)) || @@ -96,11 +126,12 @@ async function sdkPathsAt( export async function sdkToolBin( root: string, filesystem: Filesystem, + platform: NodeJS.Platform = process.platform, ): Promise | undefined> { const bins = [...(await commandLineToolBins(root, filesystem)), `${root}/tools/bin`]; for (const bin of bins) { - const avdmanager = `${bin}/avdmanager`; - const sdkmanager = `${bin}/sdkmanager`; + const avdmanager = withWindowsExtension(`${bin}/avdmanager`, platform, ".bat"); + const sdkmanager = withWindowsExtension(`${bin}/sdkmanager`, platform, ".bat"); if ((await filesystem.exists(avdmanager)) && (await filesystem.exists(sdkmanager))) { return { avdmanager, sdkmanager }; } diff --git a/src/ports/AGENTS.md b/src/ports/AGENTS.md index 84fc03655..be8952c3a 100644 --- a/src/ports/AGENTS.md +++ b/src/ports/AGENTS.md @@ -11,7 +11,7 @@ Uses: nothing from other components. Imported by: every component that touches t | ------------------------------------------ | --------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | | `Clock` | `clock.ts` | `SystemClock` | `FakeClock` | `now`, `setTimer`, `cancel` | | `Filesystem` | `filesystem.ts` | `NodeFilesystem` | `MemoryFilesystem` | Read, atomic write, copy, stat, delete, disk free; `mkdirp(path, { mode })` gives every directory it creates, parents included, and none that exists, exactly that mode (chmod past the umask) | -| `ProcessRunner` | `process-runner.ts` | `NodeProcessRunner` | `ScriptedProcessRunner` | Run or stream a command, capture output | +| `ProcessRunner` | `process-runner.ts` | `NodeProcessRunner` | `ScriptedProcessRunner` | Run or stream a command, capture output; on Windows a `.bat`/`.cmd` runs through `cmd.exe /d /s /c` (`windows-command.ts`), and an argument holding `%`, `"` or a line break is refused | | (wrapper) | `logging-process-runner.ts` | `LoggingProcessRunner` | — | One `process` log line per command, at `debug` only | | `ProcessSupervisor` | `process-supervisor.ts` | `NodeProcessSupervisor` | `FakeProcessSupervisor` | Is a pid alive; signal it | | `ParentWatch` | `parent-watch.ts` | `NodeParentWatch` | `FakeParentWatch` | Call once when a pid exits (polls) | diff --git a/src/ports/process-runner.ts b/src/ports/process-runner.ts index 02aa6e078..13c368699 100644 --- a/src/ports/process-runner.ts +++ b/src/ports/process-runner.ts @@ -1,6 +1,8 @@ import { spawn as spawnChildProcess, type ChildProcess } from "node:child_process"; import { constants } from "node:os"; +import { childLaunch } from "./windows-command.js"; + // `close` normally follows `exit` within the same tick, once the child's own stdio // pipes report EOF. But a child that forks a grandchild before it dies leaves that // grandchild holding the inherited write end of our pipe open -- it was handed the @@ -234,11 +236,13 @@ export class NodeProcessRunner implements ProcessRunner { } spawn(command: string, args: readonly string[], options: ProcessRunOptions = {}): ProcessHandle { - const child = spawnChildProcess(command, args, { + const launch = childLaunch(command, args); + const child = spawnChildProcess(launch.command, launch.args, { ...(options.cwd === undefined ? {} : { cwd: options.cwd }), ...(options.env === undefined ? {} : { env: options.env }), detached: process.platform !== "win32", stdio: options.stdio ?? "pipe", + windowsVerbatimArguments: launch.windowsVerbatimArguments, }); if (child.pid === undefined) { @@ -261,6 +265,7 @@ export class NodeProcessRunner implements ProcessRunner { options.lineEnd ?? "newline", this.exitDeferralCapMs, this.exitGraceMs, + launch.windowsVerbatimArguments, ); } @@ -269,11 +274,13 @@ export class NodeProcessRunner implements ProcessRunner { args: readonly string[], options: ProcessStreamOptions, ): StreamingProcessHandle { - const child = spawnChildProcess(command, args, { + const launch = childLaunch(command, args); + const child = spawnChildProcess(launch.command, launch.args, { ...(options.cwd === undefined ? {} : { cwd: options.cwd }), ...(options.env === undefined ? {} : { env: options.env }), detached: process.platform !== "win32", stdio: "pipe", + windowsVerbatimArguments: launch.windowsVerbatimArguments, }); if (child.pid === undefined) { @@ -289,6 +296,7 @@ export class NodeProcessRunner implements ProcessRunner { options.onChunk, this.exitDeferralCapMs, this.exitGraceMs, + launch.windowsVerbatimArguments, ); if (options.input !== undefined) { // One shot, then closed (ADR 0005 §19c): a command reading stdin sees exactly this and @@ -370,6 +378,7 @@ class NodeStreamingProcessHandle implements StreamingProcessHandle { * same stream is still unaccounted for. */ #pendingByStream: Record<"stdout" | "stderr", number> = { stderr: 0, stdout: 0 }; #deliveryWaiters: Array<() => void> = []; + #killedWith: NodeJS.Signals | undefined; constructor( private readonly child: ChildProcess, @@ -377,6 +386,7 @@ class NodeStreamingProcessHandle implements StreamingProcessHandle { onChunk: (stream: "stdout" | "stderr", chunk: string) => void | Promise, private readonly exitDeferralCapMs: number, private readonly exitGraceMs: number, + private readonly wrapped: boolean, ) { this.pid = pid; this.#forward(child.stdout, "stdout", onChunk); @@ -388,7 +398,12 @@ class NodeStreamingProcessHandle implements StreamingProcessHandle { const settle = (code: number | null, signal: NodeJS.Signals | null): void => { if (settled) return; settled = true; - resolve({ code, signal }); + const killedWith = this.#killedWith; + resolve( + wrapped && killedWith !== undefined + ? { code: null, signal: killedWith } + : { code, signal }, + ); }; const fail = (error: Error): void => { if (settled) return; @@ -457,7 +472,8 @@ class NodeStreamingProcessHandle implements StreamingProcessHandle { } kill(signal: NodeJS.Signals = "SIGTERM"): void { - killProcessTree(this.child, this.pid, signal); + if (isRunning(this.child)) this.#killedWith ??= signal; + killProcessTree(this.child, this.pid, signal, this.wrapped); } wait(): Promise { @@ -519,10 +535,37 @@ class NodeStreamingProcessHandle implements StreamingProcessHandle { } } +const TASKKILL_TIMEOUT_MS = 10_000; + /** - * Signals the child's whole process group (children are spawned `detached`, so the group is - * the unit that actually dies), falling back to the child alone on Windows and treating an - * already-exited process as success. Extracted so `ProcessHandle` and `StreamingProcessHandle` + * why: Windows has no process groups, and a batch file runs under a `cmd.exe` wrapper + * (`windows-command.ts`): signalling the wrapper alone would leave the script's own processes, + * `sdkmanager`'s Java, running. `taskkill /T` walks the tree from the wrapper's pid, so it runs + * while the wrapper is still alive; the wrapper outlives what it runs, since a script runs its + * commands in the foreground. Windows ends a process on any signal, so `/F` is no harsher than + * `child.kill`. `taskkill` makes the wrapper exit with a code where `child.kill` reports a + * signal, so the handle reports the signal it sent instead. Should `taskkill` itself fail, the + * wrapper alone is killed as before. + */ +function killWindowsProcessTree(child: ChildProcess, pid: number, signal: NodeJS.Signals): void { + const fallback = () => { + if (isRunning(child)) child.kill(signal); + }; + const taskkill = spawnChildProcess("taskkill", ["/pid", String(pid), "/T", "/F"], { + stdio: "ignore", + timeout: TASKKILL_TIMEOUT_MS, + windowsHide: true, + }); + taskkill.once("error", fallback); + taskkill.once("exit", (code) => { + if (code !== 0) fallback(); + }); +} + +/** + * why: Signals the child's whole process group (children are spawned `detached`, so the group is + * the unit that actually dies), or on Windows a batch file's whole tree and any other child + * alone, treating an already-exited process as success. Extracted so `ProcessHandle` and `StreamingProcessHandle` * kill identically -- a timeout that only reached the direct child would leave a tool's own * subprocesses running. * @@ -535,11 +578,17 @@ class NodeStreamingProcessHandle implements StreamingProcessHandle { * already handed to someone else -- latent before this PR, but `device.exec` is what makes the * timing remotely triggerable. */ -function killProcessTree(child: ChildProcess, pid: number, signal: NodeJS.Signals): void { - if (child.exitCode !== null || child.signalCode !== null) return; +function killProcessTree( + child: ChildProcess, + pid: number, + signal: NodeJS.Signals, + wrapped: boolean, +): void { + if (!isRunning(child)) return; if (process.platform === "win32") { - child.kill(signal); + if (wrapped) killWindowsProcessTree(child, pid, signal); + else child.kill(signal); return; } @@ -554,6 +603,12 @@ function killProcessTree(child: ChildProcess, pid: number, signal: NodeJS.Signal } } +// why: a wrapper that already exited, its output still held open by a grandchild, is never +// signalled, so its own exit code stands rather than a kill nobody sent. +function isRunning(child: ChildProcess): boolean { + return child.exitCode === null && child.signalCode === null; +} + class NodeProcessHandle implements ProcessHandle { readonly pid: number; readonly stdout = new LineBuffer(); @@ -561,6 +616,7 @@ class NodeProcessHandle implements ProcessHandle { readonly #stdoutChunks: string[] = []; readonly #stderrChunks: string[] = []; readonly #result: Promise; + #killedWith: NodeJS.Signals | undefined; constructor( private readonly child: ChildProcess, @@ -568,6 +624,7 @@ class NodeProcessHandle implements ProcessHandle { lineEnd: LineEnd, private readonly exitDeferralCapMs: number, private readonly exitGraceMs: number, + private readonly wrapped: boolean, ) { this.pid = pid; captureLines(child.stdout, this.stdout, this.#stdoutChunks, lineEnd); @@ -581,7 +638,11 @@ class NodeProcessHandle implements ProcessHandle { return; } settled = true; - resolve({ code, stderr: this.#stderrChunks.join(""), stdout: this.#stdoutChunks.join("") }); + resolve({ + code: wrapped && this.#killedWith !== undefined ? null : code, + stderr: this.#stderrChunks.join(""), + stdout: this.#stdoutChunks.join(""), + }); }; child.once("close", (code) => { @@ -611,7 +672,8 @@ class NodeProcessHandle implements ProcessHandle { } kill(signal: NodeJS.Signals = "SIGTERM"): void { - killProcessTree(this.child, this.pid, signal); + if (isRunning(this.child)) this.#killedWith ??= signal; + killProcessTree(this.child, this.pid, signal, this.wrapped); } unref(): void { diff --git a/src/ports/windows-command.test.ts b/src/ports/windows-command.test.ts new file mode 100644 index 000000000..fa1a90b4e --- /dev/null +++ b/src/ports/windows-command.test.ts @@ -0,0 +1,180 @@ +import { mkdtemp, readFile, rm, writeFile } from "node:fs/promises"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; + +import { describe, expect, it } from "vitest"; + +import { NodeProcessRunner } from "./index.js"; +import { childLaunch } from "./windows-command.js"; + +const sdkmanager = String.raw`C:\Android\Sdk/cmdline-tools/latest/bin/sdkmanager.bat`; + +// why: pure quoting logic with many cases, which the runner's surface could only reach on Windows. +describe("childLaunch", () => { + it.each([ + ["linux", "/sdk/cmdline-tools/latest/bin/sdkmanager"], + ["darwin", "/sdk/cmdline-tools/latest/bin/sdkmanager"], + ["win32", String.raw`C:\Android\Sdk\platform-tools\adb.exe`], + ] as const)("spawns anything but a Windows batch file as it is (%s)", (platform, command) => { + expect(childLaunch(command, ["50%"], platform, "cmd.exe")).toEqual({ + command, + args: ["50%"], + windowsVerbatimArguments: false, + }); + }); + + it("runs a batch file through cmd.exe /d /s /c, with backslashes in its path", () => { + expect(childLaunch(sdkmanager, ["--version"], "win32", "cmd.exe")).toEqual({ + command: "cmd.exe", + args: [ + "/d", + "/s", + "/c", + String.raw`"C:\Android\Sdk\cmdline-tools\latest\bin\sdkmanager.bat ^"--version^""`, + ], + windowsVerbatimArguments: true, + }); + }); + + it("uses the ComSpec it is given, and matches .cmd in any case", () => { + const launch = childLaunch(String.raw`C:\tools\AVDMANAGER.CMD`, [], "win32", "C:\\cmd.exe"); + + expect(launch.command).toBe("C:\\cmd.exe"); + expect(launch.args.at(-1)).toBe(String.raw`"C:\tools\AVDMANAGER.CMD"`); + }); + + it.each([ + [ + "semicolons", + "system-images;android-36;google_apis;x86_64", + String.raw`^"system-images^;android-36^;google_apis^;x86_64^"`, + ], + ["a command separator", "x & calc", String.raw`^"x^ ^&^ calc^"`], + ["a trailing backslash", "C:\\dir\\", String.raw`^"C:\dir\\^"`], + ])("escapes an argument holding %s so cmd.exe reads it as text", (_case, argument, escaped) => { + const line = childLaunch(String.raw`C:\t.bat`, [argument], "win32", "cmd.exe").args.at(-1); + + expect(line).toBe(`"C:\\t.bat ${escaped}"`); + }); + + it.each([ + ["a percent sign", "%PATH%"], + ["a double quote", 'a"b'], + ["a CRLF line break", "a\r\nb"], + ["a bare carriage return", "a\rb"], + ["a bare line feed", "a\nb"], + ])("refuses to run a batch file with an argument holding %s", (_case, argument) => { + expect(() => childLaunch(String.raw`C:\t.bat`, [argument], "win32", "cmd.exe")).toThrow( + /cmd\.exe cannot pass to a batch file unchanged/, + ); + }); +}); + +describe.runIf(process.platform === "win32")("NodeProcessRunner on Windows", () => { + /** + * why: the SDK's Gradle-generated batch files test `"x%~1"`, collect `%*` into a variable and + * expand it on the `java` line, so cmd.exe parses every argument there twice more; this script + * reads its arguments with those same lines and prints what arrived. + */ + it("passes every argument unchanged through a batch file that reads them the way the SDK's do", async () => { + const directory = await mkdtemp(join(tmpdir(), "simlock bat ")); + const printer = join(directory, "print-args.cjs"); + const script = join(directory, "forward args.bat"); + await writeFile(printer, "console.log(JSON.stringify(process.argv.slice(2)));\n"); + await writeFile( + script, + [ + "@echo off", + "set CMD_LINE_ARGS=", + 'if "x%~1" == "x" goto execute', + "set CMD_LINE_ARGS=%*", + ":execute", + `"${process.execPath}" "${printer}" %CMD_LINE_ARGS%`, + "", + ].join("\r\n"), + ); + const args = [ + "--install", + "system-images;android-36;google_apis;x86_64", + "with space", + "x & echo injected", + "C:\\trailing\\", + "(paren) |pipe| ^caret! `tick`", + ]; + try { + const result = await new NodeProcessRunner().run(script, args, { timeoutMs: 10_000 }); + + expect(result).toMatchObject({ code: 0, stderr: "" }); + expect(JSON.parse(result.stdout)).toEqual(args); + } finally { + await rm(directory, { force: true, recursive: true }); + } + }); + + it("ends what a batch file started when its run times out, not only the cmd.exe running it", async () => { + const directory = await mkdtemp(join(tmpdir(), "simlock bat ")); + const pidFile = join(directory, "child.pid"); + const script = join(directory, "long running.bat"); + await writeFile( + script, + `@echo off\r\n"${process.execPath}" -e "require('fs').writeFileSync(process.argv[1], String(process.pid)); setInterval(() => {}, 1000)" "${pidFile}"\r\n`, + ); + let childPid: number | undefined; + try { + const run = new NodeProcessRunner().run(script, [], { timeoutMs: 1_000 }); + await expect + .poll(() => readFile(pidFile, "utf8").catch(() => ""), { timeout: 5_000 }) + .not.toBe(""); + childPid = Number(await readFile(pidFile, "utf8")); + + await expect(run).resolves.toMatchObject({ code: null }); + + await expect.poll(() => isAlive(childPid ?? 0), { timeout: 5_000 }).toBe(false); + } finally { + if (childPid !== undefined && isAlive(childPid)) process.kill(childPid); + await rm(directory, { force: true, recursive: true }); + } + }); + + it("reports a batch file's own exit code when kill comes after cmd.exe exited but a grandchild still holds its output", async () => { + const directory = await mkdtemp(join(tmpdir(), "simlock bat ")); + const pidFile = join(directory, "grandchild.pid"); + const script = join(directory, "exits early.bat"); + await writeFile( + script, + `@echo off +start /b "" "${process.execPath}" -e "require('fs').writeFileSync(process.argv[1], String(process.pid)); setTimeout(() => {}, 4000)" "${pidFile}" +exit /b 0 +`, + ); + let grandchildPid: number | undefined; + try { + const handle = new NodeProcessRunner({ exitDeferralCapMs: 10_000, exitGraceMs: 8_000 }).spawn( + script, + [], + ); + await expect + .poll(() => readFile(pidFile, "utf8").catch(() => ""), { timeout: 5_000 }) + .not.toBe(""); + grandchildPid = Number(await readFile(pidFile, "utf8")); + await expect.poll(() => isAlive(handle.pid), { timeout: 5_000 }).toBe(false); + await new Promise((resolve) => setTimeout(resolve, 200)); + + handle.kill(); + + await expect(handle.wait()).resolves.toMatchObject({ code: 0 }); + } finally { + if (grandchildPid !== undefined && isAlive(grandchildPid)) process.kill(grandchildPid); + await rm(directory, { force: true, recursive: true }); + } + }); +}); + +function isAlive(pid: number): boolean { + try { + process.kill(pid, 0); + return true; + } catch { + return false; + } +} diff --git a/src/ports/windows-command.ts b/src/ports/windows-command.ts new file mode 100644 index 000000000..c5d7aac2c --- /dev/null +++ b/src/ports/windows-command.ts @@ -0,0 +1,60 @@ +import { win32 } from "node:path"; + +export interface ChildLaunch { + readonly command: string; + readonly args: readonly string[]; + readonly windowsVerbatimArguments: boolean; +} + +const BATCH_FILE = /\.(?:bat|cmd)$/i; + +// why: every character cmd.exe gives a meaning to; each is escaped with `^` so it stays text. +const CMD_METACHARACTERS = /([()\][%!^"`<>&|;, *?])/g; + +function escapeForCmd(text: string): string { + return text.replace(CMD_METACHARACTERS, "^$1"); +} + +/** + * why: under the C runtime's argv rules, backslashes before the closing quote are doubled, or they + * would escape it. The escapes are for this `cmd.exe /c` only: the script receives each argument + * quoted, and inside quotes its own lines (`if "x%~1" == "x"`, `set ARGS=%*`) read every character + * as text. Escaping twice would leave a `^"` there, which breaks the script's syntax. + */ +function quoteArgument(argument: string): string { + return escapeForCmd(`"${argument.replace(/(\\*)$/, "$1$1")}"`); +} + +/** + * why: Node refuses to spawn a `.bat` or `.cmd` without a shell (EINVAL) since CVE-2024-27980, + * https://nodejs.org/en/blog/vulnerability/april-2024-security-releases-2, and the Android SDK's + * `sdkmanager` and `avdmanager` are batch files on Windows. They run through `cmd.exe /d /s /c` + * with every argument quoted and escaped, so no argument is ever read as a second command. + * Anything else, and every command off Windows, is spawned as it is. + */ +export function childLaunch( + command: string, + args: readonly string[], + platform: NodeJS.Platform = process.platform, + comSpec: string | undefined = process.env.ComSpec, +): ChildLaunch { + if (platform !== "win32" || !BATCH_FILE.test(command)) { + return { command, args, windowsVerbatimArguments: false }; + } + // why: cmd.exe expands `%name%` before any escape applies, a line break ends the command, and a + // script that reads its arguments inside quotes (the SDK's all do) takes an embedded `"` as the + // end of one; none can be passed through safely, and no SDK call needs any of them. + const unsafe = args.find((argument) => /[%"\r\n]/.test(argument)); + if (unsafe !== undefined) { + throw new Error( + `Refusing to run ${command}: the argument ${JSON.stringify(unsafe)} holds a %, a " or a line break, which cmd.exe cannot pass to a batch file unchanged`, + ); + } + // why: SDK paths are joined with `/`, and cmd.exe can read `/cmdline-tools` in a command as a switch. + const line = [escapeForCmd(win32.normalize(command)), ...args.map(quoteArgument)].join(" "); + return { + command: comSpec ?? "cmd.exe", + args: ["/d", "/s", "/c", `"${line}"`], + windowsVerbatimArguments: true, + }; +}