#!/usr/bin/env python3"""What an Android App Bundle says it is: the package, versionCode andversionName of its base module's manifest, read from the bundle itself. python3 scripts/lib/aab_manifest.py <bundle.aab> prints one JSON objectAn .aab keeps base/manifest/AndroidManifest.xml as aapt2's protobuf XmlNode(frameworks/base/tools/aapt2/Resources.proto): XmlNode.element (1) is anXmlElement whose name (3) is "manifest" and whose attributes (4) areXmlAttribute { namespace_uri 1, name 2, value 3 }. Only those fields are read;nothing here needs bundletool or a JDK, so the box (pnpm android:release) andthe signing machine read a bundle the same way.Exit 1 with a sentence when the file is no bundle or its manifest says no package."""import jsonimport sysimport zipfileMANIFEST = "base/manifest/AndroidManifest.xml"def varint(data, i): shift = value = 0whileTrue:if i >= len(data):raiseValueError("a varint runs past the end") byte = data[i] i += 1 value |= (byte & 0x7F) << shiftif byte < 0x80:return value, i shift += 7def fields(data):"""(field number, wire type, value) for each field of one message; length-delimited values are bytes.""" i = 0while i < len(data): key, i = varint(data, i) number, wire = key >> 3, key & 7if wire == 0: value, i = varint(data, i)elif wire == 2: size, i = varint(data, i) value = data[i : i + size]if len(value) != size:raiseValueError("a field runs past the end") i += sizeelif wire == 1: value, i = data[i : i + 8], i + 8elif wire == 5: value, i = data[i : i + 4], i + 4else:raiseValueError(f"wire type {wire} is not protobuf's")yield number, wire, valuedef manifest_of(data): element = next((v for n, w, v in fields(data) if n == 1and w == 2), None)if element isNone:raiseValueError("the manifest holds no element") name = None attributes = {}for n, w, v in fields(element):if n == 3and w == 2: name = v.decode("utf8")elif n == 4and w == 2: attribute = {an: av for an, aw, av in fields(v) if aw == 2and an in (1, 2, 3)} key = attribute.get(2, b"").decode("utf8")if key: attributes[key] = attribute.get(3, b"").decode("utf8")if name != "manifest":raiseValueError(f"the root element is {name!r}, not manifest")return {"package": attributes.get("package", ""),"versionCode": attributes.get("versionCode", ""),"versionName": attributes.get("versionName", ""), }def main(argv):if len(argv) != 2: print("usage: aab_manifest.py <bundle.aab>", file=sys.stderr)return2try:with zipfile.ZipFile(argv[1]) as bundle: said = manifest_of(bundle.read(MANIFEST))except (OSError, KeyError, zipfile.BadZipFile, ValueError, UnicodeDecodeError) as error: print(f"aab_manifest: {argv[1]} is no bundle whose manifest can be read ({error})", file=sys.stderr)return1ifnot said["package"]: print(f"aab_manifest: {argv[1]}'s manifest names no package", file=sys.stderr)return1 print(json.dumps(said))return0if __name__ == "__main__": sys.exit(main(sys.argv))