storeready 0.2.0__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- storeready/__init__.py +3 -0
- storeready/__main__.py +5 -0
- storeready/advice/__init__.py +87 -0
- storeready/android/__init__.py +14 -0
- storeready/android/checks/__init__.py +10 -0
- storeready/android/checks/edge_to_edge.py +148 -0
- storeready/android/checks/large_screen.py +137 -0
- storeready/android/checks/page_size.py +180 -0
- storeready/android/checks/target_api.py +119 -0
- storeready/android/formats/__init__.py +2 -0
- storeready/android/formats/_guard.py +41 -0
- storeready/android/formats/arsc.py +140 -0
- storeready/android/formats/axml.py +210 -0
- storeready/android/formats/bundle.py +191 -0
- storeready/android/formats/elf.py +84 -0
- storeready/android/formats/protobuf.py +92 -0
- storeready/android/load.py +195 -0
- storeready/android/manifest.py +159 -0
- storeready/android/model.py +124 -0
- storeready/cli.py +240 -0
- storeready/core/__init__.py +36 -0
- storeready/core/artifact.py +48 -0
- storeready/core/check.py +58 -0
- storeready/core/engine.py +115 -0
- storeready/core/finding.py +71 -0
- storeready/core/frozen.py +22 -0
- storeready/core/platform.py +38 -0
- storeready/core/rulebook.py +109 -0
- storeready/ios/__init__.py +14 -0
- storeready/ios/checks/__init__.py +33 -0
- storeready/ios/checks/ipad_multitasking.py +75 -0
- storeready/ios/checks/liquid_glass.py +75 -0
- storeready/ios/checks/privacy_manifest.py +126 -0
- storeready/ios/checks/privacy_reasons.py +213 -0
- storeready/ios/checks/sdk_manifests.py +85 -0
- storeready/ios/checks/upload_settings.py +152 -0
- storeready/ios/checks/usage_descriptions.py +233 -0
- storeready/ios/checks/xcode_sdk.py +121 -0
- storeready/ios/formats/__init__.py +1 -0
- storeready/ios/formats/macho.py +118 -0
- storeready/ios/load.py +216 -0
- storeready/ios/model.py +151 -0
- storeready/ios/privacy.py +113 -0
- storeready/knowledge/__init__.py +0 -0
- storeready/knowledge/fixes.toml +75 -0
- storeready/knowledge/frameworks.toml +25 -0
- storeready/knowledge/rules.toml +130 -0
- storeready/py.typed +0 -0
- storeready/report/__init__.py +2 -0
- storeready/report/baseline.py +67 -0
- storeready/report/data.py +57 -0
- storeready/report/policy.py +17 -0
- storeready/report/sarif.py +97 -0
- storeready/report/text.py +118 -0
- storeready-0.2.0.dist-info/METADATA +67 -0
- storeready-0.2.0.dist-info/RECORD +61 -0
- storeready-0.2.0.dist-info/WHEEL +5 -0
- storeready-0.2.0.dist-info/entry_points.txt +2 -0
- storeready-0.2.0.dist-info/licenses/LICENSE +202 -0
- storeready-0.2.0.dist-info/licenses/NOTICE +20 -0
- storeready-0.2.0.dist-info/top_level.txt +1 -0
|
@@ -0,0 +1,119 @@
|
|
|
1
|
+
"""Google Play refuses new apps and updates below its target API level for the form factor."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
from datetime import date
|
|
6
|
+
|
|
7
|
+
from storeready.android.model import AndroidApp
|
|
8
|
+
from storeready.core import CheckDoc, CheckInfo, Context, Evidence, Finding, Level, Platform
|
|
9
|
+
|
|
10
|
+
DOC = CheckDoc(
|
|
11
|
+
reads=("Manifest",),
|
|
12
|
+
what="Compares `targetSdkVersion` with the level Google Play requires for the app's form "
|
|
13
|
+
"factor. The form factor comes from `<uses-feature>`: phone and tablet (the default), Wear "
|
|
14
|
+
"OS, Android TV or Android Automotive OS.",
|
|
15
|
+
why="Google Play refuses new apps and app updates below the required level. The level rises "
|
|
16
|
+
"each year: API {android.target_api.phone.level} for phones and tablets from "
|
|
17
|
+
"{android.target_api.phone.deadline}, with extensions available until "
|
|
18
|
+
"{android.target_api.phone.extension_until}.",
|
|
19
|
+
fix="Raise `targetSdk` to the required level and test the behaviour changes of each level "
|
|
20
|
+
"you skip.",
|
|
21
|
+
example="""[BLOCKER] target-api: Targets the API level Google Play requires
|
|
22
|
+
- (blocker) Targets API 35; Google Play needs API 36.
|
|
23
|
+
Refused for new apps and updates since 2026-08-31 (extensions ended 2026-11-01).
|
|
24
|
+
Fix: Set targetSdk = 36 and test the behaviour changes of each level.""",
|
|
25
|
+
limitations=(
|
|
26
|
+
"Android XR apps are held to the phone and tablet level, because Google's pages don't "
|
|
27
|
+
"say how Play recognises them.",
|
|
28
|
+
),
|
|
29
|
+
)
|
|
30
|
+
|
|
31
|
+
|
|
32
|
+
class TargetApi:
|
|
33
|
+
info = CheckInfo(
|
|
34
|
+
id="target-api",
|
|
35
|
+
platform=Platform.ANDROID,
|
|
36
|
+
title="Targets the API level Google Play requires",
|
|
37
|
+
rules=("android.target_api",),
|
|
38
|
+
doc=DOC,
|
|
39
|
+
)
|
|
40
|
+
|
|
41
|
+
def run(self, app: AndroidApp, ctx: Context) -> list[Finding]:
|
|
42
|
+
rule = ctx.rule("android.target_api")
|
|
43
|
+
form = app.manifest.form_factor
|
|
44
|
+
levels = rule[form.value]
|
|
45
|
+
target = app.manifest.target_sdk
|
|
46
|
+
evidence = (Evidence("manifest", f"targetSdkVersion={target}", "AndroidManifest.xml"),)
|
|
47
|
+
|
|
48
|
+
def finding(level: Level, title: str, detail: str = "", fix: str = "") -> Finding:
|
|
49
|
+
return Finding(
|
|
50
|
+
self.info.id,
|
|
51
|
+
level,
|
|
52
|
+
subject=form.value,
|
|
53
|
+
title=title,
|
|
54
|
+
detail=detail,
|
|
55
|
+
evidence=evidence,
|
|
56
|
+
fix=fix,
|
|
57
|
+
source=rule.source,
|
|
58
|
+
)
|
|
59
|
+
|
|
60
|
+
if target is None and app.manifest.target_sdk_is_reference:
|
|
61
|
+
return [
|
|
62
|
+
finding(
|
|
63
|
+
Level.NOTE,
|
|
64
|
+
"targetSdkVersion is set through a resource reference, which storeready "
|
|
65
|
+
"doesn't resolve.",
|
|
66
|
+
f"Check that it resolves to API {levels['level']} or higher.",
|
|
67
|
+
"Set targetSdkVersion as a number in the build file.",
|
|
68
|
+
)
|
|
69
|
+
]
|
|
70
|
+
if target is None:
|
|
71
|
+
return [finding(Level.BLOCKER, "No target SDK in the manifest.")]
|
|
72
|
+
|
|
73
|
+
required: int = levels["level"]
|
|
74
|
+
deadline: date = levels["deadline"]
|
|
75
|
+
extension: date | None = levels.get("extension_until")
|
|
76
|
+
who = "" if form.value == "phone" else f" for {form.value} apps"
|
|
77
|
+
if target < required:
|
|
78
|
+
title = f"Targets API {target}; Google Play needs API {required}{who}."
|
|
79
|
+
fix = f"Set targetSdk = {required} and test the behaviour changes of each level."
|
|
80
|
+
if ctx.today >= (extension or deadline):
|
|
81
|
+
ended = f" (extensions ended {extension})" if extension else ""
|
|
82
|
+
return [
|
|
83
|
+
finding(
|
|
84
|
+
Level.BLOCKER,
|
|
85
|
+
title,
|
|
86
|
+
f"Refused for new apps and updates since {deadline}{ended}.",
|
|
87
|
+
fix,
|
|
88
|
+
)
|
|
89
|
+
]
|
|
90
|
+
when = (
|
|
91
|
+
f"Required since {deadline}; extensions run to {extension}."
|
|
92
|
+
if ctx.today >= deadline
|
|
93
|
+
else f"Required from {deadline}."
|
|
94
|
+
)
|
|
95
|
+
return [finding(Level.DUE, title, when, fix)]
|
|
96
|
+
|
|
97
|
+
next_level: int | None = levels.get("next_level")
|
|
98
|
+
next_deadline: date | None = levels.get("next_deadline")
|
|
99
|
+
if next_level and next_deadline and target < next_level:
|
|
100
|
+
if ctx.today >= next_deadline:
|
|
101
|
+
return [
|
|
102
|
+
finding(
|
|
103
|
+
Level.DUE,
|
|
104
|
+
f"Targets API {target}; API {next_level} was expected to be required by "
|
|
105
|
+
f"{next_deadline}.",
|
|
106
|
+
"That date was announced as anticipated; check Google Play's page and "
|
|
107
|
+
"update rules.toml.",
|
|
108
|
+
f"Set targetSdk = {next_level}.",
|
|
109
|
+
)
|
|
110
|
+
]
|
|
111
|
+
return [
|
|
112
|
+
finding(
|
|
113
|
+
Level.OK,
|
|
114
|
+
f"Targets API {target}; meets Google Play's API {required} rule{who}.",
|
|
115
|
+
f"Next: API {next_level}, expected by {next_deadline} (announced as "
|
|
116
|
+
"anticipated).",
|
|
117
|
+
)
|
|
118
|
+
]
|
|
119
|
+
return [finding(Level.OK, f"Targets API {target}; meets Google Play's rule{who}.")]
|
|
@@ -0,0 +1,41 @@
|
|
|
1
|
+
"""Turns whatever a malformed file makes a reader trip over into that reader's own error.
|
|
2
|
+
|
|
3
|
+
Readers walk untrusted bytes with offsets taken from the same bytes, so truncated or crafted
|
|
4
|
+
input can fail anywhere (struct.error, IndexError, bad encodings...). Callers should only
|
|
5
|
+
ever have to catch one error type per format.
|
|
6
|
+
"""
|
|
7
|
+
|
|
8
|
+
from __future__ import annotations
|
|
9
|
+
|
|
10
|
+
import functools
|
|
11
|
+
import struct
|
|
12
|
+
from collections.abc import Callable
|
|
13
|
+
from typing import Any
|
|
14
|
+
|
|
15
|
+
# What reading crafted bytes can raise. MemoryError and KeyboardInterrupt are not caught.
|
|
16
|
+
MALFORMED = (
|
|
17
|
+
struct.error,
|
|
18
|
+
IndexError,
|
|
19
|
+
KeyError,
|
|
20
|
+
ValueError,
|
|
21
|
+
OverflowError,
|
|
22
|
+
UnicodeError,
|
|
23
|
+
RecursionError,
|
|
24
|
+
TypeError,
|
|
25
|
+
)
|
|
26
|
+
|
|
27
|
+
|
|
28
|
+
def guarded[F: Callable[..., Any]](error: type[Exception]) -> Callable[[F], F]:
|
|
29
|
+
def wrap(fn: F) -> F:
|
|
30
|
+
@functools.wraps(fn)
|
|
31
|
+
def inner(*args: Any, **kwargs: Any) -> Any:
|
|
32
|
+
try:
|
|
33
|
+
return fn(*args, **kwargs)
|
|
34
|
+
except error:
|
|
35
|
+
raise
|
|
36
|
+
except MALFORMED as e:
|
|
37
|
+
raise error(f"malformed data ({type(e).__name__}: {e})") from e
|
|
38
|
+
|
|
39
|
+
return inner # type: ignore[return-value]
|
|
40
|
+
|
|
41
|
+
return wrap
|
|
@@ -0,0 +1,140 @@
|
|
|
1
|
+
"""Reads an APK's compiled resource table (resources.arsc) far enough to answer one kind of
|
|
2
|
+
question: which styles set a given boolean theme attribute to true, following parents.
|
|
3
|
+
|
|
4
|
+
Format reference: frameworks/base/libs/androidfw/include/androidfw/ResourceTypes.h.
|
|
5
|
+
"""
|
|
6
|
+
|
|
7
|
+
from __future__ import annotations
|
|
8
|
+
|
|
9
|
+
import struct
|
|
10
|
+
from dataclasses import dataclass, field
|
|
11
|
+
|
|
12
|
+
from storeready.android.formats._guard import guarded
|
|
13
|
+
from storeready.android.formats.axml import TYPE_BOOLEAN, read_string_pool
|
|
14
|
+
|
|
15
|
+
_TABLE = 0x0002
|
|
16
|
+
_STRING_POOL = 0x0001
|
|
17
|
+
_PACKAGE = 0x0200
|
|
18
|
+
_TYPE = 0x0201
|
|
19
|
+
|
|
20
|
+
_FLAG_SPARSE = 0x01
|
|
21
|
+
_FLAG_OFFSET16 = 0x02
|
|
22
|
+
_ENTRY_COMPLEX = 0x0001
|
|
23
|
+
_ENTRY_COMPACT = 0x0008
|
|
24
|
+
_NO_ENTRY = 0xFFFFFFFF
|
|
25
|
+
_NO_ENTRY16 = 0xFFFF
|
|
26
|
+
|
|
27
|
+
|
|
28
|
+
class ArscError(ValueError):
|
|
29
|
+
"""The bytes are not a resource table this reader understands."""
|
|
30
|
+
|
|
31
|
+
|
|
32
|
+
@dataclass
|
|
33
|
+
class _Style:
|
|
34
|
+
name: str
|
|
35
|
+
parent: int = 0
|
|
36
|
+
flag: bool | None = None # the attribute's value in this style, if set
|
|
37
|
+
configs_true: bool = False # set to true in at least one configuration
|
|
38
|
+
|
|
39
|
+
|
|
40
|
+
@dataclass
|
|
41
|
+
class _Table:
|
|
42
|
+
styles: dict[int, _Style] = field(default_factory=dict)
|
|
43
|
+
|
|
44
|
+
|
|
45
|
+
@guarded(ArscError)
|
|
46
|
+
def styles_with_flag(data: bytes, attr: int) -> dict[int, str]:
|
|
47
|
+
"""Resource id -> name of every style whose effective value of `attr` is true in at
|
|
48
|
+
least one configuration, counting values inherited from parent styles."""
|
|
49
|
+
table = _read(data, attr)
|
|
50
|
+
result: dict[int, str] = {}
|
|
51
|
+
for style_id, style in table.styles.items():
|
|
52
|
+
seen: set[int] = set()
|
|
53
|
+
current: int | None = style_id
|
|
54
|
+
while current is not None and current in table.styles and current not in seen:
|
|
55
|
+
seen.add(current)
|
|
56
|
+
node = table.styles[current]
|
|
57
|
+
if node.configs_true:
|
|
58
|
+
result[style_id] = style.name
|
|
59
|
+
break
|
|
60
|
+
if node.flag is False:
|
|
61
|
+
break
|
|
62
|
+
current = node.parent or None
|
|
63
|
+
return result
|
|
64
|
+
|
|
65
|
+
|
|
66
|
+
def _read(data: bytes, attr: int) -> _Table:
|
|
67
|
+
if len(data) < 12:
|
|
68
|
+
raise ArscError("too short")
|
|
69
|
+
kind, header_size, size = struct.unpack_from("<HHI", data, 0)
|
|
70
|
+
if kind != _TABLE or size > len(data):
|
|
71
|
+
raise ArscError("not a resource table")
|
|
72
|
+
table = _Table()
|
|
73
|
+
pos = header_size
|
|
74
|
+
while pos + 8 <= size:
|
|
75
|
+
kind, _hs, chunk_size = struct.unpack_from("<HHI", data, pos)
|
|
76
|
+
if chunk_size < 8 or pos + chunk_size > size:
|
|
77
|
+
raise ArscError(f"bad chunk at {pos}")
|
|
78
|
+
if kind == _PACKAGE:
|
|
79
|
+
_read_package(data, pos, chunk_size, attr, table)
|
|
80
|
+
pos += chunk_size
|
|
81
|
+
return table
|
|
82
|
+
|
|
83
|
+
|
|
84
|
+
def _read_package(data: bytes, start: int, size: int, attr: int, table: _Table) -> None:
|
|
85
|
+
_kind, header_size, _size, package_id = struct.unpack_from("<HHII", data, start)
|
|
86
|
+
type_strings_at, _last_type, key_strings_at = struct.unpack_from("<III", data, start + 268)
|
|
87
|
+
type_names = read_string_pool(data, start + type_strings_at)
|
|
88
|
+
key_names = read_string_pool(data, start + key_strings_at)
|
|
89
|
+
pos = start + header_size
|
|
90
|
+
end = start + size
|
|
91
|
+
while pos + 8 <= end:
|
|
92
|
+
kind, chunk_header, chunk_size = struct.unpack_from("<HHI", data, pos)
|
|
93
|
+
if chunk_size < 8 or pos + chunk_size > end:
|
|
94
|
+
raise ArscError(f"bad chunk at {pos}")
|
|
95
|
+
if kind == _TYPE:
|
|
96
|
+
type_id = data[pos + 8]
|
|
97
|
+
if 0 < type_id <= len(type_names) and type_names[type_id - 1] == "style":
|
|
98
|
+
_read_styles(data, pos, chunk_header, package_id, type_id, key_names, attr, table)
|
|
99
|
+
pos += chunk_size
|
|
100
|
+
|
|
101
|
+
|
|
102
|
+
def _read_styles(
|
|
103
|
+
data: bytes,
|
|
104
|
+
pos: int,
|
|
105
|
+
header_size: int,
|
|
106
|
+
package_id: int,
|
|
107
|
+
type_id: int,
|
|
108
|
+
keys: list[str],
|
|
109
|
+
attr: int,
|
|
110
|
+
table: _Table,
|
|
111
|
+
) -> None:
|
|
112
|
+
flags = data[pos + 9]
|
|
113
|
+
entry_count, entries_start = struct.unpack_from("<II", data, pos + 12)
|
|
114
|
+
offsets_at = pos + header_size
|
|
115
|
+
for index, offset in _entry_offsets(data, offsets_at, entry_count, flags):
|
|
116
|
+
at = pos + entries_start + offset
|
|
117
|
+
_size, entry_flags, key = struct.unpack_from("<HHI", data, at)
|
|
118
|
+
if entry_flags & _ENTRY_COMPACT or not entry_flags & _ENTRY_COMPLEX:
|
|
119
|
+
continue # a style is always a map entry
|
|
120
|
+
parent, count = struct.unpack_from("<II", data, at + 8)
|
|
121
|
+
res_id = (package_id << 24) | (type_id << 16) | index
|
|
122
|
+
style = table.styles.setdefault(res_id, _Style(keys[key] if key < len(keys) else "?"))
|
|
123
|
+
style.parent = style.parent or parent
|
|
124
|
+
map_at = at + _size
|
|
125
|
+
for i in range(count):
|
|
126
|
+
name, _vsize, _res0, kind, value = struct.unpack_from("<IHBBI", data, map_at + 12 * i)
|
|
127
|
+
if name == attr and kind == TYPE_BOOLEAN:
|
|
128
|
+
style.flag = value != 0
|
|
129
|
+
style.configs_true = style.configs_true or value != 0
|
|
130
|
+
|
|
131
|
+
|
|
132
|
+
def _entry_offsets(data: bytes, at: int, count: int, flags: int) -> list[tuple[int, int]]:
|
|
133
|
+
if flags & _FLAG_SPARSE:
|
|
134
|
+
pairs = struct.unpack_from(f"<{2 * count}H", data, at)
|
|
135
|
+
return [(pairs[i], pairs[i + 1] * 4) for i in range(0, 2 * count, 2)]
|
|
136
|
+
if flags & _FLAG_OFFSET16:
|
|
137
|
+
offsets16 = struct.unpack_from(f"<{count}H", data, at)
|
|
138
|
+
return [(i, o * 4) for i, o in enumerate(offsets16) if o != _NO_ENTRY16]
|
|
139
|
+
offsets = struct.unpack_from(f"<{count}I", data, at)
|
|
140
|
+
return [(i, o) for i, o in enumerate(offsets) if o != _NO_ENTRY]
|
|
@@ -0,0 +1,210 @@
|
|
|
1
|
+
"""Reads Android's binary XML (the compiled AndroidManifest.xml inside an APK).
|
|
2
|
+
|
|
3
|
+
Only what a manifest needs: the string pool, the resource map and the element tree.
|
|
4
|
+
Format reference: frameworks/base/libs/androidfw/include/androidfw/ResourceTypes.h.
|
|
5
|
+
"""
|
|
6
|
+
|
|
7
|
+
from __future__ import annotations
|
|
8
|
+
|
|
9
|
+
import struct
|
|
10
|
+
from dataclasses import dataclass, field
|
|
11
|
+
|
|
12
|
+
from storeready.android.formats._guard import guarded
|
|
13
|
+
|
|
14
|
+
_STRING_POOL = 0x0001
|
|
15
|
+
_XML = 0x0003
|
|
16
|
+
_START_ELEMENT = 0x0102
|
|
17
|
+
_END_ELEMENT = 0x0103
|
|
18
|
+
_RESOURCE_MAP = 0x0180
|
|
19
|
+
|
|
20
|
+
_UTF8_FLAG = 1 << 8
|
|
21
|
+
|
|
22
|
+
# Typed value kinds (Res_value::dataType).
|
|
23
|
+
TYPE_REFERENCE = 0x01
|
|
24
|
+
TYPE_STRING = 0x03
|
|
25
|
+
TYPE_FLOAT = 0x04
|
|
26
|
+
TYPE_INT_DEC = 0x10
|
|
27
|
+
TYPE_INT_HEX = 0x11
|
|
28
|
+
TYPE_BOOLEAN = 0x12
|
|
29
|
+
|
|
30
|
+
# Android attribute ids, used when a shrinker removed the attribute names.
|
|
31
|
+
# Values from the platform's public.xml (checked with `aapt2 dump xmltree`).
|
|
32
|
+
ANDROID_ATTR_IDS = {
|
|
33
|
+
0x01010000: "theme",
|
|
34
|
+
0x01010003: "name",
|
|
35
|
+
0x01010024: "value",
|
|
36
|
+
0x0101001E: "screenOrientation",
|
|
37
|
+
0x0101020C: "minSdkVersion",
|
|
38
|
+
0x0101021C: "versionName",
|
|
39
|
+
0x01010270: "targetSdkVersion",
|
|
40
|
+
0x0101028E: "required",
|
|
41
|
+
0x010104F6: "resizeableActivity",
|
|
42
|
+
0x01010545: "appCategory",
|
|
43
|
+
0x01010560: "maxAspectRatio",
|
|
44
|
+
0x0101059B: "minAspectRatio",
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
# android:windowOptOutEdgeToEdgeEnforcement, a theme attribute (read from resources.arsc).
|
|
48
|
+
ATTR_EDGE_TO_EDGE_OPT_OUT = 0x0101069A
|
|
49
|
+
|
|
50
|
+
# android:appCategory enum value for games.
|
|
51
|
+
APP_CATEGORY_GAME = 0
|
|
52
|
+
|
|
53
|
+
|
|
54
|
+
class AxmlError(ValueError):
|
|
55
|
+
"""The bytes are not a binary XML document this reader understands."""
|
|
56
|
+
|
|
57
|
+
|
|
58
|
+
@dataclass(frozen=True)
|
|
59
|
+
class Value:
|
|
60
|
+
"""One attribute value: its raw string (if any) and its typed form."""
|
|
61
|
+
|
|
62
|
+
kind: int
|
|
63
|
+
data: int
|
|
64
|
+
raw: str | None
|
|
65
|
+
|
|
66
|
+
def as_int(self) -> int | None:
|
|
67
|
+
if self.kind in (TYPE_INT_DEC, TYPE_INT_HEX):
|
|
68
|
+
return self.data - (1 << 32) if self.data >= 1 << 31 else self.data
|
|
69
|
+
if self.raw is not None:
|
|
70
|
+
try:
|
|
71
|
+
return int(self.raw, 0)
|
|
72
|
+
except ValueError:
|
|
73
|
+
return None
|
|
74
|
+
return None
|
|
75
|
+
|
|
76
|
+
def as_bool(self) -> bool | None:
|
|
77
|
+
if self.kind == TYPE_BOOLEAN:
|
|
78
|
+
return self.data != 0
|
|
79
|
+
if self.raw is not None and self.raw.lower() in ("true", "false"):
|
|
80
|
+
return self.raw.lower() == "true"
|
|
81
|
+
return None
|
|
82
|
+
|
|
83
|
+
def as_float(self) -> float | None:
|
|
84
|
+
if self.kind == TYPE_FLOAT:
|
|
85
|
+
return float(struct.unpack("<f", struct.pack("<I", self.data))[0])
|
|
86
|
+
if self.raw is not None:
|
|
87
|
+
try:
|
|
88
|
+
return float(self.raw)
|
|
89
|
+
except ValueError:
|
|
90
|
+
return None
|
|
91
|
+
return None
|
|
92
|
+
|
|
93
|
+
def as_str(self) -> str | None:
|
|
94
|
+
return self.raw
|
|
95
|
+
|
|
96
|
+
@property
|
|
97
|
+
def is_reference(self) -> bool:
|
|
98
|
+
return self.kind == TYPE_REFERENCE
|
|
99
|
+
|
|
100
|
+
|
|
101
|
+
@dataclass
|
|
102
|
+
class Element:
|
|
103
|
+
tag: str
|
|
104
|
+
attrs: dict[str, Value] = field(default_factory=dict)
|
|
105
|
+
children: list[Element] = field(default_factory=list)
|
|
106
|
+
|
|
107
|
+
def find_all(self, tag: str) -> list[Element]:
|
|
108
|
+
return [c for c in self.children if c.tag == tag]
|
|
109
|
+
|
|
110
|
+
def find(self, tag: str) -> Element | None:
|
|
111
|
+
return next((c for c in self.children if c.tag == tag), None)
|
|
112
|
+
|
|
113
|
+
|
|
114
|
+
@guarded(AxmlError)
|
|
115
|
+
def parse(data: bytes) -> Element:
|
|
116
|
+
"""Parses a binary XML document and returns its root element."""
|
|
117
|
+
if len(data) < 8:
|
|
118
|
+
raise AxmlError("too short")
|
|
119
|
+
kind, header_size, size = struct.unpack_from("<HHI", data, 0)
|
|
120
|
+
if kind != _XML or size > len(data):
|
|
121
|
+
raise AxmlError("not a binary XML document")
|
|
122
|
+
|
|
123
|
+
strings: list[str] = []
|
|
124
|
+
res_ids: list[int] = []
|
|
125
|
+
root: Element | None = None
|
|
126
|
+
stack: list[Element] = []
|
|
127
|
+
|
|
128
|
+
pos = header_size
|
|
129
|
+
while pos + 8 <= size:
|
|
130
|
+
kind, header_size, chunk_size = struct.unpack_from("<HHI", data, pos)
|
|
131
|
+
if chunk_size < 8 or pos + chunk_size > size:
|
|
132
|
+
raise AxmlError(f"bad chunk at {pos}")
|
|
133
|
+
if kind == _STRING_POOL:
|
|
134
|
+
strings = read_string_pool(data, pos)
|
|
135
|
+
elif kind == _RESOURCE_MAP:
|
|
136
|
+
count = (chunk_size - header_size) // 4
|
|
137
|
+
res_ids = list(struct.unpack_from(f"<{count}I", data, pos + header_size))
|
|
138
|
+
elif kind == _START_ELEMENT:
|
|
139
|
+
element = _read_start(data, pos, header_size, strings, res_ids)
|
|
140
|
+
if stack:
|
|
141
|
+
stack[-1].children.append(element)
|
|
142
|
+
elif root is None:
|
|
143
|
+
root = element
|
|
144
|
+
stack.append(element)
|
|
145
|
+
elif kind == _END_ELEMENT and stack:
|
|
146
|
+
stack.pop()
|
|
147
|
+
pos += chunk_size
|
|
148
|
+
|
|
149
|
+
if root is None:
|
|
150
|
+
raise AxmlError("no root element")
|
|
151
|
+
return root
|
|
152
|
+
|
|
153
|
+
|
|
154
|
+
def _string(strings: list[str], index: int) -> str | None:
|
|
155
|
+
if index == 0xFFFFFFFF or index >= len(strings):
|
|
156
|
+
return None
|
|
157
|
+
return strings[index]
|
|
158
|
+
|
|
159
|
+
|
|
160
|
+
def _read_start(
|
|
161
|
+
data: bytes, pos: int, header_size: int, strings: list[str], res_ids: list[int]
|
|
162
|
+
) -> Element:
|
|
163
|
+
ext = pos + header_size
|
|
164
|
+
_ns, name_idx, attr_start, attr_size, attr_count = struct.unpack_from("<IIHHH", data, ext)
|
|
165
|
+
element = Element(tag=_string(strings, name_idx) or "")
|
|
166
|
+
at = ext + attr_start
|
|
167
|
+
for _ in range(attr_count):
|
|
168
|
+
_ans, aname, raw_idx, _vsize, _res0, vkind, vdata = struct.unpack_from("<IIIHBBI", data, at)
|
|
169
|
+
name = _string(strings, aname) or ""
|
|
170
|
+
if not name and aname < len(res_ids):
|
|
171
|
+
name = ANDROID_ATTR_IDS.get(res_ids[aname], f"0x{res_ids[aname]:08x}")
|
|
172
|
+
raw = _string(strings, raw_idx)
|
|
173
|
+
if raw is None and vkind == TYPE_STRING:
|
|
174
|
+
raw = _string(strings, vdata)
|
|
175
|
+
element.attrs[name] = Value(kind=vkind, data=vdata, raw=raw)
|
|
176
|
+
at += attr_size or 20
|
|
177
|
+
return element
|
|
178
|
+
|
|
179
|
+
|
|
180
|
+
@guarded(AxmlError)
|
|
181
|
+
def read_string_pool(data: bytes, pos: int) -> list[str]:
|
|
182
|
+
_kind, header_size, _size, count, _styles, flags, strings_start, _ = struct.unpack_from(
|
|
183
|
+
"<HHIIIIII", data, pos
|
|
184
|
+
)
|
|
185
|
+
if pos + header_size + 4 * count > len(data):
|
|
186
|
+
raise AxmlError(f"string pool claims {count} strings, more than the data holds")
|
|
187
|
+
offsets = struct.unpack_from(f"<{count}I", data, pos + header_size)
|
|
188
|
+
base = pos + strings_start
|
|
189
|
+
utf8 = bool(flags & _UTF8_FLAG)
|
|
190
|
+
return [_read_pool_string(data, base + off, utf8) for off in offsets]
|
|
191
|
+
|
|
192
|
+
|
|
193
|
+
def _read_pool_string(data: bytes, at: int, utf8: bool) -> str:
|
|
194
|
+
if utf8:
|
|
195
|
+
_, at = _utf8_len(data, at) # length in UTF-16 units; not needed
|
|
196
|
+
n, at = _utf8_len(data, at)
|
|
197
|
+
return data[at : at + n].decode("utf-8", errors="replace")
|
|
198
|
+
n = struct.unpack_from("<H", data, at)[0]
|
|
199
|
+
at += 2
|
|
200
|
+
if n & 0x8000:
|
|
201
|
+
n = ((n & 0x7FFF) << 16) | struct.unpack_from("<H", data, at)[0]
|
|
202
|
+
at += 2
|
|
203
|
+
return data[at : at + n * 2].decode("utf-16-le", errors="replace")
|
|
204
|
+
|
|
205
|
+
|
|
206
|
+
def _utf8_len(data: bytes, at: int) -> tuple[int, int]:
|
|
207
|
+
n = data[at]
|
|
208
|
+
if n & 0x80:
|
|
209
|
+
return ((n & 0x7F) << 8) | data[at + 1], at + 2
|
|
210
|
+
return n, at + 1
|