-
Notifications
You must be signed in to change notification settings - Fork 4
/
binres.py
executable file
·2638 lines (2236 loc) · 97.8 KB
/
binres.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/python3
# encoding: utf-8
# SPDX-FileCopyrightText: 2024 FC (Fay) Stegerman <[email protected]>
# SPDX-License-Identifier: AGPL-3.0-or-later
r"""
parse/dump android binary XML (AXML) or resources (ARSC)
NB: work in progress; output format may change.
>>> dump("test/data/AndroidManifest.xml")
file='test/data/AndroidManifest.xml'
XML
STRING POOL [#strings=16, #styles=0]
XML RESOURCE MAP [#resources=6]
XML NS START [lineno=1, prefix='android', uri='http://schemas.android.com/apk/res/android']
XML ELEM START [lineno=1, name='manifest', #attributes=7]
ATTR: http://schemas.android.com/apk/res/android:versionCode=1
ATTR: http://schemas.android.com/apk/res/android:versionName='1'
ATTR: http://schemas.android.com/apk/res/android:compileSdkVersion=29
ATTR: http://schemas.android.com/apk/res/android:compileSdkVersionCodename='10.0.0'
ATTR: package='com.example'
ATTR: platformBuildVersionCode=29
ATTR: platformBuildVersionName='10.0.0'
XML ELEM START [lineno=2, name='uses-sdk', #attributes=2]
ATTR: http://schemas.android.com/apk/res/android:minSdkVersion=21
ATTR: http://schemas.android.com/apk/res/android:targetSdkVersion=29
XML ELEM END [lineno=2, name='uses-sdk']
XML ELEM END [lineno=1, name='manifest']
XML NS END [lineno=1, prefix='android', uri='http://schemas.android.com/apk/res/android']
>>> dump_apk("test/data/golden-aligned-in.apk", "resources.arsc")
entry='resources.arsc'
RESOURCE TABLE
STRING POOL [flags=0x100, #strings=3, #styles=0]
PACKAGE [id=0x7f, package_name='android.appsecurity.cts.tinyapp']
STRING POOL [flags=0x100, #strings=2, #styles=0]
STRING POOL [flags=0x100, #strings=1, #styles=0]
TYPE SPEC [id=0x1, type_name='attr', #resources=0]
TYPE SPEC [id=0x2, type_name='string', #resources=1]
TYPE [id=0x2, type_name='string', #entries=1]
CONFIG [default]
ENTRY [id=0x7f020000, key='app_name']
VALUE: 'Tiny App for CTS'
TYPE [id=0x2, type_name='string', #entries=1]
CONFIG [language='en', region='XA']
ENTRY [id=0x7f020000, key='app_name']
VALUE: '[Ţîñý Åþþ ƒöŕ ÇŢŠ one two three]'
TYPE [id=0x2, type_name='string', #entries=1]
CONFIG [language='ar', region='XB']
ENTRY [id=0x7f020000, key='app_name']
VALUE: '\u200f\u202eTiny\u202c\u200f \u200f\u202eApp\u202c\u200f \u200f\u202efor\u202c\u200f \u200f\u202eCTS\u202c\u200f'
>>> dump("test/data/AndroidManifest.xml", xml=True)
<!-- file='test/data/AndroidManifest.xml' -->
<manifest xmlns:android="http://schemas.android.com/apk/res/android" android:versionCode="1" android:versionName="1" android:compileSdkVersion="29" android:compileSdkVersionCodename="10.0.0" package="com.example" platformBuildVersionCode="29" platformBuildVersionName="10.0.0">
<uses-sdk android:minSdkVersion="21" android:targetSdkVersion="29" />
</manifest>
>>> dump("test/data/network_security_config.xml", xml=True)
<!-- file='test/data/network_security_config.xml' -->
<network-security-config>
<base-config cleartextTrafficPermitted="true" />
<domain-config cleartextTrafficPermitted="false">
<domain includeSubdomains="true">amazonaws.com</domain>
</domain-config>
<domain-config cleartextTrafficPermitted="false">
<domain includeSubdomains="true">f-droid.org</domain>
</domain-config>
<domain-config cleartextTrafficPermitted="false">
<domain includeSubdomains="true">github.com</domain>
</domain-config>
<domain-config cleartextTrafficPermitted="false">
<domain includeSubdomains="true">githubusercontent.com</domain>
</domain-config>
<domain-config cleartextTrafficPermitted="false">
<domain includeSubdomains="true">github.io</domain>
</domain-config>
<domain-config cleartextTrafficPermitted="false">
<domain includeSubdomains="true">gitlab.com</domain>
</domain-config>
<domain-config cleartextTrafficPermitted="false">
<domain includeSubdomains="true">gitlab.io</domain>
</domain-config>
</network-security-config>
>>> fastid("test/data/golden-aligned-in.apk")
package=android.appsecurity.cts.tinyapp versionCode=10 versionName=1.0
>>> fastperms("test/data/perms.apk", with_id=True)
file='test/data/perms.apk'
package=com.example versionCode=1 versionName=1
permission=android.permission.CAMERA
permission=android.permission.READ_EXTERNAL_STORAGE [maxSdkVersion=23]
>>> fastperms("test/data/perms.apk", json=True, with_id=True)
[
{
"package": "com.example",
"versionCode": 1,
"versionName": "1",
"permissions": [
{
"permission": "android.permission.CAMERA",
"attributes": {}
},
{
"permission": "android.permission.READ_EXTERNAL_STORAGE",
"attributes": {
"maxSdkVersion": "23"
}
}
]
}
]
"""
from __future__ import annotations
import binascii
import dataclasses
import io
import itertools
import json as _json
import logging
import os
import re
import struct
import sys
import textwrap
import weakref
import xml.etree.ElementTree as ET
import zipfile
import zlib
from collections import namedtuple
from dataclasses import dataclass, field
from enum import Enum
from fnmatch import fnmatch
from functools import cached_property, lru_cache
from typing import (cast, Any, BinaryIO, Callable, ClassVar, Dict, Iterable, Iterator,
List, Optional, Set, TextIO, Tuple, Union, TYPE_CHECKING)
# https://android.googlesource.com/platform/tools/base
# apkparser/binary-resources/src/main/java/com/google/devrel/gmscore/tools/apk/arsc/*.java
# https://android.googlesource.com/platform/frameworks/base
# libs/androidfw/include/androidfw/ResourceTypes.h
# tools/aapt2/ResourceValues.cpp
ARSC_MAGIC = b"\x02\x00\x0c\x00"
AXML_MAGIC = b"\x03\x00\x08\x00"
MANIFEST = "AndroidManifest.xml"
ARSC_FILE = "resources.arsc"
AXML_FILES = (MANIFEST, "res/*.xml")
SCHEMA_ANDROID = "http://schemas.android.com/apk/res/android"
UTF8, UTF16 = ("utf8", "utf_16_le")
XML_PROLOG = '<?xml version="1.0" encoding="UTF-8"?>'
ZipData = namedtuple("ZipData", ("cd_offset", "eocd_offset", "cd_and_eocd"))
class Error(Exception):
"""Base class for errors."""
class ParseError(Error):
"""Parse failure."""
class ParentError(Error):
"""Missing/deallocated parent."""
class ChildError(Error):
"""Missing child."""
class ZipError(Error):
"""Something wrong with ZIP file."""
class ResourceError(Error):
"""Resource retrieval failure."""
class ResourceNotFound(ResourceError):
"""Resource not found."""
@dataclass(frozen=True)
class Chunk:
"""Base class for chunks."""
header_size: int
chunk_size: int
parent: Optional[ChunkRef] = field(repr=False, compare=False)
level: int = field(compare=False)
offset: int = field(compare=False)
TYPE_ID: ClassVar[Optional[int]] = None
HIDDEN_FIELDS: ClassVar[Tuple[str, ...]] = ("header_size", "chunk_size", "level", "offset")
@classmethod
def _parse(_cls, header: bytes, payload: bytes, **kwargs: Any) -> Dict[str, Any]:
header_size = len(header) + 8
chunk_size = len(payload) + header_size
return dict(header_size=header_size, chunk_size=chunk_size, **kwargs)
@property
def type_id(self) -> int:
if self.__class__.TYPE_ID is not None:
return self.__class__.TYPE_ID
raise NotImplementedError("No .TYPE_ID or custom .type_id")
@classmethod
def fields(cls) -> Tuple[Tuple[str, str, int, Optional[str]], ...]:
return _fields(cls) # type: ignore[arg-type]
@dataclass(frozen=True)
class ParentChunk(Chunk):
"""Base class for chunks with children."""
children: Tuple[Chunk, ...] = field(repr=False, compare=False)
@classmethod
def _parse(_cls, header: bytes, payload: bytes, **kwargs: Any) -> Dict[str, Any]:
return Chunk._parse(header=header, payload=payload, children=None, **kwargs)
def _parse_children(self, payload: bytes) -> None:
c = tuple(read_chunks(payload, weakref.ref(self), self.level + 1, self.header_size))
object.__setattr__(self, "children", c)
@dataclass(frozen=True)
class StringPoolChunk(Chunk):
"""String pool."""
flags: int
strings: Tuple[str, ...]
styles: Tuple[Style, ...]
TYPE_ID: ClassVar[int] = 0x0001
FLAG_SORTED: ClassVar[int] = 0x1
FLAG_UTF8: ClassVar[int] = 0x100
@dataclass(frozen=True)
class Style:
"""String pool style."""
spans: Tuple[StringPoolChunk.Span, ...]
SPAN_END: ClassVar[int] = 0xFFFFFFFF
@classmethod
def fields(cls) -> Tuple[Tuple[str, str, int, Optional[str]], ...]:
return _fields(cls) # type: ignore[arg-type]
@dataclass(frozen=True)
class Span:
"""String pool style span."""
name_idx: int
start: int
stop: int
parent: StringPoolChunkRef = field(repr=False, compare=False)
@property
def name(self) -> str:
"""Get name from parent."""
if (p := self.parent()) is not None:
return p.string(self.name_idx)
raise ParentError("Parent deallocated")
@classmethod
def fields(cls) -> Tuple[Tuple[str, str, int, Optional[str]], ...]:
return _fields(cls) # type: ignore[arg-type]
# FIXME: check payload size
@classmethod
def parse(cls, header: bytes, payload: bytes, **kwargs: Any) -> StringPoolChunk:
"""Parse StringPoolChunk."""
d = Chunk._parse(header=header, payload=payload, **kwargs)
n_strs, n_styles, flags, strs_start, styles_start = struct.unpack("<IIIII", header)
codec = UTF8 if flags & cls.FLAG_UTF8 else UTF16
strings = tuple(_read_strings(payload, strs_start - d["header_size"], n_strs, codec))
chunk = cls(**d, flags=flags, strings=strings, styles=())
styles = tuple(_read_styles(payload, styles_start - d["header_size"],
n_styles, n_strs, weakref.ref(chunk)))
object.__setattr__(chunk, "styles", styles)
return chunk
@property
def is_sorted(self) -> bool:
"""Whether the sorted flag is set."""
return bool(self.flags & self.FLAG_SORTED)
@property
def is_utf8(self) -> bool:
"""Whether the UTF-8 flag is set."""
return bool(self.flags & self.FLAG_UTF8)
def string(self, idx: Optional[int]) -> str:
"""Get string by index."""
return "" if idx is None else self.strings[idx]
def style(self, idx: int) -> Style:
"""Get style by index."""
return self.styles[idx]
@property
def styled_strings(self) -> Iterable[Tuple[Optional[str], Optional[Style]]]:
"""Paired strings & styles."""
return itertools.zip_longest(self.strings, self.styles)
# FIXME: string array, styled string, ...
@dataclass(frozen=True)
class ResourceTableChunk(ParentChunk):
"""Resource table; contains string pool and packages."""
string_pool: StringPoolChunk = field(repr=False, compare=False)
packages: Tuple[Tuple[str, PackageChunk], ...] = field(repr=False, compare=False)
TYPE_ID: ClassVar[int] = 0x0002
@classmethod
def parse(cls, header: bytes, payload: bytes, **kwargs: Any) -> ResourceTableChunk:
"""Parse ResourceTableChunk."""
d = ParentChunk._parse(header=header, payload=payload, **kwargs)
_size, = struct.unpack("<I", header)
chunk = cls(**d, string_pool=cast(StringPoolChunk, None), packages=())
chunk._parse_children(payload)
string_pool, packages = None, []
for c in chunk.children:
if isinstance(c, PackageChunk):
packages.append((c.package_name, c))
elif isinstance(c, StringPoolChunk):
if string_pool is not None:
raise ParseError("Multiple StringPoolChunk children")
string_pool = c
if string_pool is None:
raise ParseError("No StringPoolChunk child")
object.__setattr__(chunk, "string_pool", string_pool)
object.__setattr__(chunk, "packages", tuple(packages))
return chunk
def get_bool(self, id: int, *, language: Optional[str] = None,
region: Optional[str] = None, density: int = 0) -> bool:
"""Get bool value."""
e = self.get_entry(id, typ=BinResVal.Type.INT_BOOLEAN, language=language,
region=region, density=density)
assert e.value is not None
return False if e.value.data == 0 else True
# FIXME: INT_HEX?!
def get_int(self, id: int, *, language: Optional[str] = None,
region: Optional[str] = None, density: int = 0) -> int:
"""Get int value."""
e = self.get_entry(id, typ=BinResVal.Type.INT_DEC, language=language,
region=region, density=density)
assert e.value is not None
return e.value.data
def get_str(self, id: int, *, language: Optional[str] = None,
region: Optional[str] = None, density: int = 0) -> str:
r"""
Get str value.
>>> chunk = quick_get_resources("test/data/golden-aligned-in.apk")
>>> chunk.get_str(0x7f020000)
'Tiny App for CTS'
>>> chunk.get_str(0x7f020000, language="en", region="XA")
'[Ţîñý Åþþ ƒöŕ ÇŢŠ one two three]'
>>> with open("test/data/resources1.arsc", "rb") as fh:
... chunk = parse(fh.read())[0]
>>> chunk.get_str(0x7f010001)
'res/drawable/presplash.jpg'
"""
e = self.get_entry(id, typ=BinResVal.Type.STRING, language=language,
region=region, density=density)
return e.str_value()
def _get_value(self, typ: type, *args: Any, **kwargs: Any) -> Any:
if typ is bool:
return self.get_bool(*args, **kwargs)
if typ is int:
return self.get_int(*args, **kwargs)
if typ is str:
return self.get_str(*args, **kwargs)
raise ValueError(f"Unsupported type {typ.__name__}")
def get_entry(self, id: int, *, typ: Optional[BinResVal.Type] = None, array: bool = False,
language: Optional[str] = None, region: Optional[str] = None,
density: int = 0) -> TypeChunk.Entry:
r"""
Get (first matching) type chunk entry with specified ID.
>>> chunk = quick_get_resources("test/data/golden-aligned-in.apk")
>>> e = chunk.get_entry(0x7f020000)
>>> e
TypeChunk.Entry(header_size=8, flags=0, key_idx=0, value=BinResVal(size=8, type=<Type.STRING: 3>, data=0, res0=0), values=(), parent_entry=0)
>>> e.key
'app_name'
>>> e.str_value()
'Tiny App for CTS'
"""
entries = self.find_entries(id, typ=typ, array=array, return_first=True,
language=language, region=region, density=density)
if not entries:
raise ResourceNotFound(f"No matching entry for {hex(id)}")
return entries[0]
def find_entries(self, id: int, *, typ: Optional[BinResVal.Type] = None, array: bool = False,
return_first: bool = True, language: Optional[str] = None,
region: Optional[str] = None, density: int = 0) -> List[TypeChunk.Entry]:
r"""
Get (first/all matching) type chunk entries with specified ID.
NB: there should only be one matching entry, but this is not enforced;
finding all entries is thus provided for analysis purposes.
>>> chunk = quick_get_resources("test/data/golden-aligned-in.apk")
>>> entries = chunk.find_entries(0x7f020000)
>>> [e.str_value() for e in entries]
['Tiny App for CTS']
"""
entries = []
fltr = dict(language=language, region=region, density=density)
rid = BinResId.from_int(id)
if rid.package_id not in self.packages_by_id:
raise ResourceError(f"No package with id {rid.package_id}")
for t in self.package_with_id(rid.package_id).type_chunks(rid.type_id):
for k, v in fltr.items():
if getattr(t.configuration, k) != v:
break
else:
for i, e in t.entries:
if i == rid.entry_id:
if e.is_complex and not array:
raise ResourceError(f"Type mismatch for {hex(id)}: expected scalar")
if not e.is_complex and array:
raise ResourceError(f"Type mismatch for {hex(id)}: expected complex")
for val in e.values_as_dict.values():
if typ and val.type is not typ:
raise ResourceError(f"Type mismatch for {hex(id)}: expected "
f"{typ.name}, got {val.type.name}")
entries.append(e)
if return_first:
return entries
return entries
@cached_property
def packages_as_dict(self) -> Dict[str, PackageChunk]:
"""Packages as dict, indexed by name."""
return dict(self.packages)
@cached_property
def packages_by_id(self) -> Dict[int, PackageChunk]:
"""Packages as dict, indexed by ID."""
return {p.id: p for _, p in self.packages}
def package(self, name: str) -> PackageChunk:
"""Get package by name."""
return self.packages_as_dict[name]
def package_with_id(self, id: int) -> PackageChunk:
"""Get package by ID."""
return self.packages_by_id[id]
@dataclass(frozen=True)
class XMLChunk(ParentChunk):
"""XML chunk; contains string pool and XML nodes."""
TYPE_ID: ClassVar[int] = 0x0003
@classmethod
def parse(cls, header: bytes, payload: bytes, **kwargs: Any) -> XMLChunk:
"""Parse XMLChunk."""
if header:
raise ParseError("Expected empty header")
chunk = cls(**ParentChunk._parse(header=header, payload=payload, **kwargs))
chunk._parse_children(payload)
return chunk
@cached_property
def string_pool(self) -> StringPoolChunk:
"""Get string pool child."""
for c in self.children:
if isinstance(c, StringPoolChunk):
return c
raise ChildError("No StringPoolChunk child")
def string(self, idx: Optional[int]) -> str:
"""Get string from string pool by index."""
return self.string_pool.string(idx)
@dataclass(frozen=True)
class XMLNodeChunk(Chunk):
"""Base class for XML node chunks."""
lineno: int
comment_idx: Optional[int]
@classmethod
def _parse(_cls, header: bytes, payload: bytes, **kwargs: Any) -> Dict[str, Any]:
d = Chunk._parse(header=header, payload=payload, **kwargs)
lineno, comment_idx = struct.unpack("<II", header)
return dict(**d, lineno=lineno, comment_idx=_noref(comment_idx))
# FIXME: weakref?
@cached_property
def xml_chunk(self) -> XMLChunk:
"""Get XMLChunk parent."""
r = self.parent
while r is not None:
if (p := r()) is None:
raise ParentError("Parent deallocated")
if isinstance(p, XMLChunk):
return p
r = p.parent
raise ParentError("No XMLChunk parent")
def string(self, idx: Optional[int]) -> str:
"""Get string from XML chunk parent by index."""
return "" if idx is None else self.xml_chunk.string(idx)
@property
def comment(self) -> str:
"""Get comment string."""
return self.string(self.comment_idx)
@dataclass(frozen=True)
class XMLNSChunk(XMLNodeChunk):
"""Base class for XML namespace chunks."""
prefix_idx: int
uri_idx: int
@classmethod
def _parse(_cls, header: bytes, payload: bytes, **kwargs: Any) -> Dict[str, Any]:
d = XMLNodeChunk._parse(header=header, payload=payload, **kwargs)
prefix_idx, uri_idx = struct.unpack("<II", payload)
return dict(**d, prefix_idx=prefix_idx, uri_idx=uri_idx)
@property
def prefix(self) -> str:
"""Get prefix string."""
return self.string(self.prefix_idx)
@property
def uri(self) -> str:
"""Get uri string."""
return self.string(self.uri_idx)
@dataclass(frozen=True)
class XMLNSStartChunk(XMLNSChunk):
"""XML namespace start."""
TYPE_ID: ClassVar[int] = 0x0100
@classmethod
def parse(cls, header: bytes, payload: bytes, **kwargs: Any) -> XMLNSStartChunk:
"""Parse XMLNSStartChunk."""
return cls(**XMLNSChunk._parse(header=header, payload=payload, **kwargs))
@dataclass(frozen=True)
class XMLNSEndChunk(XMLNSChunk):
"""XML namespace end."""
TYPE_ID: ClassVar[int] = 0x0101
@classmethod
def parse(cls, header: bytes, payload: bytes, **kwargs: Any) -> XMLNSEndChunk:
"""Parse XMLNSEndChunk."""
return cls(**XMLNSChunk._parse(header=header, payload=payload, **kwargs))
@dataclass(frozen=True)
class XMLElemStartChunk(XMLNodeChunk):
"""XML element start; contains XML attributes."""
namespace_idx: Optional[int]
name_idx: int
id_idx: Optional[int]
class_idx: Optional[int]
style_idx: Optional[int]
attributes: Tuple[XMLAttr, ...]
TYPE_ID: ClassVar[int] = 0x0102
# FIXME: check payload size
@classmethod
def parse(cls, header: bytes, payload: bytes, **kwargs: Any) -> XMLElemStartChunk:
"""Parse XMLElemStartChunk."""
d = XMLNodeChunk._parse(header=header, payload=payload, **kwargs)
ns_idx, name_idx, attr_start, attr_size, n_attrs, id_idx, class_idx, \
style_idx, data = _unpack("<IIHHHHHH", payload)
if attr_size != 20:
raise ParseError("Wrong XML attribute size")
# NB: adjust 1-based indices
chunk = cls(**d, namespace_idx=_noref(ns_idx), name_idx=name_idx,
id_idx=_noref(id_idx - 1), class_idx=_noref(class_idx - 1),
style_idx=_noref(style_idx - 1), attributes=())
attrs = tuple(_read_attrs(data, weakref.ref(chunk), attr_start - 20, n_attrs))
object.__setattr__(chunk, "attributes", attrs)
return chunk
def attr_as_bool(self, name: str, **kwargs: Any) -> Optional[bool]:
"""Get bool attr."""
value = self._attr_as(bool, name, **kwargs)
assert value is None or isinstance(value, bool)
return value
def attr_as_int(self, name: str, **kwargs: Any) -> Optional[int]:
"""Get int attr."""
value = self._attr_as(int, name, **kwargs)
assert value is None or isinstance(value, int)
return value
def attr_as_str(self, name: str, **kwargs: Any) -> Optional[str]:
"""Get str attr."""
value = self._attr_as(str, name, **kwargs)
assert value is None or isinstance(value, str)
return value
def _attr_as(self, typ: type, name: str, *, android: bool = False, optional: bool = False,
resources: Optional[ResourceTableChunk] = None) -> Any:
brv_type = py_type_to_brv_type(typ)
if android:
name = f"{{{SCHEMA_ANDROID}}}{name}"
if name not in self.attrs_as_dict:
if optional:
return None
raise ParseError(f"No such attribute: {name!r}")
attr = self.attrs_as_dict[name]
if resources and attr.typed_value.type is BinResVal.Type.REFERENCE:
value = resources._get_value(typ, attr.typed_value.data)
if not isinstance(value, typ):
raise ParseError(f"Wrong type for resource referenced by attribute {name!r}: "
f"expected {typ.__name__}, got {type(value).__name__}")
return value
if attr.typed_value.type is not brv_type:
raise ParseError(f"Wrong type for attribute {name!r}: "
f"expected {brv_type.name}, got {attr.typed_value.type.name}")
return brv_to_py(attr.typed_value, attr.raw_value)[2]
@cached_property
def attrs_as_dict(self) -> Dict[str, XMLAttr]:
"""XML attributes as dict."""
d = {}
for a in self.attributes:
if (n := a.name_with_ns) in d:
raise ParseError(f"Duplicate attribute name: {n!r}")
d[n] = a
return d
@property
def namespace(self) -> str:
"""Get namespace string."""
return self.string(self.namespace_idx)
@property
def name(self) -> str:
"""Get name string."""
return self.string(self.name_idx)
@dataclass(frozen=True)
class XMLElemEndChunk(XMLNodeChunk):
"""XML element end."""
namespace_idx: Optional[int]
name_idx: int
TYPE_ID: ClassVar[int] = 0x0103
@classmethod
def parse(cls, header: bytes, payload: bytes, **kwargs: Any) -> XMLElemEndChunk:
"""Parse XMLElemEndChunk."""
d = XMLNodeChunk._parse(header=header, payload=payload, **kwargs)
namespace_idx, name_idx = struct.unpack("<II", payload)
return cls(**d, namespace_idx=_noref(namespace_idx), name_idx=name_idx)
@property
def namespace(self) -> str:
"""Get namespace string."""
return self.string(self.namespace_idx)
@property
def name(self) -> str:
"""Get name string."""
return self.string(self.name_idx)
@dataclass(frozen=True)
class XMLCDATAChunk(XMLNodeChunk):
"""XML CDATA."""
raw_value_idx: int
typed_value: BinResVal
TYPE_ID: ClassVar[int] = 0x0104
@classmethod
def parse(cls, header: bytes, payload: bytes, **kwargs: Any) -> XMLCDATAChunk:
"""Parse XMLCDATAChunk."""
d = XMLNodeChunk._parse(header=header, payload=payload, **kwargs)
raw_value_idx, tv_data = _unpack("<I", payload)
return cls(**d, raw_value_idx=raw_value_idx, typed_value=_read_brv(tv_data))
@property
def raw_value(self) -> str:
"""Get raw value string."""
return self.string(self.raw_value_idx)
@dataclass(frozen=True)
class XMLResourceMapChunk(Chunk):
"""XML resource map."""
resources: Tuple[int, ...]
TYPE_ID: ClassVar[int] = 0x0180
@classmethod
def parse(cls, header: bytes, payload: bytes, **kwargs: Any) -> XMLResourceMapChunk:
"""Parse XMLResourceMapChunk."""
d = Chunk._parse(header=header, payload=payload, **kwargs)
n = (d["chunk_size"] - d["header_size"]) // 4
return cls(**d, resources=struct.unpack(f"<{n}I", payload))
def resource(self, i: int) -> BinResId:
"""Get resource by index."""
return BinResId.from_int(self.resources[i])
@dataclass(frozen=True)
class PackageChunk(ParentChunk):
"""
Package chunk; contains type specs and types.
NB: types can have multiple values for the same key.
"""
id: int
package_name: str
type_specs: Tuple[Tuple[int, TypeSpecChunk], ...] = field(repr=False, compare=False)
types: Tuple[Tuple[int, TypeChunk], ...] = field(repr=False, compare=False)
library_chunk: Optional[LibraryChunk] = field(repr=False, compare=False)
type_strings_offset: int = field(compare=False)
key_strings_offset: int = field(compare=False)
TYPE_ID: ClassVar[int] = 0x0200
# NB: last public type/key offset in string pool & type id offset are unused;
# type id offset can be missing in some (older) APKs
@classmethod
def parse(cls, header: bytes, payload: bytes, **kwargs: Any) -> PackageChunk:
"""Parse PackageChunk."""
d = ParentChunk._parse(header=header, payload=payload, **kwargs)
hdr = header + bytes(4) if len(header) == 276 else header
id_, name_b, t_off, last_pub_t, k_off, last_pub_k, tid_off = \
struct.unpack("<I256sIIIII", hdr)
name = _decode_package_name(name_b)
chunk = cls(**d, id=id_, package_name=name, type_specs=(), types=(),
library_chunk=None, key_strings_offset=k_off, type_strings_offset=t_off)
chunk._parse_children(payload)
type_specs, types, library_chunk = [], [], None
for c in chunk.children:
if isinstance(c, TypeSpecChunk):
type_specs.append((c.id, c))
elif isinstance(c, TypeChunk):
types.append((c.id, c))
elif isinstance(c, LibraryChunk):
if library_chunk is not None:
raise ParseError("Multiple LibraryChunk children")
library_chunk = c
elif not isinstance(c, StringPoolChunk):
raise ParseError(f"Unexpected {c.__class__.__name__} child")
object.__setattr__(chunk, "type_specs", tuple(type_specs))
object.__setattr__(chunk, "types", tuple(types))
object.__setattr__(chunk, "library_chunk", library_chunk)
return chunk
@cached_property
def type_specs_as_dict(self) -> Dict[int, TypeSpecChunk]:
"""Type specs as dict."""
return dict(self.type_specs)
@cached_property
def types_as_dict(self) -> Dict[int, List[TypeChunk]]:
"""Types as dict of lists."""
d: Dict[int, List[TypeChunk]] = {}
for i, c in self.types:
d.setdefault(i, []).append(c)
return d
def type_spec_chunks(self) -> Tuple[TypeSpecChunk, ...]:
"""Get all type specs."""
return tuple(c for _, c in self.type_specs)
def type_spec_chunk(self, type_id: Union[int, str]) -> TypeSpecChunk:
"""Get type spec by id"""
if isinstance(type_id, str):
type_id = self.type_string_pool.strings.index(type_id) + 1
return self.type_specs_as_dict[type_id]
def type_chunks(self, type_id: Union[int, str, None]) -> Tuple[TypeChunk, ...]:
"""Get all types or types by id."""
if type_id is None:
return tuple(c for _, c in self.types)
if isinstance(type_id, str):
type_id = self.type_string_pool.strings.index(type_id) + 1
return tuple(self.types_as_dict[type_id])
@cached_property
def type_string_pool(self) -> StringPoolChunk:
"""Get type string pool child."""
return self._string_pool(self.type_strings_offset, "type")
@cached_property
def key_string_pool(self) -> StringPoolChunk:
"""Get key string pool child."""
return self._string_pool(self.key_strings_offset, "key")
def _string_pool(self, offset: int, what: str) -> StringPoolChunk:
pool = None
for c in self.children:
if c.offset == offset:
pool = c
break
if not isinstance(pool, StringPoolChunk):
raise ChildError(f"Unable to find {what} string pool")
return pool
@dataclass(frozen=True)
class TypeOrSpecChunk(Chunk):
"""Base class for TypeChunk and TypeSpecChunk."""
id: int
SUBFIELDS: ClassVar[Dict[str, Tuple[str, ...]]] = dict(id=("#keep", "type_name"))
@classmethod
def _parse(_cls, header: bytes, payload: bytes, **kwargs: Any) -> Dict[str, Any]:
return Chunk._parse(header=header, payload=payload, **kwargs)
# FIXME: weakref?
@cached_property
def package_chunk(self) -> Optional[PackageChunk]:
"""Get PackageChunk parent."""
r = self.parent
while r is not None:
if (p := r()) is None:
raise ParentError("Parent deallocated")
if isinstance(p, PackageChunk):
return p
r = p.parent
return None
@property
def type_name(self) -> str:
"""Get type name from package chunk type string pool."""
if (c := self.package_chunk) is None:
raise ParentError("No PackageChunk parent")
return c.type_string_pool.strings[self.id - 1]
def resource_id(self, entry_id: int) -> BinResId:
"""Get resource ID (package + type + entry) for entry."""
if (c := self.package_chunk) is None:
raise ParentError("No PackageChunk parent")
return BinResId(c.id, self.id, entry_id)
# FIXME: FLAG_SPARSE untested!
# FIXME: overlay packages
@dataclass(frozen=True)
class TypeChunk(TypeOrSpecChunk):
"""Type chunk; contains entries and configuration."""
entries: Tuple[Tuple[int, Entry], ...]
configuration: BinResCfg
flags: int
TYPE_ID: ClassVar[int] = 0x0201
NO_ENTRY: ClassVar[int] = 0xFFFFFFFF
NO_ENTRY_OFFSET16: ClassVar[int] = 0xFFFF
FLAG_SPARSE: ClassVar[int] = 0x01
FLAG_OFFSET16: ClassVar[int] = 0x02
@dataclass(frozen=True)
class Entry:
"""Type chunk entry."""
header_size: int
flags: int
key_idx: int
value: Optional[BinResVal]
values: Tuple[Tuple[int, BinResVal], ...]
parent_entry: int
parent: TypeChunkRef = field(repr=False, compare=False)
HIDDEN_FIELDS: ClassVar[Tuple[str, ...]] = ("header_size",)
FLAG_COMPLEX: ClassVar[int] = 0x1
FLAG_PUBLIC: ClassVar[int] = 0x2
FLAG_WEAK: ClassVar[int] = 0x4
FLAG_COMPACT: ClassVar[int] = 0x8
@cached_property
def values_as_dict(self) -> Dict[Optional[int], BinResVal]:
"""Values as dict (array will be enumerated)."""
if self.is_complex:
if self.is_array:
return dict(enumerate(self.values_as_list))
d: Dict[Optional[int], BinResVal] = {}
for k, v in self.values:
if k in d:
raise ParseError(f"Duplicate value ID: {k}")
d[k] = v
return d
assert self.value is not None
return {None: self.value}
@cached_property
def values_as_list(self) -> List[BinResVal]:
"""Values as list (must be array)."""
if not self.is_array:
raise ParseError("Expected array")
return [v for k, v in self.values]
@cached_property
def is_array(self) -> bool:
"""Whether the entry is complex with all zero keys."""
return self.is_complex and all(k == 0 for k, v in self.values)
@property
def is_complex(self) -> bool:
"""Whether the entry has multiple values (instead of one value)."""
return bool(self.flags & self.FLAG_COMPLEX)
@property
def is_public(self) -> bool:
"""Whether the entry is public (libraries can reference it)."""
return bool(self.flags & self.FLAG_PUBLIC)
@property
def is_weak(self) -> bool:
"""Whether the entry is weak (can be overridden)."""
return bool(self.flags & self.FLAG_WEAK)
@property
def is_compact(self) -> bool:
"""Whether the entry is compact."""
return bool(self.flags & self.FLAG_COMPACT)
@property
def key(self) -> str:
"""Get key name from TypeChunk parent."""
if (p := self.parent()) is not None:
return p.key_name(self.key_idx)
raise ParentError("Parent deallocated")
def string(self, idx: Optional[int]) -> str:
"""Get string from string pool by index."""
if (p := self.parent()) is not None:
return p.string(idx)
raise ParentError("Parent deallocated")
def str_value(self) -> str:
"""Get string value."""
if self.is_complex:
raise ResourceError("Expected scalar value")
assert self.value is not None
if self.value.type is not BinResVal.Type.STRING:
raise ResourceError("Expected string value")
return self.string(self.value.data)
@classmethod
def fields(cls) -> Tuple[Tuple[str, str, int, Optional[str]], ...]:
return _fields(cls) # type: ignore[arg-type]
@classmethod
def parse(cls, header: bytes, payload: bytes, **kwargs: Any) -> TypeChunk:
"""Parse TypeChunk."""
d = TypeOrSpecChunk._parse(header=header, payload=payload, **kwargs)
id_, t_flags, reserved, n_ents, start, cfg_data = _unpack("<BBHII", header)
chunk = cls(**d, id=id_, entries=(), configuration=_read_cfg(cfg_data), flags=t_flags)
entries = []
if t_flags & cls.FLAG_SPARSE:
_untested("FLAG_SPARSE")
for i in range(n_ents):
if t_flags & cls.FLAG_SPARSE:
idx, off16 = struct.unpack("<HH", payload[4 * i:4 * (i + 1)])
off = off16 * 4
elif t_flags & cls.FLAG_OFFSET16:
idx = i
off16, = struct.unpack("<H", payload[2 * i:2 * (i + 1)])
off = cls.NO_ENTRY if off16 == cls.NO_ENTRY_OFFSET16 else off16 * 4
else:
idx = i
off, = struct.unpack("<I", payload[4 * i:4 * (i + 1)])