From de1c85c9300a812996a941712307ee5ba826895a Mon Sep 17 00:00:00 2001 From: Xavier Date: Thu, 29 Oct 2026 21:18:44 -0300 Subject: [PATCH 01/11] fix(drivers,ports,core): Android on Windows Three things kept the Android driver off on native Windows (#1051): - SDK discovery looked for the bare tool names. On Windows the SDK holds `adb.exe`, `emulator.exe`, `sdkmanager.bat` and `avdmanager.bat`, so a complete SDK read as missing every tool. With no `ANDROID_HOME` it also searched only the macOS default; it now searches Android Studio's `%LOCALAPPDATA%\Android\Sdk` there. - Node refuses to spawn a `.bat` without a shell (EINVAL, since CVE-2024-27980). `NodeProcessRunner` now runs a batch file through `cmd.exe /d /s /c` with every argument quoted and its metacharacters escaped twice, once for `/c` and once for the script's own re-expansion of `%*`. An argument holding `%`, `"` or a line break cannot survive that, so it is refused; no SDK call passes one. - The device root was refused as `wrong-permissions`: Node reports every writable directory on Windows as mode 0o666. A platform with no uids already skips the owner check, and now skips the mode check too. Part of #1051. Co-Authored-By: Claude Opus 5.5 --- src/core/device-root.test.ts | 10 +++ src/core/device-root.ts | 4 +- src/drivers/android/prerequisites.test.ts | 72 +++++++++++++++ src/drivers/android/prerequisites.ts | 16 +++- src/drivers/android/sdk-paths.ts | 59 ++++++++++--- src/ports/process-runner.ts | 10 ++- src/ports/windows-command.test.ts | 102 ++++++++++++++++++++++ src/ports/windows-command.ts | 59 +++++++++++++ 8 files changed, 311 insertions(+), 21 deletions(-) create mode 100644 src/ports/windows-command.test.ts create mode 100644 src/ports/windows-command.ts diff --git a/src/core/device-root.test.ts b/src/core/device-root.test.ts index 9924f068c..b95534aeb 100644 --- a/src/core/device-root.test.ts +++ b/src/core/device-root.test.ts @@ -275,6 +275,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); diff --git a/src/core/device-root.ts b/src/core/device-root.ts index 5ae9de56d..85c147360 100644 --- a/src/core/device-root.ts +++ b/src/core/device-root.ts @@ -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", diff --git a/src/drivers/android/prerequisites.test.ts b/src/drivers/android/prerequisites.test.ts index 6eeabe28d..87f61c4ae 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,71 @@ 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"; + const winSdkmanager = `${winSdk}/cmdline-tools/latest/bin/sdkmanager.bat`; + + /** why: Android Studio installs `.exe` binaries and `.bat` tools on Windows, never the bare names. */ + async function windowsSdk(): Promise { + const filesystem = new MemoryFilesystem(); + await filesystem.mkdirp(winSdk); + await writeFile(filesystem, winSdkmanager); + await writeFile(filesystem, `${winSdk}/cmdline-tools/latest/bin/avdmanager.bat`); + await writeFile(filesystem, `${winSdk}/emulator/emulator.exe`); + await writeFile(filesystem, `${winSdk}/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 }], + ["Android Studio's %LOCALAPPDATA% default", { LOCALAPPDATA: "/Users/me/AppData/Local" }], + ])( + "finds a complete SDK of .exe and .bat tools through %s and runs its sdkmanager.bat", + async (_source, env) => { + const runner = new ScriptedProcessRunner([WINDOWS_SDKMANAGER_RUNS]); + + await expect(windowsCheck(await windowsSdk(), runner, env).check()).resolves.toEqual([]); + expect(runner.calls.map((call) => [call.command, ...call.args])).toEqual([ + [winSdkmanager, "--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/process-runner.ts b/src/ports/process-runner.ts index 02aa6e078..8a5984993 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) { @@ -269,11 +273,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) { diff --git a/src/ports/windows-command.test.ts b/src/ports/windows-command.test.ts new file mode 100644 index 000000000..e7b2304ec --- /dev/null +++ b/src/ports/windows-command.test.ts @@ -0,0 +1,102 @@ +import { mkdtemp, 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 line break", "a\r\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 batch files collect `%*` into a variable and expand it on the `java` line, so + * every argument is parsed by cmd.exe twice; this script does the same and prints what arrived. + */ + it("passes every argument unchanged through a batch file that forwards %* 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\r\nset CMD_LINE_ARGS=%*\r\n"${process.execPath}" "${printer}" %CMD_LINE_ARGS%\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 }); + } + }); +}); diff --git a/src/ports/windows-command.ts b/src/ports/windows-command.ts new file mode 100644 index 000000000..a4333926a --- /dev/null +++ b/src/ports/windows-command.ts @@ -0,0 +1,59 @@ +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. A batch file hands its arguments to `cmd.exe` once more, so the metacharacters + * are escaped twice: once for this `cmd.exe /c`, once for the script's own expansion of `%*`. + */ +function quoteArgument(argument: string): string { + return escapeForCmd(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 re-expands `%*` (the SDK's all do) reads an embedded `"` as the end of a quote; + // 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, + }; +} From d8a187313d51e3b823a85ed0f586ae48e88946a8 Mon Sep 17 00:00:00 2001 From: Xavier Date: Thu, 29 Oct 2026 21:21:46 -0300 Subject: [PATCH 02/11] fix(ports): escape a batch file's arguments once, not twice The SDK's Gradle-generated scripts read their arguments inside quotes (`if "x%~1" == "x"`, `set CMD_LINE_ARGS=%*`), where `^` is text. Escaping twice left `^"--version^"` there, and `sdkmanager.bat` failed with "The syntax of the command is incorrect". Escaping is for the `cmd.exe /c` line only; the Windows test script now reads its arguments with the SDK's own lines. Co-Authored-By: Claude Opus 5.5 --- src/ports/windows-command.test.ts | 25 +++++++++++++++++-------- src/ports/windows-command.ts | 11 ++++++----- 2 files changed, 23 insertions(+), 13 deletions(-) diff --git a/src/ports/windows-command.test.ts b/src/ports/windows-command.test.ts index e7b2304ec..b16898d50 100644 --- a/src/ports/windows-command.test.ts +++ b/src/ports/windows-command.test.ts @@ -30,7 +30,7 @@ describe("childLaunch", () => { "/d", "/s", "/c", - String.raw`"C:\Android\Sdk\cmdline-tools\latest\bin\sdkmanager.bat ^^^"--version^^^""`, + String.raw`"C:\Android\Sdk\cmdline-tools\latest\bin\sdkmanager.bat ^"--version^""`, ], windowsVerbatimArguments: true, }); @@ -47,10 +47,10 @@ describe("childLaunch", () => { [ "semicolons", "system-images;android-36;google_apis;x86_64", - String.raw`^^^"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\\^^^"`], + ["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); @@ -70,17 +70,26 @@ describe("childLaunch", () => { describe.runIf(process.platform === "win32")("NodeProcessRunner on Windows", () => { /** - * why: the SDK's batch files collect `%*` into a variable and expand it on the `java` line, so - * every argument is parsed by cmd.exe twice; this script does the same and prints what arrived. + * 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 forwards %* the way the SDK's do", async () => { + 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\r\nset CMD_LINE_ARGS=%*\r\n"${process.execPath}" "${printer}" %CMD_LINE_ARGS%\r\n`, + [ + "@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", diff --git a/src/ports/windows-command.ts b/src/ports/windows-command.ts index a4333926a..c5d7aac2c 100644 --- a/src/ports/windows-command.ts +++ b/src/ports/windows-command.ts @@ -17,11 +17,12 @@ function escapeForCmd(text: string): string { /** * why: under the C runtime's argv rules, backslashes before the closing quote are doubled, or they - * would escape it. A batch file hands its arguments to `cmd.exe` once more, so the metacharacters - * are escaped twice: once for this `cmd.exe /c`, once for the script's own expansion of `%*`. + * 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(escapeForCmd(`"${argument.replace(/(\\*)$/, "$1$1")}"`)); + return escapeForCmd(`"${argument.replace(/(\\*)$/, "$1$1")}"`); } /** @@ -41,8 +42,8 @@ export function childLaunch( return { command, args, windowsVerbatimArguments: false }; } // why: cmd.exe expands `%name%` before any escape applies, a line break ends the command, and a - // script that re-expands `%*` (the SDK's all do) reads an embedded `"` as the end of a quote; - // none can be passed through safely, and no SDK call needs any of them. + // 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( From a60450efc5efe81ec7e6eb2afd0c4fa7b1505250 Mon Sep 17 00:00:00 2001 From: Xavier Date: Thu, 29 Oct 2026 21:26:29 -0300 Subject: [PATCH 03/11] docs(agents): manuals for the Windows SDK names, batch launch and root checks Co-Authored-By: Claude Opus 5.5 --- src/core/AGENTS.md | 1 + src/drivers/android/AGENTS.md | 3 ++- src/ports/AGENTS.md | 2 +- 3 files changed, 4 insertions(+), 2 deletions(-) diff --git a/src/core/AGENTS.md b/src/core/AGENTS.md index d7e164bfb..23a95cd34 100644 --- a/src/core/AGENTS.md +++ b/src/core/AGENTS.md @@ -107,6 +107,7 @@ Events: → `absent` `device.absence-detected`; `absent` → `reclaiming` `devic 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`. + With no `uid` (Windows) it checks neither the owner nor the mode, which that platform does not have. 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/drivers/android/AGENTS.md b/src/drivers/android/AGENTS.md index 47a271484..f4d9248c0 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/ports/AGENTS.md b/src/ports/AGENTS.md index be4678885..0b383b27f 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) | From 32f44dc1a5d35cc6aedbea439c2f23c44f31aed6 Mon Sep 17 00:00:00 2001 From: Xavier Date: Thu, 29 Oct 2026 21:51:10 -0300 Subject: [PATCH 04/11] fix(ports): end a batch file's whole process tree on Windows `kill()` on Windows signalled only the child, which for a batch file is the `cmd.exe` wrapper, so a timed-out or aborted `sdkmanager` left its Java running. A wrapped batch launch is now ended with `taskkill /T /F` while the wrapper is alive, which also ends what the script started. `taskkill` makes the wrapper exit with code 1 where `child.kill` reports a signal, so the handle reports the signal it sent, and a timeout still reads as one (`code: null`). Every other Windows child is killed as before. Addresses CodeRabbit review on #1053. Co-Authored-By: Claude Opus 5.5 --- src/ports/process-runner.ts | 68 +++++++++++++++++++++++++++---- src/ports/windows-command.test.ts | 36 +++++++++++++++- 2 files changed, 94 insertions(+), 10 deletions(-) diff --git a/src/ports/process-runner.ts b/src/ports/process-runner.ts index 8a5984993..65e77b7f7 100644 --- a/src/ports/process-runner.ts +++ b/src/ports/process-runner.ts @@ -265,6 +265,7 @@ export class NodeProcessRunner implements ProcessRunner { options.lineEnd ?? "newline", this.exitDeferralCapMs, this.exitGraceMs, + launch.windowsVerbatimArguments, ); } @@ -295,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 @@ -376,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, @@ -383,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); @@ -394,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; @@ -463,7 +472,8 @@ class NodeStreamingProcessHandle implements StreamingProcessHandle { } kill(signal: NodeJS.Signals = "SIGTERM"): void { - killProcessTree(this.child, this.pid, signal); + this.#killedWith ??= signal; + killProcessTree(this.child, this.pid, signal, this.wrapped); } wait(): Promise { @@ -526,9 +536,9 @@ class NodeStreamingProcessHandle implements StreamingProcessHandle { } /** - * 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: 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. * @@ -541,11 +551,44 @@ 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 { +const TASKKILL_TIMEOUT_MS = 10_000; + +/** + * 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 (child.exitCode === null && child.signalCode === null) 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(); + }); +} + +function killProcessTree( + child: ChildProcess, + pid: number, + signal: NodeJS.Signals, + wrapped: boolean, +): void { if (child.exitCode !== null || child.signalCode !== null) return; if (process.platform === "win32") { - child.kill(signal); + if (wrapped) killWindowsProcessTree(child, pid, signal); + else child.kill(signal); return; } @@ -567,6 +610,7 @@ class NodeProcessHandle implements ProcessHandle { readonly #stdoutChunks: string[] = []; readonly #stderrChunks: string[] = []; readonly #result: Promise; + #killedWith: NodeJS.Signals | undefined; constructor( private readonly child: ChildProcess, @@ -574,6 +618,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); @@ -587,7 +632,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) => { @@ -617,7 +666,8 @@ class NodeProcessHandle implements ProcessHandle { } kill(signal: NodeJS.Signals = "SIGTERM"): void { - killProcessTree(this.child, this.pid, signal); + 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 index b16898d50..b9417179a 100644 --- a/src/ports/windows-command.test.ts +++ b/src/ports/windows-command.test.ts @@ -1,4 +1,4 @@ -import { mkdtemp, rm, writeFile } from "node:fs/promises"; +import { mkdtemp, readFile, rm, writeFile } from "node:fs/promises"; import { tmpdir } from "node:os"; import { join } from "node:path"; @@ -108,4 +108,38 @@ describe.runIf(process.platform === "win32")("NodeProcessRunner on Windows", () 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 }); + } + }); }); + +function isAlive(pid: number): boolean { + try { + process.kill(pid, 0); + return true; + } catch { + return false; + } +} From ab68169492888227f7a8770bc4f92e9161033ac9 Mon Sep 17 00:00:00 2001 From: Xavier Date: Thu, 29 Oct 2026 22:11:08 -0300 Subject: [PATCH 05/11] fix(core): a device root another daemon published first survives Windows' rename refusal Two daemons starting at once both stage a device root and rename it into place. On POSIX the loser's rename fails EEXIST or ENOTEMPTY, and it validates the winner's root. Windows refuses with EPERM (or EACCES), so the loser refused its own root as `unreadable` and ran without that platform. Seen live: a `simlock status` auto-launch raced a scheduled `daemon start`, and the surviving daemon had no Android driver. An EPERM or EACCES from that rename is now a lost race when the root is there afterwards, and the root is validated as usual; with nothing there it is still refused. Co-Authored-By: Claude Opus 5.5 --- src/core/device-root.test.ts | 38 ++++++++++++++++++++++++++++++++++++ src/core/device-root.ts | 14 ++++++++++++- 2 files changed, 51 insertions(+), 1 deletion(-) diff --git a/src/core/device-root.test.ts b/src/core/device-root.test.ts index b95534aeb..051334572 100644 --- a/src/core/device-root.test.ts +++ b/src/core/device-root.test.ts @@ -175,6 +175,24 @@ describe("ensureOwnedRoot", () => { await expect(filesystem.readdir(parent)).resolves.toEqual(["ios"]); }); + it("keeps a root another process published first when Windows refuses the rename with EPERM", async () => { + const filesystem = new RefusingRenameFilesystem(uid, async (target) => { + await target.mkdirp(root); + await target.writeFileAtomic(markerPath, marker()); + }); + + 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"], @@ -475,6 +493,26 @@ class UmaskedFilesystem extends MemoryFilesystem { * 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. */ +/** Refuses renaming onto the root with EPERM, as Windows does when the root exists, after `before` runs. */ +class RefusingRenameFilesystem extends MemoryFilesystem { + constructor( + owner: number, + private readonly before: (target: MemoryFilesystem) => Promise, + ) { + 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( + `EPERM: operation not permitted, rename '${from}' -> '${to}'`, + ); + error.code = "EPERM"; + throw error; + } +} + class RacingFilesystem extends MemoryFilesystem { #absentOnce: string | undefined; diff --git a/src/core/device-root.ts b/src/core/device-root.ts index 85c147360..67b9ac665 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; } @@ -382,6 +382,18 @@ function isMissingPathError(error: unknown): boolean { * is sitting there: a non-empty directory, a directory replaced by a file, or a plain * refusal to clobber. */ +/** + * 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; +} + function isOccupiedPathError(error: unknown): boolean { const code = errorCode(error); From 746b4d84d24b42545bbf825367d868d6e1532828 Mon Sep 17 00:00:00 2001 From: Xavier Date: Thu, 29 Oct 2026 22:11:48 -0300 Subject: [PATCH 06/11] test(core): keep RacingFilesystem's comment on its class Co-Authored-By: Claude Opus 5.5 --- src/core/device-root.test.ts | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/src/core/device-root.test.ts b/src/core/device-root.test.ts index 051334572..c67476576 100644 --- a/src/core/device-root.test.ts +++ b/src/core/device-root.test.ts @@ -489,11 +489,7 @@ class UmaskedFilesystem extends MemoryFilesystem { } } -/** - * 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. - */ -/** Refuses renaming onto the root with EPERM, as Windows does when the root exists, after `before` runs. */ +/** why: Windows refuses renaming onto an existing directory with EPERM; `before` decides whether another process published the root first. */ class RefusingRenameFilesystem extends MemoryFilesystem { constructor( owner: number, @@ -513,6 +509,10 @@ class RefusingRenameFilesystem extends MemoryFilesystem { } } +/** + * 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. + */ class RacingFilesystem extends MemoryFilesystem { #absentOnce: string | undefined; From bbbc6f5eff78961792e1eebaff65d8d08cf00b8a Mon Sep 17 00:00:00 2001 From: Xavier Date: Thu, 29 Oct 2026 22:15:59 -0300 Subject: [PATCH 07/11] docs(agents): keep the core manual within its 150 lines, and name the Windows rename race Co-Authored-By: Claude Opus 5.5 --- src/core/AGENTS.md | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/src/core/AGENTS.md b/src/core/AGENTS.md index 23a95cd34..b1d8f6343 100644 --- a/src/core/AGENTS.md +++ b/src/core/AGENTS.md @@ -106,8 +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`. - With no `uid` (Windows) it checks neither the owner nor the mode, which that platform does not have. + 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) → From 2fb7f07dae1d6491058bf74d97027b4283e76fb9 Mon Sep 17 00:00:00 2001 From: Xavier Date: Thu, 29 Oct 2026 22:22:10 -0300 Subject: [PATCH 08/11] fix(drivers): enrol a USB Android phone on Windows Simlock counts a transport as USB only when `adb devices -l` lists a `usb:` path, which adb on Windows never prints, so `simlock device add` refused every phone there as network-only ("only USB-connected devices can be enrolled"). On Windows the serial now tells the kinds apart: a `host:port` or an mDNS service name is a network transport, an `emulator-` an emulator, and anything else a USB device. Every other host still requires the `usb:` path. Seen live with a Galaxy A70 (SM-A705MN) on Windows 11. Co-Authored-By: Claude Opus 5.5 --- src/drivers/android/physical-handler.test.ts | 55 ++++++++++++++++++++ src/drivers/android/physical-handler.ts | 24 +++++++-- 2 files changed, 75 insertions(+), 4 deletions(-) diff --git a/src/drivers/android/physical-handler.test.ts b/src/drivers/android/physical-handler.test.ts index 285ef173b..e0ea77fab 100644 --- a/src/drivers/android/physical-handler.test.ts +++ b/src/drivers/android/physical-handler.test.ts @@ -1604,3 +1604,58 @@ 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([ + ["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; From 888760c3f8f078ef04c20f82bc103bf397de4e53 Mon Sep 17 00:00:00 2001 From: Szymon Chmal Date: Fri, 30 Oct 2026 12:52:16 +0100 Subject: [PATCH 09/11] fix(drivers): cover EACCES, the win32 listing and LOCALAPPDATA, and reattach displaced doc comments (#1051) --- src/core/device-root.test.ts | 34 ++++++++++++-------- src/core/device-root.ts | 10 +++--- src/drivers/android/physical-handler.test.ts | 12 +++++++ src/drivers/android/prerequisites.test.ts | 30 ++++++++++------- src/ports/process-runner.ts | 32 +++++++++--------- 5 files changed, 72 insertions(+), 46 deletions(-) diff --git a/src/core/device-root.test.ts b/src/core/device-root.test.ts index c67476576..91a7f635d 100644 --- a/src/core/device-root.test.ts +++ b/src/core/device-root.test.ts @@ -175,16 +175,23 @@ describe("ensureOwnedRoot", () => { await expect(filesystem.readdir(parent)).resolves.toEqual(["ios"]); }); - it("keeps a root another process published first when Windows refuses the rename with EPERM", async () => { - const filesystem = new RefusingRenameFilesystem(uid, async (target) => { - await target.mkdirp(root); - await target.writeFileAtomic(markerPath, marker()); - }); - - await expect(ensure(filesystem)).resolves.toBe(root); - await expect(filesystem.readFile(markerPath)).resolves.toBe(marker()); - 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); @@ -489,11 +496,12 @@ class UmaskedFilesystem extends MemoryFilesystem { } } -/** why: Windows refuses renaming onto an existing directory with EPERM; `before` decides whether another process published the root first. */ +/** 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); } @@ -502,9 +510,9 @@ class RefusingRenameFilesystem extends MemoryFilesystem { if (to !== root) return super.rename(from, to); await this.before(this); const error: NodeJS.ErrnoException = new Error( - `EPERM: operation not permitted, rename '${from}' -> '${to}'`, + `${this.code}: operation not permitted, rename '${from}' -> '${to}'`, ); - error.code = "EPERM"; + error.code = this.code; throw error; } } diff --git a/src/core/device-root.ts b/src/core/device-root.ts index 67b9ac665..71dd585aa 100644 --- a/src/core/device-root.ts +++ b/src/core/device-root.ts @@ -377,11 +377,6 @@ function isMissingPathError(error: unknown): boolean { return errorCode(error) === "ENOENT"; } -/** - * 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 - * refusal to clobber. - */ /** * 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 @@ -394,6 +389,11 @@ async function lostRaceOnWindows(context: RootContext, error: unknown): Promise< 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 + * refusal to clobber. + */ function isOccupiedPathError(error: unknown): boolean { const code = errorCode(error); diff --git a/src/drivers/android/physical-handler.test.ts b/src/drivers/android/physical-handler.test.ts index e0ea77fab..a4b38d6b1 100644 --- a/src/drivers/android/physical-handler.test.ts +++ b/src/drivers/android/physical-handler.test.ts @@ -1644,6 +1644,18 @@ describe("Android physical handler on Windows", () => { }); }); + 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"], diff --git a/src/drivers/android/prerequisites.test.ts b/src/drivers/android/prerequisites.test.ts index 87f61c4ae..3993cb49d 100644 --- a/src/drivers/android/prerequisites.test.ts +++ b/src/drivers/android/prerequisites.test.ts @@ -222,16 +222,19 @@ describe("androidPrerequisites", () => { 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(): Promise { + async function windowsSdk(root = winSdk): Promise { const filesystem = new MemoryFilesystem(); - await filesystem.mkdirp(winSdk); - await writeFile(filesystem, winSdkmanager); - await writeFile(filesystem, `${winSdk}/cmdline-tools/latest/bin/avdmanager.bat`); - await writeFile(filesystem, `${winSdk}/emulator/emulator.exe`); - await writeFile(filesystem, `${winSdk}/platform-tools/adb.exe`); + 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; } @@ -255,16 +258,19 @@ describe("androidPrerequisites on Windows", () => { }; it.each([ - ["ANDROID_HOME", { ANDROID_HOME: winSdk }], - ["Android Studio's %LOCALAPPDATA% default", { LOCALAPPDATA: "/Users/me/AppData/Local" }], + ["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) => { - const runner = new ScriptedProcessRunner([WINDOWS_SDKMANAGER_RUNS]); + 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(), runner, env).check()).resolves.toEqual([]); + await expect(windowsCheck(await windowsSdk(root), runner, env).check()).resolves.toEqual([]); expect(runner.calls.map((call) => [call.command, ...call.args])).toEqual([ - [winSdkmanager, "--version"], + [sdkmanager, "--version"], ]); }, ); diff --git a/src/ports/process-runner.ts b/src/ports/process-runner.ts index 65e77b7f7..f93f23ef1 100644 --- a/src/ports/process-runner.ts +++ b/src/ports/process-runner.ts @@ -535,22 +535,6 @@ class NodeStreamingProcessHandle implements StreamingProcessHandle { } } -/** - * 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. - * - * Guarded on `child.exitCode`/`child.signalCode` -- both still `null` only while the child is - * actually running -- before ever calling `process.kill(-pid, signal)` directly: that call - * bypasses `ChildProcess.kill`'s own "already exited" guard, and `wait()` can defer settling - * up to `EXIT_TO_CLOSE_MAX_DEFERRAL_MS` past the real `exit` event (a chatty grandchild holding - * stdio open, or a stalled delivery). Node frees a reaped pid for the kernel to recycle, so a - * timeout firing in that window without this guard could signal a process group the kernel has - * already handed to someone else -- latent before this PR, but `device.exec` is what makes the - * timing remotely triggerable. - */ const TASKKILL_TIMEOUT_MS = 10_000; /** @@ -578,6 +562,22 @@ function killWindowsProcessTree(child: ChildProcess, pid: number, signal: NodeJS }); } +/** + * 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. + * + * Guarded on `child.exitCode`/`child.signalCode` -- both still `null` only while the child is + * actually running -- before ever calling `process.kill(-pid, signal)` directly: that call + * bypasses `ChildProcess.kill`'s own "already exited" guard, and `wait()` can defer settling + * up to `EXIT_TO_CLOSE_MAX_DEFERRAL_MS` past the real `exit` event (a chatty grandchild holding + * stdio open, or a stalled delivery). Node frees a reaped pid for the kernel to recycle, so a + * timeout firing in that window without this guard could signal a process group the kernel has + * 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, From 3462a4f151182cee55827fe6636aceea1d64c3d6 Mon Sep 17 00:00:00 2001 From: Xavier Date: Fri, 30 Oct 2026 09:38:41 -0300 Subject: [PATCH 10/11] fix(ports): a kill after the child exited keeps its exit code A batch launch on Windows reports the signal it sent when it was killed. `kill()` recorded that signal even when `cmd.exe` had already exited and only a grandchild still held its output open, so a run that ended with code 0 came back as killed. The signal is now recorded only while the child still runs, which is also when `killProcessTree` signals it. Addresses CodeRabbit review on #1053. Co-Authored-By: Claude Opus 5.5 --- src/ports/process-runner.ts | 14 +++++++++---- src/ports/windows-command.test.ts | 33 +++++++++++++++++++++++++++++++ 2 files changed, 43 insertions(+), 4 deletions(-) diff --git a/src/ports/process-runner.ts b/src/ports/process-runner.ts index f93f23ef1..13c368699 100644 --- a/src/ports/process-runner.ts +++ b/src/ports/process-runner.ts @@ -472,7 +472,7 @@ class NodeStreamingProcessHandle implements StreamingProcessHandle { } kill(signal: NodeJS.Signals = "SIGTERM"): void { - this.#killedWith ??= signal; + if (isRunning(this.child)) this.#killedWith ??= signal; killProcessTree(this.child, this.pid, signal, this.wrapped); } @@ -549,7 +549,7 @@ const TASKKILL_TIMEOUT_MS = 10_000; */ function killWindowsProcessTree(child: ChildProcess, pid: number, signal: NodeJS.Signals): void { const fallback = () => { - if (child.exitCode === null && child.signalCode === null) child.kill(signal); + if (isRunning(child)) child.kill(signal); }; const taskkill = spawnChildProcess("taskkill", ["/pid", String(pid), "/T", "/F"], { stdio: "ignore", @@ -584,7 +584,7 @@ function killProcessTree( signal: NodeJS.Signals, wrapped: boolean, ): void { - if (child.exitCode !== null || child.signalCode !== null) return; + if (!isRunning(child)) return; if (process.platform === "win32") { if (wrapped) killWindowsProcessTree(child, pid, signal); @@ -603,6 +603,12 @@ function killProcessTree( } } +// 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(); @@ -666,7 +672,7 @@ class NodeProcessHandle implements ProcessHandle { } kill(signal: NodeJS.Signals = "SIGTERM"): void { - this.#killedWith ??= signal; + if (isRunning(this.child)) this.#killedWith ??= signal; killProcessTree(this.child, this.pid, signal, this.wrapped); } diff --git a/src/ports/windows-command.test.ts b/src/ports/windows-command.test.ts index b9417179a..3424d57ae 100644 --- a/src/ports/windows-command.test.ts +++ b/src/ports/windows-command.test.ts @@ -133,6 +133,39 @@ describe.runIf(process.platform === "win32")("NodeProcessRunner on Windows", () 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 { From 8aeef4baff56196cc096c221f335c7ee16c0d935 Mon Sep 17 00:00:00 2001 From: Xavier Date: Fri, 30 Oct 2026 10:48:40 -0300 Subject: [PATCH 11/11] test(ports): refuse a bare CR and a bare LF in a batch argument, each on its own The refusal cases had only "a\r\nb", so dropping either half of the guard's `\r\n` left them green. A bare line feed ends the cmd.exe command line as surely as CRLF does. Addresses blind review R1 on #1053. Co-Authored-By: Claude Opus 5.5 --- src/ports/windows-command.test.ts | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/src/ports/windows-command.test.ts b/src/ports/windows-command.test.ts index 3424d57ae..fa1a90b4e 100644 --- a/src/ports/windows-command.test.ts +++ b/src/ports/windows-command.test.ts @@ -60,7 +60,9 @@ describe("childLaunch", () => { it.each([ ["a percent sign", "%PATH%"], ["a double quote", 'a"b'], - ["a line break", "a\r\nb"], + ["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/,