Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion src/core/AGENTS.md
Original file line number Diff line number Diff line change
Expand Up @@ -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) →
Expand Down
56 changes: 56 additions & 0 deletions src/core/device-root.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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"],
Expand Down Expand Up @@ -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);
Expand Down Expand Up @@ -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<void>,
private readonly code = "EPERM",
) {
super(undefined, owner);
}

async rename(from: string, to: string): Promise<void> {
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.
Expand Down
18 changes: 16 additions & 2 deletions src/core/device-root.ts
Original file line number Diff line number Diff line change
Expand Up @@ -126,7 +126,7 @@ async function createRoot(context: RootContext): Promise<boolean> {
} catch (error: unknown) {
await discard(filesystem, staging);

if (isOccupiedPathError(error)) {
if (isOccupiedPathError(error) || (await lostRaceOnWindows(context, error))) {
return false;
}

Expand Down Expand Up @@ -171,7 +171,9 @@ async function validateRootDirectory(context: RootContext): Promise<void> {
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",
Expand Down Expand Up @@ -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<boolean> {
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
Expand Down
3 changes: 2 additions & 1 deletion src/drivers/android/AGENTS.md
Original file line number Diff line number Diff line change
Expand Up @@ -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`.
Expand Down
67 changes: 67 additions & 0 deletions src/drivers/android/physical-handler.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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",
});
});
});
24 changes: 20 additions & 4 deletions src/drivers/android/physical-handler.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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<DefaultAdbServerGateOptions, "env"> & {
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;
Expand Down Expand Up @@ -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);
Expand Down Expand Up @@ -166,7 +170,7 @@ export class AndroidPhysicalHandler {

async listPresentPhysical(enrolledIds: readonly string[]): Promise<readonly PresentPhysical[]> {
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);
Expand Down Expand Up @@ -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-<port>`, 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;
Expand Down
78 changes: 78 additions & 0 deletions src/drivers/android/prerequisites.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -43,6 +43,7 @@ function check(filesystem: MemoryFilesystem, runner: ScriptedProcessRunner) {
env: { ANDROID_HOME: sdk },
filesystem,
homeDirectory: home,
platform: "linux",
processRunner: runner,
});
}
Expand Down Expand Up @@ -117,6 +118,7 @@ describe("androidPrerequisites", () => {
env: { ANDROID_HOME: "/nowhere/home", ANDROID_SDK_ROOT: "/nowhere/root" },
filesystem: new MemoryFilesystem(),
homeDirectory: home,
platform: "linux",
processRunner: runner,
});

Expand Down Expand Up @@ -153,6 +155,7 @@ describe("androidPrerequisites", () => {
env: { ANDROID_HOME: "/stale-sdk" },
filesystem,
homeDirectory: home,
platform: "linux",
processRunner: runner,
});

Expand All @@ -165,6 +168,7 @@ describe("androidPrerequisites", () => {
env: { ANDROID_HOME: "/nowhere", ANDROID_SDK_ROOT: sdk },
filesystem,
homeDirectory: home,
platform: "linux",
processRunner: new ScriptedProcessRunner([SDKMANAGER_RUNS]),
});

Expand Down Expand Up @@ -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<MemoryFilesystem> {
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<Record<string, string>>,
) {
return androidPrerequisites({
env,
filesystem,
homeDirectory: "/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",
]);
});
});
Loading
Loading