A fast 2D and 3D game engine — TypeScript SDK, C++/WebAssembly core, visual editor. Ship one project to web, desktop, WeChat MiniGames, playable ads, and native Android / iOS.
TypeScript 2d-game-engine3d3d-game-engineandroidcppecsgame-editorgame-enginegamedeviostypescriptwebassemblywebglwebgpuwechat-minigame
fix(android): the APK could not be installed, on either of two counts
yhhd89cbd31eb09
diff --git a/build-tools/utils/androidAttrValues.js b/build-tools/utils/androidAttrValues.jsnew file mode 100644index 000000000..6b7b2ca2e--- /dev/null+++ b/build-tools/utils/androidAttrValues.js@@ -0,0 +1,102 @@+// SPDX-License-Identifier: Apache-2.0+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team+//+// Manifest attributes whose values are NAMES of numbers.+//+// `android:configChanges="orientation|keyboardHidden"` and+// `android:screenOrientation="sensorPortrait"` are written as words and read as+// integers: the platform's parser does `Integer.parseInt` on whatever the compiled+// manifest holds. Shipping the words is not a smaller mistake than shipping the+// wrong number — an APK whose configChanges is a string fails to install at all:+//+// INSTALL_PARSE_FAILED_UNEXPECTED_EXCEPTION: Failed to read manifest ...+// For input string: "orientation|keyboardHidden|screenSize|..."+//+// which is how this was found: on a phone, after every structural check passed.+// A decoder reads the string back happily; only the platform insists.+//+// Values are AOSP's (attrs_manifest.xml). Both manifest encoders — binary XML for+// the APK, protobuf for the App Bundle — resolve through here, so the two cannot+// disagree about what a word means.++/** Flag attributes: `|`-separated names, OR-ed into one int. */+const FLAG_ATTRS = {+ configChanges: {+ mcc: 0x0001,+ mnc: 0x0002,+ locale: 0x0004,+ touchscreen: 0x0008,+ keyboard: 0x0010,+ keyboardHidden: 0x0020,+ navigation: 0x0040,+ orientation: 0x0080,+ screenLayout: 0x0100,+ uiMode: 0x0200,+ screenSize: 0x0400,+ smallestScreenSize: 0x0800,+ density: 0x1000,+ layoutDirection: 0x2000,+ colorMode: 0x4000,+ grammaticalGender: 0x8000,+ fontWeightAdjustment: 0x10000000,+ },+};++/** Enum attributes: one name, one int. */+const ENUM_ATTRS = {+ screenOrientation: {+ unspecified: -1,+ landscape: 0,+ portrait: 1,+ user: 2,+ behind: 3,+ sensor: 4,+ nosensor: 5,+ sensorLandscape: 6,+ sensorPortrait: 7,+ reverseLandscape: 8,+ reversePortrait: 9,+ fullSensor: 10,+ userLandscape: 11,+ userPortrait: 12,+ fullUser: 13,+ locked: 14,+ },+};++/**+ * The integer an attribute's symbolic text means, or null when the attribute is+ * not one of these (the caller then types the text by its shape, as before).+ *+ * An unknown NAME inside a known attribute throws rather than passing through:+ * a typo would otherwise reach a device as an install failure, which is a long+ * way from where it was written.+ *+ * @param {string} name The attribute's local name, e.g. `configChanges`.+ * @param {string} text Its authored value.+ * @returns {number|null}+ */+export function symbolicAttrValue(name, text) {+ const flags = FLAG_ATTRS[name];+ if (flags) {+ return text.split('|').reduce((acc, part) => {+ const key = part.trim();+ if (!(key in flags)) throw new Error(`Unknown android:${name} flag "${key}"`);+ return acc | flags[key];+ }, 0) >>> 0;+ }++ const values = ENUM_ATTRS[name];+ if (values) {+ const key = text.trim();+ if (!(key in values)) throw new Error(`Unknown android:${name} value "${key}"`);+ return values[key];+ }++ return null;+}++/** Whether an attribute's value is a name for a number (for tests and callers). */+export function isSymbolicAttr(name) {+ return name in FLAG_ATTRS || name in ENUM_ATTRS;+}diff --git a/build-tools/utils/androidBinaryXml.js b/build-tools/utils/androidBinaryXml.jsindex 3c4c7ad49..e29466da5 100644--- a/build-tools/utils/androidBinaryXml.js+++ b/build-tools/utils/androidBinaryXml.js@@ -51,6 +51,8 @@ export const ANDROID_STYLE_IDS = {// Res_value data types.const TYPE_REFERENCE = 0x01;const TYPE_STRING = 0x03;+import { symbolicAttrValue } from './androidAttrValues.js';+const TYPE_INT_DEC = 0x10;const TYPE_INT_HEX = 0x11;const TYPE_INT_BOOLEAN = 0x12;@@ -211,7 +213,14 @@ class StringPool {* are the APP's own resources, whose ids belong to whoever built the resource* table — so they are passed in rather than guessed.*/-function typedValue(value, pool, references) {+function typedValue(value, pool, references, name) {+ // Attributes whose words ARE numbers (configChanges, screenOrientation) resolve+ // first: their text looks like a plain string, and shipping it as one is an APK+ // the platform refuses to install.+ const symbolic = name === undefined ? null : symbolicAttrValue(name, value);+ if (symbolic !== null) {+ return { type: TYPE_INT_DEC, data: symbolic >>> 0, raw: NO_ENTRY };+ }const style = /^@android:style\/(.+)$/.exec(value);if (style) {const id = ANDROID_STYLE_IDS[style[1]];@@ -299,13 +308,22 @@ export function encodeBinaryXml(root, references = {}) {// reached, which is why the map's slots had to be claimed first.const nodes = [];const emit = (node) => {+ // Sorted by resource id, which is not a style: the platform reads an+ // element's attributes with a BINARY SEARCH over this array, so an+ // out-of-order attribute is one the platform cannot find. An+ // android:exported it fails to find reads as absent — and an activity with+ // an intent filter and no explicit `exported` is refused outright on+ // Android 12+. Attributes with no resource id sort last; the manifest has+ // none today, and a custom namespace is not looked up by id anyway.const attrs = node.attrs.filter((a) => a.name !== 'xmlns' && a.prefix !== 'xmlns').map((a) => ({+ id: a.prefix === 'android' ? ANDROID_ATTR_IDS[a.name] : Number.MAX_SAFE_INTEGER,ns: a.prefix === 'android' ? nsUri : NO_ENTRY,name: pool.add(a.name),- value: typedValue(a.value, pool, references),- }));+ value: typedValue(a.value, pool, references, a.name),+ }))+ .sort((x, y) => x.id - y.id);const name = pool.add(node.name);const ext = Buffer.alloc(20 + attrs.length * 20);diff --git a/build-tools/utils/androidProtoXml.js b/build-tools/utils/androidProtoXml.jsindex da8c2fa98..8f8c373a0 100644--- a/build-tools/utils/androidProtoXml.js+++ b/build-tools/utils/androidProtoXml.js@@ -27,6 +27,8 @@ const PRIM_BOOLEAN = 8;// Resources.proto — Item.valueconst ITEM_REF = 1;+import { symbolicAttrValue } from './androidAttrValues.js';+const ITEM_STR = 2;const ITEM_PRIM = 7;@@ -34,7 +36,13 @@ const ITEM_PRIM = 7;const REF_ID = 2;/** `Item` for an attribute value, typed the way the platform expects to read it. */-function compiledItem(value, references) {+function compiledItem(value, references, name) {+ // Same rule as the binary encoder: a flag or enum attribute is an int, and the+ // App Bundle carries the same manifest the APK does.+ const symbolic = name === undefined ? null : symbolicAttrValue(name, value);+ if (symbolic !== null) {+ return bytesField(ITEM_PRIM, message(varintField(PRIM_INT_DECIMAL, symbolic)));+ }const style = /^@android:style\/(.+)$/.exec(value);if (style) {const id = ANDROID_STYLE_IDS[style[1]];@@ -67,7 +75,7 @@ function attribute(attr, references) {if (framework && id === undefined) {throw new Error(`No public resource id known for android:${attr.name} — add it to ANDROID_ATTR_IDS.`);}- const compiled = framework ? compiledItem(attr.value, references) : null;+ const compiled = framework ? compiledItem(attr.value, references, attr.name) : null;return message(framework ? bytesField(1, ANDROID_NS) : null,bytesField(2, attr.name),diff --git a/desktop/tests/android-apk.test.ts b/desktop/tests/android-apk.test.tsindex f9136e716..0716756d9 100644--- a/desktop/tests/android-apk.test.ts+++ b/desktop/tests/android-apk.test.ts@@ -106,6 +106,95 @@ function verify(apk: string): {return JSON.parse(execFileSync('python3', [VERIFIER, apk], { encoding: 'utf8' }));}+/**+ * The attributes of every element, as the platform reads them: resource id, value+ * type and value. Walks the chunk tree and the resource map, and never decodes a+ * string — which is the point. A decoder that renders the manifest back as text+ * shows `android:configChanges="orientation|..."` and looks right; the platform+ * calls Integer.parseInt on it and refuses to install the package.+ */+function compiledAttributes(binary: Buffer): Array<Array<{ id: number; type: number; data: number }>> {+ const CHUNK_RESOURCE_MAP = 0x0180;+ const CHUNK_START_ELEMENT = 0x0102;++ let ids: number[] = [];+ const elements: Array<Array<{ id: number; type: number; data: number }>> = [];++ // Chunks follow the 8-byte XML header, each with type/headerSize/size.+ let at = 8;+ while (at + 8 <= binary.length) {+ const type = binary.readUInt16LE(at);+ const headerSize = binary.readUInt16LE(at + 2);+ const size = binary.readUInt32LE(at + 4);+ if (size <= 0) break;++ if (type === CHUNK_RESOURCE_MAP) {+ ids = [];+ for (let n = at + headerSize; n + 4 <= at + size; n += 4) ids.push(binary.readUInt32LE(n));+ } else if (type === CHUNK_START_ELEMENT) {+ const body = at + headerSize;+ const attrStart = binary.readUInt16LE(body + 8);+ const count = binary.readUInt16LE(body + 12);+ const attrs = [];+ for (let i = 0; i < count; i++) {+ const a = body + attrStart + i * 20;+ const nameIndex = binary.readUInt32LE(a + 4);+ attrs.push({+ id: ids[nameIndex] ?? 0,+ type: binary.readUInt8(a + 15),+ data: binary.readUInt32LE(a + 16),+ });+ }+ if (count > 0) elements.push(attrs);+ }+ at += size;+ }+ return elements;+}++describe('what the platform reads out of the compiled manifest', () => {+ const ATTR = { screenOrientation: 0x0101001e, configChanges: 0x0101001f, exported: 0x01010010 };+ const TYPE_INT_DEC = 0x10;++ const manifest = () => compiledAttributes(compileManifest(+ readFileSync(MANIFEST_TEMPLATE, 'utf8')+ .replace(/@APP_ID@/g, 'com.example.demo').replace(/@APP_NAME@/g, 'My Game')+ .replace(/@VERSION_NAME@/g, '1.2').replace(/@VERSION_CODE@/g, '7')+ .replace(/@SCREEN_ORIENTATION@/g, 'sensorPortrait').replace(/@HAS_CODE@/g, 'true'),+ appResources(Buffer.alloc(4)).references));++ it('gives configChanges the bitmask its words mean, not the words', () => {+ const attr = manifest().flat().find((a) => a.id === ATTR.configChanges);++ // orientation|keyboardHidden|screenSize|screenLayout|density, per AOSP's+ // attrs_manifest.xml. As a string this is INSTALL_PARSE_FAILED on a device.+ expect(attr).toBeDefined();+ expect(attr!.type).toBe(TYPE_INT_DEC);+ expect(attr!.data).toBe(0x0080 | 0x0020 | 0x0400 | 0x0100 | 0x1000);+ });++ it('gives screenOrientation its enum number', () => {+ const attr = manifest().flat().find((a) => a.id === ATTR.screenOrientation);+ expect(attr).toBeDefined();+ expect(attr!.type).toBe(TYPE_INT_DEC);+ expect(attr!.data).toBe(7); // sensorPortrait+ });++ it('sorts each element’s attributes by resource id, which is how they are found', () => {+ // The platform binary-searches this array. Out of order, an attribute is+ // simply not there: an activity whose android:exported cannot be found is+ // refused on Android 12+ for not declaring one.+ for (const attrs of manifest()) {+ // Only the id-bearing ones: `package` carries no resource id and the+ // platform looks it up by name, so it is not part of the ordering the+ // search depends on (it lands last, which a device accepts).+ const ids = attrs.map((a) => a.id).filter((id) => id !== 0);+ expect(ids).toEqual([...ids].sort((x, y) => x - y));+ }+ expect(manifest().flat().some((a) => a.id === ATTR.exported)).toBe(true);+ });+});+describe('the manifest is compiled, not shelled out to aapt2', () => {it('uses the resource ids AOSP publishes — the platform resolves attributes by id', () => {if (!hasAndroguard) return;