diff --git a/docs/CLI.md b/docs/CLI.md index 3b17dd2b0..fa1823278 100644 --- a/docs/CLI.md +++ b/docs/CLI.md @@ -1584,7 +1584,7 @@ device it is: `phone`, `tablet`, `watch`, `tv`, `vision`, `auto` or from the device profile's tag: `android-tv` is `tv`, `android-wear` is `watch`, `android-automotive` and its variants are `auto`, `android-desktop` is `desktop`, and a profile with no tag, or a custom profile from -`devices.xml`, is `phone`. A model whose tooling reports nothing usable has +`devices.xml`, is `phone`. A profile Simlock ships carries its own class. A model whose tooling reports nothing usable has no entry, and is still listed and leasable by name. `classDefaults` says, for a class, which model Simlock would create for it on @@ -1653,8 +1653,14 @@ own name for it. ### Where Android models come from -Simlock reads Android device models from two places and writes to neither: +Simlock reads Android device models from three places and writes to none of +them: +- **Simlock's own profiles** ship with Simlock (today: Pixel 9). They are + read first, so a device made from one has the same hardware on every + host, and the model is there even when your `cmdline-tools` is too old to + have it. A name Simlock's own profiles have wins over the same name in the + SDK and in `devices.xml`. - **Built-in profiles** ship with the Android SDK's `cmdline-tools`. A model newer than your `cmdline-tools` is not there; update `cmdline-tools` to get it. @@ -1667,7 +1673,8 @@ Simlock reads Android device models from two places and writes to neither: `avdmanager list device` prints both kinds; it shows a custom profile with `OEM : User`. Simlock also reads `devices.xml` itself. When a custom profile has the same name as a built-in one, the built-in profile wins and the model -is not custom. If `devices.xml` cannot be read, the built-in models are still +is not custom. Simlock's own models are listed first, then the SDK's, then +the custom ones. If `devices.xml` cannot be read, the built-in models are still listed. A custom model is marked `(custom)` in the human view of `simlock catalog` and listed in `customModels` in `--json`. diff --git a/e2e/slow-android-smoke.test.ts b/e2e/slow-android-smoke.test.ts index 69b24b73f..0ab6afa41 100644 --- a/e2e/slow-android-smoke.test.ts +++ b/e2e/slow-android-smoke.test.ts @@ -50,12 +50,7 @@ interface AndroidCatalogOutput { }[]; } -/** - * Checks the Android entry against the SDK on disk -- every listed image is installed, under a - * runtime the catalog lists -- and returns the AVD id a built-in profile is listed with as - * another name. - */ -function avdIdFromCatalog(output: AndroidCatalogOutput): string { +function checkCatalog(output: AndroidCatalogOutput): void { const android = output.platforms.find((platform) => platform.platform === "android"); if (android === undefined) { throw new Error("simlock catalog reported no android platform -- SDK discovery failed"); @@ -79,12 +74,9 @@ function avdIdFromCatalog(output: AndroidCatalogOutput): string { expect(existsSync(path), `listed image ${JSON.stringify(image)} is not installed`).toBe(true); } - const aliases = android.models.flatMap((name) => android.modelAliases[name] ?? []); - expect( - aliases.length, - "expected a built-in profile with its AVD id as another name", - ).toBeGreaterThan(0); - return aliases[0] as string; + expect(android.models[0]).toBe("Pixel 9"); + expect(android.modelClasses["Pixel 9"]).toBe("phone"); + expect(android.modelAliases["Pixel 9"]).toEqual(["pixel_9"]); } // Real emulator boots are slow and this SDK layout is host-specific, so this lane is @@ -94,7 +86,7 @@ describe.skipIf(!hasAndroidSdk)( { tags: ["slow", "android"] }, () => { it( - "catalog agrees with the SDK and lists an AVD id and an installed image, a cold lease by that AVD id boots a real emulator, and a shut-down emulator reports erasableReadable:false with no crash or false provenance finding", + "catalog lists Simlock's Pixel 9 first, a cold lease of Pixel 9 boots a real emulator with the library screen size, and a shut-down emulator reports erasableReadable:false with no crash or false provenance finding", { timeout: 420_000 }, async () => { const env = await withDaemon({ @@ -108,8 +100,7 @@ describe.skipIf(!hasAndroidSdk)( try { const catalog = await env.cli(["catalog", "--json", "--platform", "android"]); expect(catalog.code).toBe(0); - // The lease below asks by an AVD id the catalog lists as another name. - const model = avdIdFromCatalog(catalog.json as AndroidCatalogOutput); + checkCatalog(catalog.json as AndroidCatalogOutput); const lease = await env.cli( [ @@ -117,7 +108,7 @@ describe.skipIf(!hasAndroidSdk)( "--platform", "android", "--device", - model, + "Pixel 9", "--agent-id", "android-smoke", "--detach", @@ -146,6 +137,11 @@ describe.skipIf(!hasAndroidSdk)( expect(wrapped.code, `simlock adb failed: ${wrapped.stderr}`).toBe(0); expect(wrapped.stdout).toContain("emulator-"); + const size = await env.cli(["adb", "shell", "wm", "size"]); + expect(size.stdout).toContain("Physical size: 1080x2424"); + const density = await env.cli(["adb", "shell", "wm", "density"]); + expect(density.stdout).toContain("Physical density: 420"); + const refused = await env.cli(["adb", "kill-server"]); expect(refused.code, "simlock adb kill-server must be refused, not run").toBe(2); expect(refused.error?.code).toBe("USAGE"); diff --git a/src/core/driver-catalog.test.ts b/src/core/driver-catalog.test.ts index 86c098bac..83272bc51 100644 --- a/src/core/driver-catalog.test.ts +++ b/src/core/driver-catalog.test.ts @@ -334,6 +334,25 @@ describe("DriverCatalog", () => { return (await catalog.listCatalog())[0]?.classDefaults; } + it("is Pixel 9 for a phone list that starts at Pixel 9 when the catalog lists Pixel 9 paired and no Pixel 8", async () => { + const driver = new FakeDriver({ + availableOsVersions: ["35"], + clock: new FakeClock(), + knownModels: ["Pixel 9", "Pixel 7"], + modelAliases: { "Pixel 9": ["pixel_9"] }, + modelClasses: { "Pixel 7": "phone", "Pixel 9": "phone" }, + modelRuntimes: { "Pixel 7": [], "Pixel 9": ["35"] }, + platform: "android", + }); + const catalog = new DriverCatalog([driver], { + preferences: { + android: { phone: ["Pixel 9", "Pixel 8", "Pixel 7", "Pixel 6", "Medium Phone"] }, + }, + }); + + expect((await catalog.listCatalog())[0]?.classDefaults).toEqual({ phone: "Pixel 9" }); + }); + it("is the first name on the preference list the catalog lists", async () => { await expect( defaultsOf({ diff --git a/src/drivers/android/device-profile-source.ts b/src/drivers/android/device-profile-source.ts index cfca732f5..62eca3610 100644 --- a/src/drivers/android/device-profile-source.ts +++ b/src/drivers/android/device-profile-source.ts @@ -1,23 +1,6 @@ import { DriverCrashError, UnknownModelError, type DeviceClass } from "../../core/index.js"; import type { Filesystem, ProcessRunner } from "../../ports/index.js"; -/** - * One device profile a `DeviceProfileSource` can create an AVD from. `builtin` is today's - * `avdmanager -d ` path; `properties` is a hardware descriptor applied to `config.ini` - * after `avdmanager create avd` (see `AndroidDriver#provision`) -- there is no `avdmanager` - * device id for it because it never came from `avdmanager list device`. `name` is the - * source's own canonical spelling of the model (case may differ from what the caller asked - * for), which `AndroidDriver` needs so `DeviceSpec.model` and cache lookups stay stable. - * - * A `properties` profile has no tag and counts as a `phone`. - * - * A `builtin` profile is `custom` when `avdmanager` lists it with `OEM : User`: that is how it - * prints a profile from Android Studio's `devices.xml`, which it reads itself. - * - * `names` is every name the profile answers to, `name` first, no two equal ignoring case. - * `DeviceProfileRegistry` matches a requested model against it and lists the rest as the - * model's other names, so the two can never disagree. - */ export type DeviceProfile = | { readonly kind: "builtin"; @@ -28,6 +11,20 @@ export type DeviceProfile = /** From the entry's `Tag :` line (ADR 0015 ยง3); `undefined` for a tag the table does not know. */ readonly deviceClass: DeviceClass | undefined; } + | { + readonly kind: "library"; + readonly name: string; + readonly id: string; + readonly names: readonly string[]; + readonly deviceClass: DeviceClass; + readonly imageKind: string | undefined; + readonly apiRange: { readonly min: number; readonly max?: number }; + readonly playStore: boolean; + readonly tablet: boolean; + readonly hardware: Readonly>; + readonly bootProperties: Readonly>; + readonly copiedFrom: string; + } | { readonly kind: "properties"; readonly name: string; @@ -118,7 +115,7 @@ export class DeviceProfileRegistry { }); const modelClasses: Record = {}; for (const profile of listed.values()) { - const deviceClass = profile.kind === "builtin" ? profile.deviceClass : "phone"; + const deviceClass = profile.kind === "properties" ? "phone" : profile.deviceClass; if (deviceClass !== undefined) modelClasses[profile.name] = deviceClass; } return { customModels, modelAliases, modelClasses, models }; @@ -150,7 +147,7 @@ export class DeviceProfileRegistry { /** Made on this machine rather than shipped with the SDK. */ function isCustom(profile: DeviceProfile): boolean { - return profile.kind === "properties" || profile.custom; + return profile.kind === "properties" || (profile.kind === "builtin" && profile.custom); } /** The first profile any of whose names is `model`, ignoring case. */ @@ -444,7 +441,7 @@ export function parseDevicesXml(contents: string): readonly DevicesXmlProfile[] } /** CR, LF, or NUL -- see the rejection check at the top of the `` loop above. */ -function containsForbiddenCharacter(value: string): boolean { +export function containsForbiddenCharacter(value: string): boolean { // oxlint-disable-next-line no-control-regex -- NUL rejection is intentional, not an accidental control-character match. return /[\r\n\u0000]/.test(value); } diff --git a/src/drivers/android/image-fit.ts b/src/drivers/android/image-fit.ts new file mode 100644 index 000000000..c16c78647 --- /dev/null +++ b/src/drivers/android/image-fit.ts @@ -0,0 +1,19 @@ +export interface ImageFitInput { + readonly apiLevel: string; + readonly tag: string; + readonly tags: readonly string[]; +} + +const MIN_WEAR_PLAY_STORE_API = 25; + +export function isPlayStoreImage(image: ImageFitInput): boolean { + if (image.tags.includes("google_apis_playstore")) return true; + const [only, ...rest] = image.tags; + if (rest.length > 0) return false; + if (only === "android-automotive-playstore") return true; + return ( + only === "android-wear" && + image.tag !== "android-wear-cn" && + Number(image.apiLevel) >= MIN_WEAR_PLAY_STORE_API + ); +} diff --git a/src/drivers/android/index.test.ts b/src/drivers/android/index.test.ts index f3197596f..37a570e4f 100644 --- a/src/drivers/android/index.test.ts +++ b/src/drivers/android/index.test.ts @@ -37,6 +37,8 @@ import { type AndroidDriverDiagnostic, type AndroidEmulatorLaunchOptions, } from "./index.js"; +import type { DeviceProfileSource } from "./device-profile-source.js"; +import { LIBRARY_PROFILES, type LibraryDeviceProfile } from "./profiles/index.js"; const sdk = "/android-sdk"; const home = "/home/simlock"; @@ -1245,10 +1247,10 @@ describe("AndroidDriver", () => { { abi: "arm64-v8a", runtime: "35", tag: "google_apis" }, { abi: "x86_64", runtime: "35", tag: "google_apis" }, ], - modelAliases: { "Pixel 8": ["pixel_8"] }, - modelClasses: { "Pixel 8": "phone" }, - modelRuntimes: { "Pixel 8": ["34", "35"] }, - models: ["Pixel 8"], + modelAliases: { "Pixel 8": ["pixel_8"], "Pixel 9": ["pixel_9"] }, + modelClasses: { "Pixel 8": "phone", "Pixel 9": "phone" }, + modelRuntimes: { "Pixel 8": ["34", "35"], "Pixel 9": ["34", "35"] }, + models: ["Pixel 9", "Pixel 8"], runtimes: ["34", "35"], }); }); @@ -1268,7 +1270,7 @@ describe("AndroidDriver", () => { const catalog = await driver.listCatalog(); - expect(catalog.models).toEqual(["Pixel 8", "Pixel 9"]); + expect(catalog.models).toEqual(["Pixel 9", "Pixel 8"]); expect(catalog.modelRuntimes).toEqual({ "Pixel 8": ["33", "35"], "Pixel 9": ["33", "35"] }); }); @@ -1311,10 +1313,10 @@ describe("AndroidDriver", () => { await expect(driver.listCatalog()).resolves.toEqual({ defaultRuntime: undefined, images: [], - modelAliases: { "Pixel 8": ["pixel_8"] }, - modelClasses: { "Pixel 8": "phone" }, - modelRuntimes: { "Pixel 8": [] }, - models: ["Pixel 8"], + modelAliases: { "Pixel 8": ["pixel_8"], "Pixel 9": ["pixel_9"] }, + modelClasses: { "Pixel 8": "phone", "Pixel 9": "phone" }, + modelRuntimes: { "Pixel 8": [], "Pixel 9": [] }, + models: ["Pixel 9", "Pixel 8"], runtimes: [], }); }); @@ -1355,8 +1357,8 @@ describe("AndroidDriver", () => { const catalog = await driver.listCatalog(); - expect(catalog.models).toEqual(["Pixel 8", "automotive_1024p"]); - expect(catalog.modelAliases).toEqual({ "Pixel 8": ["pixel_8"] }); + expect(catalog.models).toEqual(["Pixel 9", "Pixel 8", "automotive_1024p"]); + expect(catalog.modelAliases).toEqual({ "Pixel 8": ["pixel_8"], "Pixel 9": ["pixel_9"] }); }); it("resolves every listed name of every listed model, in upper and lower case, to that model", async () => { @@ -1402,7 +1404,7 @@ describe("AndroidDriver", () => { const catalog = await driver.listCatalog(); - expect(catalog.models).toEqual(["Pixel 8", "Pixel 9", "pixel_8", "My Tablet"]); + expect(catalog.models).toEqual(["Pixel 9", "Pixel 8", "pixel_8", "My Tablet"]); expect(Object.keys(catalog.modelRuntimes)).toEqual(catalog.models); }); @@ -1416,7 +1418,7 @@ describe("AndroidDriver", () => { const catalog = await driver.listCatalog(); - expect(catalog.models).toEqual(["Pixel 8", "Pixel 9", "My Tablet"]); + expect(catalog.models).toEqual(["Pixel 9", "Pixel 8", "My Tablet"]); expect(catalog.customModels).toEqual(["My Tablet"]); }); @@ -1431,7 +1433,7 @@ describe("AndroidDriver", () => { const catalog = await driver.listCatalog(); - expect(catalog.models).toEqual(["Pixel 8", "Pixel 9"]); + expect(catalog.models).toEqual(["Pixel 9", "Pixel 8"]); expect(catalog).not.toHaveProperty("customModels"); }); @@ -1445,7 +1447,7 @@ describe("AndroidDriver", () => { const catalog = await driver.listCatalog(); - expect(catalog.models).toEqual(["Pixel 8", "Pixel 9"]); + expect(catalog.models).toEqual(["Pixel 9", "Pixel 8"]); expect(catalog.modelAliases).toEqual({ "Pixel 8": ["pixel_8"], "Pixel 9": ["pixel_9"] }); expect(runner.calls.filter((call) => call.command === binaries.avdmanager)).toHaveLength(1); }); @@ -2152,6 +2154,359 @@ describe("AndroidDriver", () => { }); }); + describe("library device profiles", () => { + it('resolves "Pixel 9" to the library profile when `avdmanager list device` does not list `pixel_9`', async () => { + const harness = await libraryHarness({ listing: pixelDevices }); + + const spec = await harness.resolve("Pixel 9"); + await harness.driver.provision(spec); + + expect(spec).toEqual({ + model: "Pixel 9", + osVersion: "35", + physical: false, + platform: "android", + }); + expect((await harness.config()).get("hw.lcd.height")).toBe("2424"); + expect((await harness.config()).get("hw.lcd.density")).toBe("420"); + }); + + it('resolves "Pixel 9" to the library profile when `avdmanager list device` lists `pixel_9` too', async () => { + const harness = await libraryHarness({ listing: twoPixelDevices }); + + await harness.provision("Pixel 9"); + + expect((await harness.config()).get("hw.lcd.height")).toBe("2424"); + expect(harness.seedDeviceId()).toBe("pixel_8"); + }); + + it('resolves "Pixel 9" to the library profile when `devices.xml` defines a "Pixel 9"', async () => { + const harness = await libraryHarness({ + devicesXml: customDeviceXml("Pixel 9", 4096), + listing: pixelDevices, + }); + + await harness.provision("Pixel 9"); + + const config = await harness.config(); + expect(config.get("hw.lcd.height")).toBe("2424"); + expect(config.get("hw.ramSize")).toBe("2G"); + }); + + it("resolves `pixel_9` and `PIXEL 9` to the library's Pixel 9", async () => { + for (const spelling of ["pixel_9", "PIXEL 9"]) { + const harness = await libraryHarness({ listing: pixelDevices }); + + const spec = await harness.resolve(spelling); + await harness.driver.provision(spec); + + expect(spec.model, spelling).toBe("Pixel 9"); + expect((await harness.config()).get("hw.lcd.height"), spelling).toBe("2424"); + } + }); + + it("resolves a model the library does not have through the SDK, then devices.xml, as today", async () => { + const sdkHarness = await libraryHarness({ + devicesXml: customDeviceXml("Custom A", 4096), + listing: pixelDevices, + }); + const sdkSpec = await sdkHarness.resolve("Pixel 8"); + await sdkHarness.driver.provision(sdkSpec); + + expect(sdkSpec.model).toBe("Pixel 8"); + expect(sdkHarness.seedDeviceId()).toBe("pixel_8"); + expect((await sdkHarness.config()).has("hw.lcd.height")).toBe(false); + + const userHarness = await libraryHarness({ + devicesXml: customDeviceXml("Custom A", 4096), + listing: pixelDevices, + secondList: true, + }); + const userSpec = await userHarness.resolve("Custom A"); + await userHarness.driver.provision(userSpec); + + expect(userSpec.model).toBe("Custom A"); + expect((await userHarness.config()).get("hw.ramSize")).toBe("4096"); + }); + + it("lists Pixel 9 first in the catalog, once, as `phone`, not custom, with `pixel_9` as its other name", async () => { + const filesystem = await androidFilesystem(); + await writeDevicesXml( + filesystem, + customDeviceXml("pixel_9", 4096) + customDeviceXml("PIXEL 9", 4096), + ); + const runner = new ScriptedProcessRunner([ + processResult(binaries.avdmanager, ["list", "device"], twoPixelDevices), + ]); + const driver = await createDriver(filesystem, runner); + + const catalog = await driver.listCatalog(); + + expect(catalog.models[0]).toBe("Pixel 9"); + expect(catalog.models.filter((model) => model.toLocaleLowerCase() === "pixel 9")).toEqual([ + "Pixel 9", + ]); + expect(catalog.modelClasses["Pixel 9"]).toBe("phone"); + expect(catalog.customModels ?? []).not.toContain("Pixel 9"); + expect(catalog.modelAliases["Pixel 9"]).toEqual(["pixel_9"]); + }); + + it("provisions a library device with every `hardware` value of the profile in `config.ini`", async () => { + const harness = await libraryHarness({ listing: pixelDevices }); + + await harness.provision("Pixel 9"); + + const config = await harness.config(); + const hardware = Object.entries(libraryPixel9().hardware); + expect(hardware.length).toBeGreaterThan(100); + expect(hardware.filter(([key, value]) => config.get(key) !== value)).toEqual([]); + }); + + it("provisions identical `hw.*` and `vm.heapSize` lines whether `avdmanager list device` lists `pixel_9` or not", async () => { + const without = await libraryHarness({ listing: pixelDevices }); + const withListed = await libraryHarness({ + listing: twoPixelDevices, + seed: seedConfig(["hw.gpu.mode=host", "hw.lcd.density=480", "hw.ramSize=8G"]), + }); + + await without.provision("Pixel 9"); + await withListed.provision("Pixel 9"); + + const hardwareLines = async (harness: typeof without) => + (await harness.lines()).filter((line) => /^(hw\.|vm\.heapSize=)/.test(line)).sort(); + const expected = await hardwareLines(without); + expect(expected.length).toBeGreaterThan(100); + expect(await hardwareLines(withListed)).toEqual(expected); + }); + + it("removes every `hw.*` (except `hw.cpu.arch`), `vm.heapSize` and `skin.*` line the seed wrote that the profile does not set", async () => { + const harness = await libraryHarness({ + profiles: [testLibraryProfile({ hardware: { "hw.lcd.height": "100" } })], + seed: seedConfig(["hw.seedOnly=yes", "skin.dynamic=yes"]), + }); + + await harness.provision("Test Phone"); + + const lines = await harness.lines(); + expect(lines.filter((line) => line.startsWith("skin."))).toEqual([]); + expect(lines.filter((line) => line.startsWith("vm.heapSize"))).toEqual([]); + expect(lines.filter((line) => line.startsWith("hw.")).sort()).toEqual([ + "hw.cpu.arch=arm64", + "hw.lcd.height=100", + ]); + }); + + it("keeps `image.sysdir.1`, `tag.id`, `abi.type`, `target`, `hw.cpu.arch`, `disk.dataPartition.size` and `showDeviceFrame` as `avdmanager` wrote them", async () => { + const harness = await libraryHarness({ listing: pixelDevices }); + + await harness.provision("Pixel 9"); + + const config = await harness.config(); + expect( + [ + "image.sysdir.1", + "tag.id", + "abi.type", + "target", + "hw.cpu.arch", + "disk.dataPartition.size", + "showDeviceFrame", + ].map((key) => `${key}=${config.get(key)}`), + ).toEqual([ + "image.sysdir.1=system-images/android-35/google_apis/arm64-v8a/", + "tag.id=google_apis", + "abi.type=arm64-v8a", + "target=android-35", + "hw.cpu.arch=arm64", + "disk.dataPartition.size=6G", + "showDeviceFrame=yes", + ]); + }); + + it("sets `PlayStore.enabled=yes` on a Play Store image when the profile allows Play Store, and `no` on a `google_apis` image or for a profile that does not", async () => { + const playStore = { imageTag: "google_apis_playstore" }; + const allowed = await libraryHarness({ ...playStore, listing: pixelDevices }); + await allowed.provision("Pixel 9"); + expect((await allowed.config()).get("PlayStore.enabled")).toBe("yes"); + + const googleApis = await libraryHarness({ + listing: pixelDevices, + seed: seedConfig(["PlayStore.enabled=yes"]), + }); + await googleApis.provision("Pixel 9"); + expect((await googleApis.config()).get("PlayStore.enabled")).toBe("no"); + + const refused = await libraryHarness({ + ...playStore, + profiles: [testLibraryProfile({ playStore: false })], + seed: seedConfig(["PlayStore.enabled=yes"]), + }); + await refused.provision("Test Phone"); + expect((await refused.config()).get("PlayStore.enabled")).toBe("no"); + }); + + it("reads an image's tags from `SystemImage.TagId`, and from the folder name when it has none", async () => { + const playStoreOf = async (imageTag: string, imageProperties: string) => { + const harness = await libraryHarness({ imageProperties, imageTag, listing: pixelDevices }); + await harness.provision("Pixel 9"); + return (await harness.config()).get("PlayStore.enabled"); + }; + + expect(await playStoreOf("custom-folder", "SystemImage.TagId=google_apis_playstore\n")).toBe( + "yes", + ); + expect(await playStoreOf("google_apis_playstore", "")).toBe("yes"); + expect(await playStoreOf("google_apis_playstore", "Pkg.Revision=1\n")).toBe("yes"); + expect(await playStoreOf("google_apis_playstore", "SystemImage.TagId=google_apis\n")).toBe( + "no", + ); + }); + + it("writes the profile's boot properties to `boot.prop`, and removes a seed's `boot.prop` when the profile has none", async () => { + const withProperties = await libraryHarness({ + profiles: [ + testLibraryProfile({ bootProperties: { "persist.x": "y", "ro.simlock.test": "1" } }), + ], + seedBootProp: "ro.seed=1\n", + }); + await withProperties.provision("Test Phone"); + const written = await withProperties.filesystem.readFile(withProperties.bootPropPath); + expect( + written + .split("\n") + .filter((line) => line !== "") + .sort(), + ).toEqual(["persist.x=y", "ro.simlock.test=1"]); + + const without = await libraryHarness({ listing: pixelDevices, seedBootProp: "ro.seed=1\n" }); + await expect(without.filesystem.exists(without.bootPropPath)).resolves.toBe(true); + await without.provision("Pixel 9"); + await expect(without.filesystem.exists(without.bootPropPath)).resolves.toBe(false); + }); + + it("captures the config hash after the library's keys are written", async () => { + const hashOf = async (profile: LibraryDeviceProfile, seed: string) => { + const harness = await libraryHarness({ profiles: [profile], seed }); + const device = await harness.provision("Test Phone"); + return (device.driverData as { configHash: string }).configHash; + }; + const ram = (value: string) => + testLibraryProfile({ hardware: { "hw.lcd.height": "100", "hw.ramSize": value } }); + + const small = await hashOf(ram("2G"), seedConfig([])); + const large = await hashOf(ram("4G"), seedConfig([])); + const largeOverOtherSeed = await hashOf(ram("4G"), seedConfig(["hw.ramSize=512M"])); + + expect(small).not.toBe(large); + expect(largeOverOtherSeed).toBe(large); + }); + + it.each([ + ["a hardware value", "\r"], + ["a hardware value", "\n"], + ["a hardware value", "\u0000"], + ["a hardware key", "\r"], + ["a hardware key", "\n"], + ["a hardware key", "\u0000"], + ["a boot property value", "\r"], + ["a boot property value", "\n"], + ["a boot property value", "\u0000"], + ] as const)( + "refuses %s with %j before `avdmanager create avd` runs", + async (where, character) => { + const profileWith = (inserted: string) => + testLibraryProfile( + where === "a hardware value" + ? { hardware: { "hw.ramSize": `2${inserted}G` } } + : where === "a hardware key" + ? { hardware: { [`hw.bad${inserted}key`]: "1" } } + : { bootProperties: { "ro.x": `a${inserted}b` } }, + ); + const accepted = await libraryHarness({ profiles: [profileWith("-")] }); + await accepted.provision("Test Phone"); + expect(accepted.createCalls()).toHaveLength(1); + + const refused = await libraryHarness({ profiles: [profileWith(character)] }); + + await expect(refused.provision("Test Phone")).rejects.toThrow(); + expect(refused.createCalls()).toEqual([]); + }, + ); + + it("refuses NUL in a `devices.xml` value, through the one shared check", async () => { + const profileNamed = (name: string): DeviceProfileSource => ({ + async profiles() { + return [ + { + hardwareProperties: { "hw.device.name": name }, + kind: "properties" as const, + name: "Custom A", + names: ["Custom A"], + }, + ]; + }, + }); + const accepted = await libraryHarness({ sources: [profileNamed("Custom A")] }); + await accepted.provision("Custom A"); + expect((await accepted.config()).get("hw.device.name")).toBe("Custom A"); + + const refused = await libraryHarness({ sources: [profileNamed("Custom\u0000A")] }); + + await expect(refused.provision("Custom A")).rejects.toThrow(); + }); + + it("refuses NUL in a `simlock.mark` value, through the one shared check", async () => { + const accepted = await provisionedHarness({ + firstMarkToken: "tok-en", + ids: ["one", "tok-en"], + }); + await accepted.driver.makeReady(accepted.device); + const acceptedConfig = await accepted.filesystem.readFile( + `${avdDirectory}/simlock_one.avd/config.ini`, + ); + expect(acceptedConfig).toContain("simlock.mark=tok-en"); + + const refused = await provisionedHarness({ + firstMarkToken: "tok\u0000en", + ids: ["one", "tok\u0000en"], + }); + + await expect(refused.driver.makeReady(refused.device)).rejects.toThrow(/Refusing to merge/); + const refusedConfig = await refused.filesystem.readFile( + `${avdDirectory}/simlock_one.avd/config.ini`, + ); + expect(refusedConfig).not.toContain("simlock.mark="); + }); + + it("rethrows and deletes nothing when a write after `avdmanager create avd` fails", async () => { + const filesystem = new WriteFailureFilesystem( + `${avdDirectory}/simlock_one.avd/config.ini`, + new Error("disk full"), + ); + const harness = await libraryHarness({ filesystem, listing: pixelDevices }); + const seeded = await filesystem.readFile(harness.configPath); + filesystem.armed = true; + + await expect(harness.provision("Pixel 9")).rejects.toThrow("disk full"); + + filesystem.armed = false; + expect(harness.createCalls()).toHaveLength(1); + expect(harness.runner.calls.some((call) => call.args.includes("delete"))).toBe(false); + await expect(filesystem.readFile(harness.configPath)).resolves.toBe(seeded); + }); + + it("seeds `avdmanager create avd` with the first profile `avdmanager list device` prints, also when it lists `pixel_9`", async () => { + const listsPixel9 = await libraryHarness({ listing: twoPixelDevices }); + await listsPixel9.provision("Pixel 9"); + + const lacksPixel9 = await libraryHarness({ listing: pixelDevices }); + await lacksPixel9.provision("Pixel 9"); + + expect(listsPixel9.seedDeviceId()).toBe("pixel_8"); + expect(lacksPixel9.seedDeviceId()).toBe("pixel_8"); + }); + }); + describe("Android SDK license handling", () => { const licenseNotAcceptedOutput = "Warning: License for package Android SDK Platform 35 not accepted.\n\n" + @@ -3728,6 +4083,7 @@ live( 480_000, ); +// fallow-ignore-next-line complexity -- one test harness builder; each option is a plain pass-through to a collaborator. async function provisionedHarness( options: { readonly bootCompleted?: string; @@ -3737,8 +4093,10 @@ async function provisionedHarness( readonly forBaselineReclaim?: boolean; readonly forFullCleanBoot?: boolean; readonly forReclaim?: boolean; + readonly ids?: readonly string[]; readonly initialAdbFailures?: number; readonly readinessTimeoutMs?: number; + readonly firstMarkToken?: string; /** Invocations the test makes after the harness's own, in order. */ readonly afterwards?: readonly ScriptedProcessExpectation[]; } = {}, @@ -3763,7 +4121,7 @@ async function provisionedHarness( // The mock idGenerator's first call is spent on the AVD name above, so `makeReady`'s tail // mark write is always the second call, and (when a snapshot-reclaim follows) the third. - const firstMarkToken = "device-2"; + const firstMarkToken = options.firstMarkToken ?? "device-2"; const secondMarkToken = "device-3"; if (options.forReclaim === true) { @@ -3819,7 +4177,7 @@ async function provisionedHarness( const driver = await createDriver(filesystem, runner, { clock, ...(options.emulator === undefined ? {} : { emulator: options.emulator }), - ids: ["one"], + ids: options.ids ?? ["one"], ...(options.readinessTimeoutMs === undefined ? {} : { readinessTimeoutMs: options.readinessTimeoutMs }), @@ -3949,6 +4307,7 @@ async function createDriver( /** `ANDROID_AVD_HOME` in the environment the daemon started with; unset by default. */ readonly avdHome?: string; readonly clock?: FakeClock; + readonly deviceProfileSources?: readonly DeviceProfileSource[]; readonly driverConfig?: Readonly>; readonly emulator?: AndroidEmulatorLaunchOptions; /** The ABI this host runs natively; `arm64-v8a` unless a test says otherwise. */ @@ -3994,6 +4353,7 @@ async function createDriver( * without the helper itself turning into a pile of conditionals. */ function onlyProvided(options: { readonly acceptAndroidLicenses?: boolean; + readonly deviceProfileSources?: readonly DeviceProfileSource[]; readonly emulator?: AndroidEmulatorLaunchOptions; readonly onDiagnostic?: (diagnostic: AndroidDriverDiagnostic) => void; readonly readinessTimeoutMs?: number; @@ -4002,6 +4362,9 @@ function onlyProvided(options: { ...(options.acceptAndroidLicenses === undefined ? {} : { acceptAndroidLicenses: options.acceptAndroidLicenses }), + ...(options.deviceProfileSources === undefined + ? {} + : { deviceProfileSources: options.deviceProfileSources }), ...(options.emulator === undefined ? {} : { emulator: options.emulator }), ...(options.onDiagnostic === undefined ? {} : { onDiagnostic: options.onDiagnostic }), ...(options.readinessTimeoutMs === undefined @@ -4019,6 +4382,162 @@ async function recordRunningAdbServer(filesystem: Filesystem, port = adbServerPo ); } +const SEED_LINES = [ + "avd.ini.encoding=UTF-8", + "hw.cpu.arch=arm64", + "hw.ramSize=1G", + "hw.lcd.density=1", + "hw.seedOnly=yes", + "image.sysdir.1=system-images/android-35/google_apis/arm64-v8a/", + "tag.id=google_apis", + "abi.type=arm64-v8a", + "target=android-35", + "disk.dataPartition.size=6G", + "showDeviceFrame=yes", + "skin.name=pixel_8", + "skin.path=skins/pixel_8", + "vm.heapSize=64M", + "PlayStore.enabled=no", +]; + +function seedConfig(extra: readonly string[]): string { + return `${[...SEED_LINES.filter((line) => !extra.some((added) => added.split("=")[0] === line.split("=")[0])), ...extra].join("\n")}\n`; +} + +function libraryPixel9(): LibraryDeviceProfile { + const profile = LIBRARY_PROFILES.find((candidate) => candidate.id === "pixel_9"); + if (profile === undefined) throw new Error("the library has no profile with id pixel_9"); + return profile; +} + +function testLibraryProfile(overrides: Partial = {}): LibraryDeviceProfile { + return { + apiRange: { min: 1 }, + bootProperties: {}, + copiedFrom: "20.0", + deviceClass: "phone", + hardware: { "hw.lcd.height": "100", "hw.ramSize": "2G" }, + id: "test_phone", + imageKind: undefined, + kind: "library", + name: "Test Phone", + names: ["Test Phone", "test_phone"], + playStore: true, + tablet: false, + ...overrides, + }; +} + +class WriteFailureFilesystem extends MemoryFilesystem { + armed = false; + + constructor( + private readonly failingPath: string, + private readonly error: Error, + ) { + super(); + } + + override async writeFileAtomic( + ...args: Parameters + ): Promise { + if (this.armed && args[0] === this.failingPath) { + throw this.error; + } + return super.writeFileAtomic(...args); + } +} + +// fallow-ignore-next-line complexity -- one test harness builder; each option is a plain pass-through to a collaborator. +async function libraryHarness( + options: { + readonly devicesXml?: string; + readonly filesystem?: MemoryFilesystem; + readonly imageProperties?: string; + readonly imageTag?: string; + readonly listing?: string; + readonly profiles?: readonly LibraryDeviceProfile[]; + readonly secondList?: boolean; + readonly seed?: string; + readonly seedBootProp?: string; + readonly sources?: readonly DeviceProfileSource[]; + } = {}, +) { + const tag = options.imageTag ?? "google_apis"; + const filesystem = options.filesystem ?? new MemoryFilesystem(); + await androidFilesystem({ images: [["35", tag, "arm64-v8a"]] }, filesystem); + const imageProperties = options.imageProperties ?? `Pkg.Revision=1\nSystemImage.TagId=${tag}\n`; + if (imageProperties !== "") { + await filesystem.writeFileAtomic( + `${sdk}/system-images/android-35/${tag}/arm64-v8a/source.properties`, + imageProperties, + ); + } + if (options.devicesXml !== undefined) { + await writeDevicesXml(filesystem, options.devicesXml); + } + const avd = `${avdDirectory}/simlock_one.avd`; + const configPath = `${avd}/config.ini`; + const bootPropPath = `${avd}/boot.prop`; + await filesystem.mkdirp(avd); + await filesystem.writeFileAtomic(configPath, options.seed ?? seedConfig([])); + if (options.seedBootProp !== undefined) { + await filesystem.writeFileAtomic(bootPropPath, options.seedBootProp); + } + const listing = options.listing ?? pixelDevices; + const runner = new ScriptedProcessRunner([ + processResult(binaries.avdmanager, ["list", "device"], listing), + ...(options.secondList === true + ? [processResult(binaries.avdmanager, ["list", "device"], listing)] + : []), + processResult(binaries.avdmanager, [ + "create", + "avd", + "-n", + "simlock_one", + "-k", + /.+/, + "-d", + /.+/, + ]), + processResult(binaries.emulator, ["-version"], "Android emulator version 36.1.9"), + ]); + const sources = + options.profiles === undefined + ? options.sources + : [{ profiles: async () => options.profiles ?? [] }]; + const driver = await createDriver(filesystem, runner, { + ids: ["one"], + ...(sources === undefined ? {} : { deviceProfileSources: sources }), + }); + const resolve = (model: string) => + driver.resolveSpec({ model, osVersion: "35", platform: "android" }); + const readLines = async () => + (await filesystem.readFile(configPath)).split("\n").filter((line) => line !== ""); + return { + bootPropPath, + config: async () => + new Map( + (await readLines()).map((line) => [ + line.slice(0, line.indexOf("=")), + line.slice(line.indexOf("=") + 1), + ]), + ), + configPath, + createCalls: () => runner.calls.filter((call) => call.args[0] === "create"), + driver, + filesystem, + lines: readLines, + provision: async (model: string) => driver.provision(await resolve(model)), + resolve, + runner, + seedDeviceId: () => { + const create = runner.calls.find((call) => call.args[0] === "create"); + return create?.args[create.args.indexOf("-d") + 1]; + }, + }; +} + async function writeDevicesXml(filesystem: MemoryFilesystem, deviceBodies: string): Promise { await filesystem.mkdirp(`${home}/.android`); await filesystem.writeFileAtomic( diff --git a/src/drivers/android/index.ts b/src/drivers/android/index.ts index 661fb2469..0d0ffd925 100644 --- a/src/drivers/android/index.ts +++ b/src/drivers/android/index.ts @@ -61,6 +61,7 @@ import { isAndroidDriverData, type AndroidDriverData } from "./data.js"; import { AndroidPhysicalHandler, PHYSICAL_RECLAIM_ESTIMATE_MS } from "./physical-handler.js"; import { BuiltinDeviceProfileSource, + containsForbiddenCharacter, DeviceProfileRegistry, parseAvdmanagerDeviceProfiles, UserDeviceProfileSource, @@ -68,6 +69,8 @@ import { type DeviceProfileSourceDiagnostic, type DeviceProfile, } from "./device-profile-source.js"; +import { isPlayStoreImage } from "./image-fit.js"; +import { LibraryDeviceProfileSource } from "./profiles/index.js"; import { type AndroidSdkPaths, locateSdk } from "./sdk-paths.js"; export { AdbServerUnavailableError } from "./adb-server.js"; @@ -173,11 +176,6 @@ export interface AndroidDriverOptions { /** This driver's own `drivers.android` block, handed over unread by the core. */ readonly driverConfig: Readonly>; /** The environment every scoped invocation is layered on top of; `process.env` in production. */ - /** - * Ordered device-profile sources, first match wins (see `DeviceProfileRegistry`). Defaults - * to `[builtin, user]` -- `avdmanager list device` first, then a read-only parse of - * `~/.android/devices.xml`, so a name defined in both resolves to the built-in. - */ readonly deviceProfileSources?: readonly DeviceProfileSource[]; readonly env: Readonly>; readonly filesystem: Filesystem; @@ -256,6 +254,7 @@ interface SystemImage { readonly apiLevel: string; readonly path: string; readonly tag: string; + readonly tags: readonly string[]; readonly version: string; } @@ -832,11 +831,9 @@ export class AndroidDriver implements Driver { const avdName = `simlock_${this.#idGenerator.generate()}`; const packageName = systemImagePackage(image.apiLevel, image.tag, image.abi); - // A `builtin` profile already carries the `avdmanager` device id `-d` wants. A - // `properties` profile has none -- it never came from `avdmanager list device` -- so - // `avdmanager create avd` is seeded with *some* built-in device (only to skip the - // interactive "custom hardware profile?" prompt) and the profile's own properties then - // overwrite that seed's config.ini values below, before anything reads them. + if (profile.kind === "library") { + assertLibraryProfileWritable(profile); + } const seedDeviceId = profile.kind === "builtin" ? profile.avdmanagerId : await this.#defaultAvdmanagerDeviceId(); await this.#runOrThrow(this.#sdk.avdmanager, [ @@ -857,6 +854,10 @@ export class AndroidDriver implements Driver { await this.#applyHardwareProperties(avdName, profile.hardwareProperties); } + if (profile.kind === "library") { + await this.#applyLibraryProfile(avdName, profile, image); + } + const configHash = await this.#configHash(avdName, image); // No console port yet: `makeReady` reserves one at the device's first boot. const driverData: AndroidDriverData = { @@ -1270,6 +1271,31 @@ export class AndroidDriver implements Driver { return first.id; } + async #applyLibraryProfile( + avdName: string, + profile: Extract, + image: SystemImage, + ): Promise { + await this.#mergeConfigIniLines( + avdName, + { + ...profile.hardware, + "PlayStore.enabled": profile.playStore && isPlayStoreImage(image) ? "yes" : "no", + }, + (line) => !isSeedHardwareLine(line), + ); + const bootPropPath = `${this.#configIniPath(avdName).replace(/\/config\.ini$/, "")}/boot.prop`; + const properties = Object.entries(profile.bootProperties); + if (properties.length > 0) { + await this.#filesystem.writeFileAtomic( + bootPropPath, + `${properties.map(([key, value]) => `${key}=${value}`).join("\n")}\n`, + ); + } else if (await this.#filesystem.exists(bootPropPath)) { + await this.#filesystem.rm(bootPropPath); + } + } + /** Merges `properties` into the AVD's `config.ini` -- see `#mergeConfigIniLines`. */ async #applyHardwareProperties( avdName: string, @@ -1576,6 +1602,7 @@ export class AndroidDriver implements Driver { apiLevel: apiMatch[1], path, tag, + tags: await systemImageTags(this.#filesystem, path, tag), version: await systemImageVersion(this.#filesystem, path), }); } @@ -1696,31 +1723,15 @@ export class AndroidDriver implements Driver { await this.#mergeConfigIniLines(avdName, { [DURABLE_MARK_KEY]: token }); } - /** - * Reads `avdName`'s `config.ini`, merges `entries` into it -- overwriting any key already - * present, appending the rest -- and writes it back atomically. Shared by - * `#applyHardwareProperties` and `#writeDurableMark`, the driver's two config.ini - * read-modify-write sites. A missing file (the AVD's config.ini not created yet) starts the - * merge from empty content; any other read failure is rethrown rather than treated as an - * empty file -- silently starting from "" on, say, an EACCES or EIO would write back only - * `entries` and clobber whatever config.ini already held. - * - * Defense in depth against a config.ini injection: `#applyHardwareProperties` calls this with - * values sourced from a device profile (`avdmanager list device`, or a parsed - * `~/.android/devices.xml` -- see `device-profile-source.ts`'s own line-break rejection at the - * parse boundary). A key or value containing a line break would let one logical property - * inject arbitrary extra `config.ini` lines once joined in -- rejected here unconditionally, - * independent of and in addition to that parse-time check, so this merge is never the only - * thing standing between untrusted input and config.ini. - */ async #mergeConfigIniLines( avdName: string, entries: Readonly>, + keepLine: (line: string) => boolean = () => true, ): Promise { for (const [key, value] of Object.entries(entries)) { - if (containsLineBreak(key) || containsLineBreak(value)) { + if (containsForbiddenCharacter(key) || containsForbiddenCharacter(value)) { throw new DriverCrashError( - `Refusing to merge config.ini entry with an embedded line break (key ${JSON.stringify(key)})`, + `Refusing to merge config.ini entry with a line break or NUL (key ${JSON.stringify(key)})`, ); } } @@ -1734,7 +1745,9 @@ export class AndroidDriver implements Driver { } contents = ""; } - const lines = contents === "" ? [] : contents.replace(/\r?\n$/, "").split(/\r?\n/); + const lines = (contents === "" ? [] : contents.replace(/\r?\n$/, "").split(/\r?\n/)).filter( + keepLine, + ); for (const [key, value] of Object.entries(entries)) { const line = `${key}=${value}`; const existingIndex = lines.findIndex((entry) => entry.startsWith(`${key}=`)); @@ -2386,9 +2399,49 @@ function portsFromAdbDevices(output: string): number[] { .filter((port) => Number.isInteger(port)); } -/** See `#mergeConfigIniLines`'s defense-in-depth check. */ -function containsLineBreak(value: string): boolean { - return /[\r\n]/.test(value); +function isSeedHardwareLine(line: string): boolean { + return ( + (line.startsWith("hw.") && !line.startsWith("hw.cpu.arch=")) || + line.startsWith("vm.heapSize=") || + line.startsWith("skin.") + ); +} + +function assertLibraryProfileWritable( + profile: Extract, +): void { + for (const [key, value] of [ + ...Object.entries(profile.hardware), + ...Object.entries(profile.bootProperties), + ]) { + if (containsForbiddenCharacter(key) || containsForbiddenCharacter(value)) { + throw new DriverCrashError( + `Refusing library profile ${JSON.stringify(profile.name)}: ${JSON.stringify(key)} holds a line break or NUL`, + ); + } + } +} + +async function systemImageTags( + filesystem: Filesystem, + imagePath: string, + folder: string, +): Promise { + try { + const properties = await filesystem.readFile(`${imagePath}/source.properties`); + const tagId = properties + .split(/\r?\n/) + .find((line) => line.startsWith("SystemImage.TagId=")) + ?.slice("SystemImage.TagId=".length) + .trim(); + const tags = (tagId ?? "") + .split(",") + .map((tag) => tag.trim()) + .filter((tag) => tag !== ""); + return tags.length > 0 ? tags : [folder]; + } catch { + return [folder]; + } } /** @@ -2462,8 +2515,7 @@ function hasUnacceptedLicense(result: ProcessResult): boolean { } /** - * `[builtin, user]`: `avdmanager list device` first, then a read-only parse of Android - * Studio's `~/.android/devices.xml`. `ANDROID_SDK_HOME` (not `ANDROID_AVD_HOME`, which only + * why: `ANDROID_SDK_HOME` (not `ANDROID_AVD_HOME`, which only * relocates created AVDs) is the historical env var Android tooling uses to relocate the whole * `~/.android` directory, including `devices.xml`. */ @@ -2475,6 +2527,7 @@ function defaultDeviceProfileSources( ): readonly DeviceProfileSource[] { const devicesXmlPath = `${options.env.ANDROID_SDK_HOME ?? options.homeDirectory}/.android/devices.xml`; return [ + new LibraryDeviceProfileSource(), // Scoped like every other call: an unscoped `avdmanager` would read the user's `~/.android`. new BuiltinDeviceProfileSource(sdk.avdmanager, options.processRunner, env), new UserDeviceProfileSource(devicesXmlPath, options.filesystem, onDiagnostic), diff --git a/src/drivers/android/profiles/fixtures/pixel-9.config.ini b/src/drivers/android/profiles/fixtures/pixel-9.config.ini new file mode 100644 index 000000000..c92861372 --- /dev/null +++ b/src/drivers/android/profiles/fixtures/pixel-9.config.ini @@ -0,0 +1,141 @@ +PlayStore.enabled=no +abi.type=arm64-v8a +avd.id= +avd.ini.encoding=UTF-8 +avd.name= +disk.cachePartition=yes +disk.cachePartition.size=66MB +disk.dataPartition.path= +disk.dataPartition.size=6G +disk.systemPartition.size=0 +disk.vendorPartition.size=0 +environment.height=0 +environment.width=0 +fastboot.forceChosenSnapshotBoot=no +fastboot.forceColdBoot=no +fastboot.forceFastBoot=yes +firstboot.bootFromDownloadableSnapshot=yes +firstboot.bootFromLocalSnapshot=yes +firstboot.saveToLocalSnapshot=yes +hw.accelerometer=yes +hw.accelerometer_uncalibrated=yes +hw.arc=no +hw.arc.autologin=no +hw.audioInput=yes +hw.audioOutput=yes +hw.battery=yes +hw.camera.back=emulated +hw.camera.back.orientation=90 +hw.camera.front=none +hw.camera.front.orientation=90 +hw.cpu.arch=arm64 +hw.cpu.ncore=4 +hw.dPad=no +hw.device.hash2=MD5:5478e3411cc0e0441240e736eb14c07a +hw.device.manufacturer=Google +hw.device.name=pixel_9 +hw.display1.density=0 +hw.display1.flag=0 +hw.display1.height=0 +hw.display1.width=0 +hw.display1.xOffset=-1 +hw.display1.yOffset=-1 +hw.display2.density=0 +hw.display2.flag=0 +hw.display2.height=0 +hw.display2.width=0 +hw.display2.xOffset=-1 +hw.display2.yOffset=-1 +hw.display3.density=0 +hw.display3.flag=0 +hw.display3.height=0 +hw.display3.width=0 +hw.display3.xOffset=-1 +hw.display3.yOffset=-1 +hw.displayRegion.0.1.height=0 +hw.displayRegion.0.1.width=0 +hw.displayRegion.0.1.xOffset=-1 +hw.displayRegion.0.1.yOffset=-1 +hw.displayRegion.0.2.height=0 +hw.displayRegion.0.2.width=0 +hw.displayRegion.0.2.xOffset=-1 +hw.displayRegion.0.2.yOffset=-1 +hw.displayRegion.0.3.height=0 +hw.displayRegion.0.3.width=0 +hw.displayRegion.0.3.xOffset=-1 +hw.displayRegion.0.3.yOffset=-1 +hw.gltransport=pipe +hw.gltransport.asg.dataRingSize=32768 +hw.gltransport.asg.writeBufferSize=1048576 +hw.gltransport.asg.writeStepSize=4096 +hw.gltransport.drawFlushInterval=800 +hw.gps=yes +hw.gpu.enabled=no +hw.gpu.mode=auto +hw.gsmModem=yes +hw.gyroscope=yes +hw.hotplug_multi_display=no +hw.initialOrientation=portrait +hw.keyboard=no +hw.keyboard.charmap=qwerty2 +hw.keyboard.lid=yes +hw.lcd.backlight=yes +hw.lcd.circular=false +hw.lcd.density=420 +hw.lcd.depth=16 +hw.lcd.height=2424 +hw.lcd.transparent=false +hw.lcd.vsync=60 +hw.lcd.width=1080 +hw.mainKeys=no +hw.multi_display_window=no +hw.ramSize=2G +hw.rotaryInput=no +hw.screen=multi-touch +hw.sdCard=yes +hw.sensor.hinge=no +hw.sensor.hinge.count=0 +hw.sensor.hinge.fold_to_displayRegion.0.1_at_posture=1 +hw.sensor.hinge.resizable.config=1 +hw.sensor.hinge.sub_type=0 +hw.sensor.hinge.type=0 +hw.sensor.roll=no +hw.sensor.roll.count=0 +hw.sensor.roll.resize_to_displayRegion.0.1_at_posture=6 +hw.sensor.roll.resize_to_displayRegion.0.2_at_posture=6 +hw.sensor.roll.resize_to_displayRegion.0.3_at_posture=6 +hw.sensors.gyroscope_uncalibrated=yes +hw.sensors.heading=no +hw.sensors.heart_rate=no +hw.sensors.humidity=yes +hw.sensors.light=yes +hw.sensors.magnetic_field=yes +hw.sensors.magnetic_field_uncalibrated=yes +hw.sensors.orientation=yes +hw.sensors.pressure=yes +hw.sensors.proximity=yes +hw.sensors.rgbclight=no +hw.sensors.temperature=yes +hw.sensors.wrist_tilt=no +hw.touchpad0=no +hw.touchpad0.height=400 +hw.touchpad0.width=600 +hw.trackBall=no +hw.useext4=yes +image.sysdir.1=system-images/android-35/default/arm64-v8a/ +kernel.newDeviceNaming=autodetect +kernel.supportsYaffs2=autodetect +runtime.network.latency=none +runtime.network.speed=full +sdcard.size=512 MB +showDeviceFrame=yes +tag.display=Default Android System Image +tag.displaynames=Default Android System Image +tag.id=default +tag.ids=default +target=android-35 +test.delayAdbTillBootComplete=0 +test.monitorAdb=0 +test.quitAfterBootTimeOut=-1 +userdata.useQcow2=no +vm.heapSize=228M diff --git a/src/drivers/android/profiles/hardware-keys.ts b/src/drivers/android/profiles/hardware-keys.ts new file mode 100644 index 000000000..f86966f12 --- /dev/null +++ b/src/drivers/android/profiles/hardware-keys.ts @@ -0,0 +1,106 @@ +export const LIBRARY_HARDWARE_KEYS: readonly string[] = [ + "hw.accelerometer", + "hw.accelerometer_uncalibrated", + "hw.arc", + "hw.arc.autologin", + "hw.audioInput", + "hw.audioOutput", + "hw.battery", + "hw.camera.back", + "hw.camera.back.orientation", + "hw.camera.front", + "hw.camera.front.orientation", + "hw.cpu.ncore", + "hw.dPad", + "hw.device.manufacturer", + "hw.device.name", + "hw.display1.density", + "hw.display1.flag", + "hw.display1.height", + "hw.display1.width", + "hw.display1.xOffset", + "hw.display1.yOffset", + "hw.display2.density", + "hw.display2.flag", + "hw.display2.height", + "hw.display2.width", + "hw.display2.xOffset", + "hw.display2.yOffset", + "hw.display3.density", + "hw.display3.flag", + "hw.display3.height", + "hw.display3.width", + "hw.display3.xOffset", + "hw.display3.yOffset", + "hw.displayRegion.0.1.height", + "hw.displayRegion.0.1.width", + "hw.displayRegion.0.1.xOffset", + "hw.displayRegion.0.1.yOffset", + "hw.displayRegion.0.2.height", + "hw.displayRegion.0.2.width", + "hw.displayRegion.0.2.xOffset", + "hw.displayRegion.0.2.yOffset", + "hw.displayRegion.0.3.height", + "hw.displayRegion.0.3.width", + "hw.displayRegion.0.3.xOffset", + "hw.displayRegion.0.3.yOffset", + "hw.gltransport", + "hw.gltransport.asg.dataRingSize", + "hw.gltransport.asg.writeBufferSize", + "hw.gltransport.asg.writeStepSize", + "hw.gltransport.drawFlushInterval", + "hw.gps", + "hw.gpu.enabled", + "hw.gpu.mode", + "hw.gsmModem", + "hw.gyroscope", + "hw.hotplug_multi_display", + "hw.initialOrientation", + "hw.keyboard", + "hw.keyboard.charmap", + "hw.keyboard.lid", + "hw.lcd.backlight", + "hw.lcd.circular", + "hw.lcd.density", + "hw.lcd.depth", + "hw.lcd.height", + "hw.lcd.transparent", + "hw.lcd.vsync", + "hw.lcd.width", + "hw.mainKeys", + "hw.multi_display_window", + "hw.ramSize", + "hw.rotaryInput", + "hw.screen", + "hw.sdCard", + "hw.sensor.hinge", + "hw.sensor.hinge.count", + "hw.sensor.hinge.fold_to_displayRegion.0.1_at_posture", + "hw.sensor.hinge.resizable.config", + "hw.sensor.hinge.sub_type", + "hw.sensor.hinge.type", + "hw.sensor.roll", + "hw.sensor.roll.count", + "hw.sensor.roll.resize_to_displayRegion.0.1_at_posture", + "hw.sensor.roll.resize_to_displayRegion.0.2_at_posture", + "hw.sensor.roll.resize_to_displayRegion.0.3_at_posture", + "hw.sensors.gyroscope_uncalibrated", + "hw.sensors.heading", + "hw.sensors.heart_rate", + "hw.sensors.humidity", + "hw.sensors.light", + "hw.sensors.magnetic_field", + "hw.sensors.magnetic_field_uncalibrated", + "hw.sensors.orientation", + "hw.sensors.pressure", + "hw.sensors.proximity", + "hw.sensors.rgbclight", + "hw.sensors.temperature", + "hw.sensors.wrist_tilt", + "hw.touchpad0", + "hw.touchpad0.height", + "hw.touchpad0.width", + "hw.trackBall", + "hw.useext4", + "vm.heapSize", +]; diff --git a/src/drivers/android/profiles/index.ts b/src/drivers/android/profiles/index.ts new file mode 100644 index 000000000..5f09c9176 --- /dev/null +++ b/src/drivers/android/profiles/index.ts @@ -0,0 +1,12 @@ +import type { DeviceProfile, DeviceProfileSource } from "../device-profile-source.js"; +import { PIXEL_9 } from "./pixel-9.js"; + +export type LibraryDeviceProfile = Extract; + +export const LIBRARY_PROFILES: readonly LibraryDeviceProfile[] = [PIXEL_9]; + +export class LibraryDeviceProfileSource implements DeviceProfileSource { + async profiles(): Promise { + return LIBRARY_PROFILES; + } +} diff --git a/src/drivers/android/profiles/library.test.ts b/src/drivers/android/profiles/library.test.ts new file mode 100644 index 000000000..402c0a395 --- /dev/null +++ b/src/drivers/android/profiles/library.test.ts @@ -0,0 +1,155 @@ +import { readdirSync, readFileSync } from "node:fs"; +import { dirname, join } from "node:path"; +import { fileURLToPath } from "node:url"; + +import { describe, expect, it } from "vitest"; + +import { isPlayStoreImage } from "../image-fit.js"; +import { LIBRARY_HARDWARE_KEYS } from "./hardware-keys.js"; +import { LIBRARY_PROFILES, LibraryDeviceProfileSource } from "./index.js"; + +const folder = dirname(fileURLToPath(import.meta.url)); +const NOT_PROFILE_FILES = new Set(["index.ts", "hardware-keys.ts"]); + +function profileFiles(): string[] { + return readdirSync(folder).filter( + (file) => file.endsWith(".ts") && !file.endsWith(".test.ts") && !NOT_PROFILE_FILES.has(file), + ); +} + +function fixtureConfig(): Map { + const entries = new Map(); + for (const line of readFileSync(join(folder, "fixtures/pixel-9.config.ini"), "utf8").split( + "\n", + )) { + const at = line.indexOf("="); + if (at > 0) entries.set(line.slice(0, at), line.slice(at + 1)); + } + return entries; +} + +function isLibraryKey(key: string): boolean { + return ( + (key.startsWith("hw.") || key === "vm.heapSize") && + key !== "hw.cpu.arch" && + key !== "hw.device.hash2" + ); +} + +function pixel9() { + const profile = LIBRARY_PROFILES.find((candidate) => candidate.id === "pixel_9"); + if (profile === undefined) throw new Error("the library has no profile with id pixel_9"); + return profile; +} + +describe("the Android device profile library", () => { + it("LIBRARY_HARDWARE_KEYS equals the hw.* and vm.heapSize keys of the Pixel 9 fixture without hw.cpu.arch and hw.device.hash2", () => { + const expected = [...fixtureConfig().keys()].filter(isLibraryKey).sort(); + + expect(expected).toHaveLength(104); + expect([...LIBRARY_HARDWARE_KEYS].sort()).toEqual(expected); + }); + + it("Pixel 9's hardware equals the values in the fixture config.ini", () => { + const expected = Object.fromEntries([...fixtureConfig()].filter(([key]) => isLibraryKey(key))); + + expect(pixel9().hardware).toEqual(expected); + expect(pixel9().hardware["hw.ramSize"]).toBe("2G"); + }); + + it("Pixel 9's class, image kind, API range, Play Store and tablet flags and boot properties are phone, none, 35-, yes, no, none", () => { + const profile = pixel9(); + + expect(profile.name).toBe("Pixel 9"); + expect(profile.names).toEqual(["Pixel 9", "pixel_9"]); + expect(profile.deviceClass).toBe("phone"); + expect(profile.imageKind).toBeUndefined(); + expect(profile.apiRange).toEqual({ min: 35 }); + expect(profile.playStore).toBe(true); + expect(profile.tablet).toBe(false); + expect(profile.bootProperties).toEqual({}); + }); + + it("the source lists exactly the profiles the library holds", async () => { + const listed = await new LibraryDeviceProfileSource().profiles(); + + expect(LIBRARY_PROFILES.length).toBeGreaterThan(0); + expect(listed).toEqual(LIBRARY_PROFILES); + }); + + it("index.ts imports exactly the profile files in the folder", () => { + const files = profileFiles(); + const imported = [ + ...readFileSync(join(folder, "index.ts"), "utf8").matchAll(/from "\.\/([^"]+)\.js"/g), + ] + .map((match) => `${match[1] ?? ""}.ts`) + .filter((file) => !NOT_PROFILE_FILES.has(file)); + + expect(files.length).toBeGreaterThan(0); + expect(imported.sort()).toEqual(files.sort()); + }); + + it("each profile file is named after its id with - for _", () => { + expect(LIBRARY_PROFILES.length).toBeGreaterThan(0); + const expected = LIBRARY_PROFILES.map((profile) => `${profile.id.replaceAll("_", "-")}.ts`); + + expect(expected.sort()).toEqual(profileFiles().sort()); + }); + + it("no name, ignoring case, appears in two profiles", () => { + const names = LIBRARY_PROFILES.flatMap((profile) => + profile.names.map((name) => name.toLocaleLowerCase()), + ); + + expect(names.length).toBeGreaterThan(0); + expect(new Set(names).size).toBe(names.length); + }); + + it("every profile sets every key in LIBRARY_HARDWARE_KEYS, and only hw.* and vm.heapSize keys other than hw.cpu.arch and hw.device.hash2", () => { + expect(LIBRARY_HARDWARE_KEYS.length).toBeGreaterThan(0); + expect(LIBRARY_PROFILES.length).toBeGreaterThan(0); + for (const profile of LIBRARY_PROFILES) { + const keys = Object.keys(profile.hardware); + expect( + keys.filter((key) => !isLibraryKey(key)), + profile.id, + ).toEqual([]); + expect( + LIBRARY_HARDWARE_KEYS.filter((key) => !keys.includes(key)), + profile.id, + ).toEqual([]); + } + }); + + it("every profile names the cmdline-tools version it was copied from", () => { + expect(LIBRARY_PROFILES.length).toBeGreaterThan(0); + for (const profile of LIBRARY_PROFILES) { + expect(profile.copiedFrom, profile.id).toMatch(/^\d+\.\d+$/); + } + }); +}); + +describe("isPlayStoreImage", () => { + const image = (tag: string, tags: readonly string[], apiLevel = "35") => ({ + apiLevel, + tag, + tags, + }); + + it("is true for a google_apis_playstore tag, a single android-automotive-playstore tag and a single android-wear tag at 25 or newer", () => { + expect(isPlayStoreImage(image("google_apis_playstore", ["google_apis_playstore"]))).toBe(true); + expect(isPlayStoreImage(image("x", ["google-tv", "google_apis_playstore"]))).toBe(true); + expect( + isPlayStoreImage(image("android-automotive-playstore", ["android-automotive-playstore"])), + ).toBe(true); + expect(isPlayStoreImage(image("android-wear", ["android-wear"], "25"))).toBe(true); + expect(isPlayStoreImage(image("android-wear", ["android-wear"], "34"))).toBe(true); + }); + + it("is false for android-wear at 24, android-wear-cn, google_apis and google-tv,google_apis", () => { + expect(isPlayStoreImage(image("android-wear", ["android-wear"], "24"))).toBe(false); + expect(isPlayStoreImage(image("android-wear-cn", ["android-wear"], "34"))).toBe(false); + expect(isPlayStoreImage(image("google_apis", ["google_apis"]))).toBe(false); + expect(isPlayStoreImage(image("google-tv", ["google-tv", "google_apis"]))).toBe(false); + }); +}); diff --git a/src/drivers/android/profiles/pixel-9.ts b/src/drivers/android/profiles/pixel-9.ts new file mode 100644 index 000000000..46381cf82 --- /dev/null +++ b/src/drivers/android/profiles/pixel-9.ts @@ -0,0 +1,121 @@ +import type { LibraryDeviceProfile } from "./index.js"; + +export const PIXEL_9: LibraryDeviceProfile = { + kind: "library", + name: "Pixel 9", + id: "pixel_9", + names: ["Pixel 9", "pixel_9"], + deviceClass: "phone", + imageKind: undefined, + apiRange: { min: 35 }, + playStore: true, + tablet: false, + hardware: { + "hw.accelerometer": "yes", + "hw.accelerometer_uncalibrated": "yes", + "hw.arc": "no", + "hw.arc.autologin": "no", + "hw.audioInput": "yes", + "hw.audioOutput": "yes", + "hw.battery": "yes", + "hw.camera.back": "emulated", + "hw.camera.back.orientation": "90", + "hw.camera.front": "none", + "hw.camera.front.orientation": "90", + "hw.cpu.ncore": "4", + "hw.dPad": "no", + "hw.device.manufacturer": "Google", + "hw.device.name": "pixel_9", + "hw.display1.density": "0", + "hw.display1.flag": "0", + "hw.display1.height": "0", + "hw.display1.width": "0", + "hw.display1.xOffset": "-1", + "hw.display1.yOffset": "-1", + "hw.display2.density": "0", + "hw.display2.flag": "0", + "hw.display2.height": "0", + "hw.display2.width": "0", + "hw.display2.xOffset": "-1", + "hw.display2.yOffset": "-1", + "hw.display3.density": "0", + "hw.display3.flag": "0", + "hw.display3.height": "0", + "hw.display3.width": "0", + "hw.display3.xOffset": "-1", + "hw.display3.yOffset": "-1", + "hw.displayRegion.0.1.height": "0", + "hw.displayRegion.0.1.width": "0", + "hw.displayRegion.0.1.xOffset": "-1", + "hw.displayRegion.0.1.yOffset": "-1", + "hw.displayRegion.0.2.height": "0", + "hw.displayRegion.0.2.width": "0", + "hw.displayRegion.0.2.xOffset": "-1", + "hw.displayRegion.0.2.yOffset": "-1", + "hw.displayRegion.0.3.height": "0", + "hw.displayRegion.0.3.width": "0", + "hw.displayRegion.0.3.xOffset": "-1", + "hw.displayRegion.0.3.yOffset": "-1", + "hw.gltransport": "pipe", + "hw.gltransport.asg.dataRingSize": "32768", + "hw.gltransport.asg.writeBufferSize": "1048576", + "hw.gltransport.asg.writeStepSize": "4096", + "hw.gltransport.drawFlushInterval": "800", + "hw.gps": "yes", + "hw.gpu.enabled": "no", + "hw.gpu.mode": "auto", + "hw.gsmModem": "yes", + "hw.gyroscope": "yes", + "hw.hotplug_multi_display": "no", + "hw.initialOrientation": "portrait", + "hw.keyboard": "no", + "hw.keyboard.charmap": "qwerty2", + "hw.keyboard.lid": "yes", + "hw.lcd.backlight": "yes", + "hw.lcd.circular": "false", + "hw.lcd.density": "420", + "hw.lcd.depth": "16", + "hw.lcd.height": "2424", + "hw.lcd.transparent": "false", + "hw.lcd.vsync": "60", + "hw.lcd.width": "1080", + "hw.mainKeys": "no", + "hw.multi_display_window": "no", + "hw.ramSize": "2G", + "hw.rotaryInput": "no", + "hw.screen": "multi-touch", + "hw.sdCard": "yes", + "hw.sensor.hinge": "no", + "hw.sensor.hinge.count": "0", + "hw.sensor.hinge.fold_to_displayRegion.0.1_at_posture": "1", + "hw.sensor.hinge.resizable.config": "1", + "hw.sensor.hinge.sub_type": "0", + "hw.sensor.hinge.type": "0", + "hw.sensor.roll": "no", + "hw.sensor.roll.count": "0", + "hw.sensor.roll.resize_to_displayRegion.0.1_at_posture": "6", + "hw.sensor.roll.resize_to_displayRegion.0.2_at_posture": "6", + "hw.sensor.roll.resize_to_displayRegion.0.3_at_posture": "6", + "hw.sensors.gyroscope_uncalibrated": "yes", + "hw.sensors.heading": "no", + "hw.sensors.heart_rate": "no", + "hw.sensors.humidity": "yes", + "hw.sensors.light": "yes", + "hw.sensors.magnetic_field": "yes", + "hw.sensors.magnetic_field_uncalibrated": "yes", + "hw.sensors.orientation": "yes", + "hw.sensors.pressure": "yes", + "hw.sensors.proximity": "yes", + "hw.sensors.rgbclight": "no", + "hw.sensors.temperature": "yes", + "hw.sensors.wrist_tilt": "no", + "hw.touchpad0": "no", + "hw.touchpad0.height": "400", + "hw.touchpad0.width": "600", + "hw.trackBall": "no", + "hw.useext4": "yes", + "vm.heapSize": "228M", + }, + bootProperties: {}, + copiedFrom: "20.0", +};