This repository has been archived by the owner on Feb 19, 2024. It is now read-only.
forked from xpirt/img2sdat
-
Notifications
You must be signed in to change notification settings - Fork 3
/
common.py
executable file
·4264 lines (3528 loc) · 150 KB
/
common.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
# Copyright (C) 2008 The Android Open Source Project
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
from __future__ import print_function
import base64
import collections
import copy
import datetime
import errno
import fnmatch
import getopt
import getpass
import gzip
import imp
import json
import logging
import logging.config
import os
import platform
import re
import shlex
import shutil
import subprocess
import stat
import sys
import tempfile
import threading
import time
import zipfile
from dataclasses import dataclass
from genericpath import isdir
from hashlib import sha1, sha256
import images
import rangelib
import sparse_img
from blockimgdiff import BlockImageDiff
logger = logging.getLogger(__name__)
class Options(object):
def __init__(self):
# Set up search path, in order to find framework/ and lib64/. At the time of
# running this function, user-supplied search path (`--path`) hasn't been
# available. So the value set here is the default, which might be overridden
# by commandline flag later.
exec_path = os.path.realpath(sys.argv[0])
if exec_path.endswith('.py'):
script_name = os.path.basename(exec_path)
# logger hasn't been initialized yet at this point. Use print to output
# warnings.
print(
'Warning: releasetools script should be invoked as hermetic Python '
'executable -- build and run `{}` directly.'.format(
script_name[:-3]),
file=sys.stderr)
self.search_path = os.path.dirname(os.path.dirname(exec_path))
self.signapk_path = "framework/signapk.jar" # Relative to search_path
if not os.path.exists(os.path.join(self.search_path, self.signapk_path)):
if "ANDROID_HOST_OUT" in os.environ:
self.search_path = os.environ["ANDROID_HOST_OUT"]
self.signapk_shared_library_path = "lib64" # Relative to search_path
self.extra_signapk_args = []
self.aapt2_path = "aapt2"
self.java_path = "java" # Use the one on the path by default.
self.java_args = ["-Xmx4096m"] # The default JVM args.
self.android_jar_path = None
self.public_key_suffix = ".x509.pem"
self.private_key_suffix = ".pk8"
# use otatools built boot_signer by default
self.verbose = False
self.tempfiles = []
self.device_specific = None
self.extras = {}
self.info_dict = None
self.source_info_dict = None
self.target_info_dict = None
self.worker_threads = None
# Stash size cannot exceed cache_size * threshold.
self.cache_size = None
self.stash_threshold = 0.8
self.logfile = None
OPTIONS = Options()
# The block size that's used across the releasetools scripts.
BLOCK_SIZE = 4096
# Values for "certificate" in apkcerts that mean special things.
SPECIAL_CERT_STRINGS = ("PRESIGNED", "EXTERNAL")
# The partitions allowed to be signed by AVB (Android Verified Boot 2.0). Note
# that system_other is not in the list because we don't want to include its
# descriptor into vbmeta.img. When adding a new entry here, the
# AVB_FOOTER_ARGS_BY_PARTITION in sign_target_files_apks need to be updated
# accordingly.
AVB_PARTITIONS = ('boot', 'init_boot', 'dtbo', 'odm', 'product', 'pvmfw',
'recovery', 'system', 'system_ext', 'vendor', 'vendor_boot',
'vendor_kernel_boot', 'vendor_dlkm', 'odm_dlkm',
'system_dlkm')
# Chained VBMeta partitions.
AVB_VBMETA_PARTITIONS = ('vbmeta_system', 'vbmeta_vendor')
# avbtool arguments name
AVB_ARG_NAME_INCLUDE_DESC_FROM_IMG = '--include_descriptors_from_image'
AVB_ARG_NAME_CHAIN_PARTITION = '--chain_partition'
# Partitions that should have their care_map added to META/care_map.pb
PARTITIONS_WITH_CARE_MAP = [
'system',
'vendor',
'product',
'system_ext',
'odm',
'vendor_dlkm',
'odm_dlkm',
'system_dlkm',
]
# Partitions with a build.prop file
PARTITIONS_WITH_BUILD_PROP = PARTITIONS_WITH_CARE_MAP + ['boot', 'init_boot']
# See sysprop.mk. If file is moved, add new search paths here; don't remove
# existing search paths.
RAMDISK_BUILD_PROP_REL_PATHS = ['system/etc/ramdisk/build.prop']
@dataclass
class AvbChainedPartitionArg:
"""The required arguments for avbtool --chain_partition."""
partition: str
rollback_index_location: int
pubkey_path: str
def to_string(self):
"""Convert to string command arguments."""
return '{}:{}:{}'.format(
self.partition, self.rollback_index_location, self.pubkey_path)
class ErrorCode(object):
"""Define error_codes for failures that happen during the actual
update package installation.
Error codes 0-999 are reserved for failures before the package
installation (i.e. low battery, package verification failure).
Detailed code in 'bootable/recovery/error_code.h' """
SYSTEM_VERIFICATION_FAILURE = 1000
SYSTEM_UPDATE_FAILURE = 1001
SYSTEM_UNEXPECTED_CONTENTS = 1002
SYSTEM_NONZERO_CONTENTS = 1003
SYSTEM_RECOVER_FAILURE = 1004
VENDOR_VERIFICATION_FAILURE = 2000
VENDOR_UPDATE_FAILURE = 2001
VENDOR_UNEXPECTED_CONTENTS = 2002
VENDOR_NONZERO_CONTENTS = 2003
VENDOR_RECOVER_FAILURE = 2004
OEM_PROP_MISMATCH = 3000
FINGERPRINT_MISMATCH = 3001
THUMBPRINT_MISMATCH = 3002
OLDER_BUILD = 3003
DEVICE_MISMATCH = 3004
BAD_PATCH_FILE = 3005
INSUFFICIENT_CACHE_SPACE = 3006
TUNE_PARTITION_FAILURE = 3007
APPLY_PATCH_FAILURE = 3008
class ExternalError(RuntimeError):
pass
def InitLogging():
DEFAULT_LOGGING_CONFIG = {
'version': 1,
'disable_existing_loggers': False,
'formatters': {
'standard': {
'format':
'%(asctime)s - %(filename)s - %(levelname)-8s: %(message)s',
'datefmt': '%Y-%m-%d %H:%M:%S',
},
},
'handlers': {
'default': {
'class': 'logging.StreamHandler',
'formatter': 'standard',
'level': 'WARNING',
},
},
'loggers': {
'': {
'handlers': ['default'],
'propagate': True,
'level': 'NOTSET',
}
}
}
env_config = os.getenv('LOGGING_CONFIG')
if env_config:
with open(env_config) as f:
config = json.load(f)
else:
config = DEFAULT_LOGGING_CONFIG
# Increase the logging level for verbose mode.
if OPTIONS.verbose:
config = copy.deepcopy(config)
config['handlers']['default']['level'] = 'INFO'
if OPTIONS.logfile:
config = copy.deepcopy(config)
config['handlers']['logfile'] = {
'class': 'logging.FileHandler',
'formatter': 'standard',
'level': 'INFO',
'mode': 'w',
'filename': OPTIONS.logfile,
}
config['loggers']['']['handlers'].append('logfile')
logging.config.dictConfig(config)
def FindHostToolPath(tool_name):
"""Finds the path to the host tool.
Args:
tool_name: name of the tool to find
Returns:
path to the tool if found under the same directory as this binary is located at. If not found,
tool_name is returned.
"""
my_dir = os.path.dirname(os.path.realpath(sys.argv[0]))
tool_path = os.path.join(my_dir, tool_name)
if os.path.exists(tool_path):
return tool_path
return tool_name
def Run(args, verbose=None, **kwargs):
"""Creates and returns a subprocess.Popen object.
Args:
args: The command represented as a list of strings.
verbose: Whether the commands should be shown. Default to the global
verbosity if unspecified.
kwargs: Any additional args to be passed to subprocess.Popen(), such as env,
stdin, etc. stdout and stderr will default to subprocess.PIPE and
subprocess.STDOUT respectively unless caller specifies any of them.
universal_newlines will default to True, as most of the users in
releasetools expect string output.
Returns:
A subprocess.Popen object.
"""
if 'stdout' not in kwargs and 'stderr' not in kwargs:
kwargs['stdout'] = subprocess.PIPE
kwargs['stderr'] = subprocess.STDOUT
if 'universal_newlines' not in kwargs:
kwargs['universal_newlines'] = True
if args:
# Make a copy of args in case client relies on the content of args later.
args = args[:]
args[0] = FindHostToolPath(args[0])
if verbose is None:
verbose = OPTIONS.verbose
# Don't log any if caller explicitly says so.
if verbose:
logger.info(" Running: \"%s\"", " ".join(args))
return subprocess.Popen(args, **kwargs)
def RunAndCheckOutput(args, verbose=None, **kwargs):
"""Runs the given command and returns the output.
Args:
args: The command represented as a list of strings.
verbose: Whether the commands should be shown. Default to the global
verbosity if unspecified.
kwargs: Any additional args to be passed to subprocess.Popen(), such as env,
stdin, etc. stdout and stderr will default to subprocess.PIPE and
subprocess.STDOUT respectively unless caller specifies any of them.
Returns:
The output string.
Raises:
ExternalError: On non-zero exit from the command.
"""
if verbose is None:
verbose = OPTIONS.verbose
proc = Run(args, verbose=verbose, **kwargs)
output, _ = proc.communicate()
if output is None:
output = ""
# Don't log any if caller explicitly says so.
if verbose:
logger.info("%s", output.rstrip())
if proc.returncode != 0:
raise ExternalError(
"Failed to run command '{}' (exit code {}):\n{}".format(
args, proc.returncode, output))
return output
def RoundUpTo4K(value):
rounded_up = value + 4095
return rounded_up - (rounded_up % 4096)
def CloseInheritedPipes():
""" Gmake in MAC OS has file descriptor (PIPE) leak. We close those fds
before doing other work."""
if platform.system() != "Darwin":
return
for d in range(3, 1025):
try:
stat = os.fstat(d)
if stat is not None:
pipebit = stat[0] & 0x1000
if pipebit != 0:
os.close(d)
except OSError:
pass
class BuildInfo(object):
"""A class that holds the information for a given build.
This class wraps up the property querying for a given source or target build.
It abstracts away the logic of handling OEM-specific properties, and caches
the commonly used properties such as fingerprint.
There are two types of info dicts: a) build-time info dict, which is generated
at build time (i.e. included in a target_files zip); b) OEM info dict that is
specified at package generation time (via command line argument
'--oem_settings'). If a build doesn't use OEM-specific properties (i.e. not
having "oem_fingerprint_properties" in build-time info dict), all the queries
would be answered based on build-time info dict only. Otherwise if using
OEM-specific properties, some of them will be calculated from two info dicts.
Users can query properties similarly as using a dict() (e.g. info['fstab']),
or to query build properties via GetBuildProp() or GetPartitionBuildProp().
Attributes:
info_dict: The build-time info dict.
is_ab: Whether it's a build that uses A/B OTA.
oem_dicts: A list of OEM dicts.
oem_props: A list of OEM properties that should be read from OEM dicts; None
if the build doesn't use any OEM-specific property.
fingerprint: The fingerprint of the build, which would be calculated based
on OEM properties if applicable.
device: The device name, which could come from OEM dicts if applicable.
"""
_RO_PRODUCT_RESOLVE_PROPS = ["ro.product.brand", "ro.product.device",
"ro.product.manufacturer", "ro.product.model",
"ro.product.name"]
_RO_PRODUCT_PROPS_DEFAULT_SOURCE_ORDER_CURRENT = [
"product", "odm", "vendor", "system_ext", "system"]
_RO_PRODUCT_PROPS_DEFAULT_SOURCE_ORDER_ANDROID_10 = [
"product", "product_services", "odm", "vendor", "system"]
_RO_PRODUCT_PROPS_DEFAULT_SOURCE_ORDER_LEGACY = []
# The length of vbmeta digest to append to the fingerprint
_VBMETA_DIGEST_SIZE_USED = 8
def __init__(self, info_dict, oem_dicts=None, use_legacy_id=False):
"""Initializes a BuildInfo instance with the given dicts.
Note that it only wraps up the given dicts, without making copies.
Arguments:
info_dict: The build-time info dict.
oem_dicts: A list of OEM dicts (which is parsed from --oem_settings). Note
that it always uses the first dict to calculate the fingerprint or the
device name. The rest would be used for asserting OEM properties only
(e.g. one package can be installed on one of these devices).
use_legacy_id: Use the legacy build id to construct the fingerprint. This
is used when we need a BuildInfo class, while the vbmeta digest is
unavailable.
Raises:
ValueError: On invalid inputs.
"""
self.info_dict = info_dict
self.oem_dicts = oem_dicts
self._is_ab = info_dict.get("ab_update") == "true"
self.use_legacy_id = use_legacy_id
# Skip _oem_props if oem_dicts is None to use BuildInfo in
# sign_target_files_apks
if self.oem_dicts:
self._oem_props = info_dict.get("oem_fingerprint_properties")
else:
self._oem_props = None
def check_fingerprint(fingerprint):
if (" " in fingerprint or any(ord(ch) > 127 for ch in fingerprint)):
raise ValueError(
'Invalid build fingerprint: "{}". See the requirement in Android CDD '
"3.2.2. Build Parameters.".format(fingerprint))
self._partition_fingerprints = {}
for partition in PARTITIONS_WITH_BUILD_PROP:
try:
fingerprint = self.CalculatePartitionFingerprint(partition)
check_fingerprint(fingerprint)
self._partition_fingerprints[partition] = fingerprint
except ExternalError:
continue
if "system" in self._partition_fingerprints:
# system_other is not included in PARTITIONS_WITH_BUILD_PROP, but does
# need a fingerprint when creating the image.
self._partition_fingerprints[
"system_other"] = self._partition_fingerprints["system"]
# These two should be computed only after setting self._oem_props.
self._device = self.GetOemProperty("ro.product.device")
self._fingerprint = self.CalculateFingerprint()
check_fingerprint(self._fingerprint)
@property
def is_ab(self):
return self._is_ab
@property
def device(self):
return self._device
@property
def fingerprint(self):
return self._fingerprint
@property
def is_vabc(self):
return self.info_dict.get("virtual_ab_compression") == "true"
@property
def is_android_r(self):
system_prop = self.info_dict.get("system.build.prop")
return system_prop and system_prop.GetProp("ro.build.version.release") == "11"
@property
def is_release_key(self):
system_prop = self.info_dict.get("build.prop")
return system_prop and system_prop.GetProp("ro.build.tags") == "release-key"
@property
def vabc_compression_param(self):
return self.get("virtual_ab_compression_method", "")
@property
def vendor_api_level(self):
vendor_prop = self.info_dict.get("vendor.build.prop")
if not vendor_prop:
return -1
props = [
"ro.board.api_level",
"ro.board.first_api_level",
"ro.product.first_api_level",
]
for prop in props:
value = vendor_prop.GetProp(prop)
try:
return int(value)
except:
pass
return -1
@property
def is_vabc_xor(self):
vendor_prop = self.info_dict.get("vendor.build.prop")
vabc_xor_enabled = vendor_prop and \
vendor_prop.GetProp("ro.virtual_ab.compression.xor.enabled") == "true"
return vabc_xor_enabled
@property
def vendor_suppressed_vabc(self):
vendor_prop = self.info_dict.get("vendor.build.prop")
vabc_suppressed = vendor_prop and \
vendor_prop.GetProp("ro.vendor.build.dont_use_vabc")
return vabc_suppressed and vabc_suppressed.lower() == "true"
@property
def oem_props(self):
return self._oem_props
def __getitem__(self, key):
return self.info_dict[key]
def __setitem__(self, key, value):
self.info_dict[key] = value
def get(self, key, default=None):
return self.info_dict.get(key, default)
def items(self):
return self.info_dict.items()
def _GetRawBuildProp(self, prop, partition):
prop_file = '{}.build.prop'.format(
partition) if partition else 'build.prop'
partition_props = self.info_dict.get(prop_file)
if not partition_props:
return None
return partition_props.GetProp(prop)
def GetPartitionBuildProp(self, prop, partition):
"""Returns the inquired build property for the provided partition."""
# Boot image and init_boot image uses ro.[product.]bootimage instead of boot.
# This comes from the generic ramdisk
prop_partition = "bootimage" if partition == "boot" or partition == "init_boot" else partition
# If provided a partition for this property, only look within that
# partition's build.prop.
if prop in BuildInfo._RO_PRODUCT_RESOLVE_PROPS:
prop = prop.replace("ro.product", "ro.product.{}".format(prop_partition))
else:
prop = prop.replace("ro.", "ro.{}.".format(prop_partition))
prop_val = self._GetRawBuildProp(prop, partition)
if prop_val is not None:
return prop_val
raise ExternalError("couldn't find %s in %s.build.prop" %
(prop, partition))
def GetBuildProp(self, prop):
"""Returns the inquired build property from the standard build.prop file."""
if prop in BuildInfo._RO_PRODUCT_RESOLVE_PROPS:
return self._ResolveRoProductBuildProp(prop)
if prop == "ro.build.id":
return self._GetBuildId()
prop_val = self._GetRawBuildProp(prop, None)
if prop_val is not None:
return prop_val
raise ExternalError("couldn't find %s in build.prop" % (prop,))
def _ResolveRoProductBuildProp(self, prop):
"""Resolves the inquired ro.product.* build property"""
prop_val = self._GetRawBuildProp(prop, None)
if prop_val:
return prop_val
default_source_order = self._GetRoProductPropsDefaultSourceOrder()
source_order_val = self._GetRawBuildProp(
"ro.product.property_source_order", None)
if source_order_val:
source_order = source_order_val.split(",")
else:
source_order = default_source_order
# Check that all sources in ro.product.property_source_order are valid
if any([x not in default_source_order for x in source_order]):
raise ExternalError(
"Invalid ro.product.property_source_order '{}'".format(source_order))
for source_partition in source_order:
source_prop = prop.replace(
"ro.product", "ro.product.{}".format(source_partition), 1)
prop_val = self._GetRawBuildProp(source_prop, source_partition)
if prop_val:
return prop_val
raise ExternalError("couldn't resolve {}".format(prop))
def _GetRoProductPropsDefaultSourceOrder(self):
# NOTE: refer to CDDs and android.os.Build.VERSION for the definition and
# values of these properties for each Android release.
android_codename = self._GetRawBuildProp("ro.build.version.codename", None)
if android_codename == "REL":
android_version = self._GetRawBuildProp("ro.build.version.release", None)
if android_version == "10":
return BuildInfo._RO_PRODUCT_PROPS_DEFAULT_SOURCE_ORDER_ANDROID_10
# NOTE: float() conversion of android_version will have rounding error.
# We are checking for "9" or less, and using "< 10" is well outside of
# possible floating point rounding.
try:
android_version_val = float(android_version)
except ValueError:
android_version_val = 0
if android_version_val < 10:
return BuildInfo._RO_PRODUCT_PROPS_DEFAULT_SOURCE_ORDER_LEGACY
return BuildInfo._RO_PRODUCT_PROPS_DEFAULT_SOURCE_ORDER_CURRENT
def _GetPlatformVersion(self):
version_sdk = self.GetBuildProp("ro.build.version.sdk")
# init code switches to version_release_or_codename (see b/158483506). After
# API finalization, release_or_codename will be the same as release. This
# is the best effort to support pre-S dev stage builds.
if int(version_sdk) >= 30:
try:
return self.GetBuildProp("ro.build.version.release_or_codename")
except ExternalError:
logger.warning('Failed to find ro.build.version.release_or_codename')
return self.GetBuildProp("ro.build.version.release")
def _GetBuildId(self):
build_id = self._GetRawBuildProp("ro.build.id", None)
if build_id:
return build_id
legacy_build_id = self.GetBuildProp("ro.build.legacy.id")
if not legacy_build_id:
raise ExternalError("Couldn't find build id in property file")
if self.use_legacy_id:
return legacy_build_id
# Append the top 8 chars of vbmeta digest to the existing build id. The
# logic needs to match the one in init, so that OTA can deliver correctly.
avb_enable = self.info_dict.get("avb_enable") == "true"
if not avb_enable:
raise ExternalError("AVB isn't enabled when using legacy build id")
vbmeta_digest = self.info_dict.get("vbmeta_digest")
if not vbmeta_digest:
raise ExternalError("Vbmeta digest isn't provided when using legacy build"
" id")
if len(vbmeta_digest) < self._VBMETA_DIGEST_SIZE_USED:
raise ExternalError("Invalid vbmeta digest " + vbmeta_digest)
digest_prefix = vbmeta_digest[:self._VBMETA_DIGEST_SIZE_USED]
return legacy_build_id + '.' + digest_prefix
def _GetPartitionPlatformVersion(self, partition):
try:
return self.GetPartitionBuildProp("ro.build.version.release_or_codename",
partition)
except ExternalError:
return self.GetPartitionBuildProp("ro.build.version.release",
partition)
def GetOemProperty(self, key):
if self.oem_props is not None and key in self.oem_props:
return self.oem_dicts[0][key]
return self.GetBuildProp(key)
def GetPartitionFingerprint(self, partition):
return self._partition_fingerprints.get(partition, None)
def CalculatePartitionFingerprint(self, partition):
try:
return self.GetPartitionBuildProp("ro.build.fingerprint", partition)
except ExternalError:
return "{}/{}/{}:{}/{}/{}:{}/{}".format(
self.GetPartitionBuildProp("ro.product.brand", partition),
self.GetPartitionBuildProp("ro.product.name", partition),
self.GetPartitionBuildProp("ro.product.device", partition),
self._GetPartitionPlatformVersion(partition),
self.GetPartitionBuildProp("ro.build.id", partition),
self.GetPartitionBuildProp(
"ro.build.version.incremental", partition),
self.GetPartitionBuildProp("ro.build.type", partition),
self.GetPartitionBuildProp("ro.build.tags", partition))
def CalculateFingerprint(self):
if self.oem_props is None:
try:
return self.GetBuildProp("ro.build.fingerprint")
except ExternalError:
return "{}/{}/{}:{}/{}/{}:{}/{}".format(
self.GetBuildProp("ro.product.brand"),
self.GetBuildProp("ro.product.name"),
self.GetBuildProp("ro.product.device"),
self._GetPlatformVersion(),
self.GetBuildProp("ro.build.id"),
self.GetBuildProp("ro.build.version.incremental"),
self.GetBuildProp("ro.build.type"),
self.GetBuildProp("ro.build.tags"))
return "%s/%s/%s:%s" % (
self.GetOemProperty("ro.product.brand"),
self.GetOemProperty("ro.product.name"),
self.GetOemProperty("ro.product.device"),
self.GetBuildProp("ro.build.thumbprint"))
def WriteMountOemScript(self, script):
assert self.oem_props is not None
recovery_mount_options = self.info_dict.get("recovery_mount_options")
script.Mount("/oem", recovery_mount_options)
def WriteDeviceAssertions(self, script, oem_no_mount):
# Read the property directly if not using OEM properties.
if not self.oem_props:
script.AssertDevice(self.device)
return
# Otherwise assert OEM properties.
if not self.oem_dicts:
raise ExternalError(
"No OEM file provided to answer expected assertions")
for prop in self.oem_props.split():
values = []
for oem_dict in self.oem_dicts:
if prop in oem_dict:
values.append(oem_dict[prop])
if not values:
raise ExternalError(
"The OEM file is missing the property %s" % (prop,))
script.AssertOemProperty(prop, values, oem_no_mount)
def DoesInputFileContain(input_file, fn):
"""Check whether the input target_files.zip contain an entry `fn`"""
if isinstance(input_file, zipfile.ZipFile):
return fn in input_file.namelist()
elif zipfile.is_zipfile(input_file):
with zipfile.ZipFile(input_file, "r", allowZip64=True) as zfp:
return fn in zfp.namelist()
else:
if not os.path.isdir(input_file):
raise ValueError(
"Invalid input_file, accepted inputs are ZipFile object, path to .zip file on disk, or path to extracted directory. Actual: " + input_file)
path = os.path.join(input_file, *fn.split("/"))
return os.path.exists(path)
def ReadBytesFromInputFile(input_file, fn):
"""Reads the bytes of fn from input zipfile or directory."""
if isinstance(input_file, zipfile.ZipFile):
return input_file.read(fn)
elif zipfile.is_zipfile(input_file):
with zipfile.ZipFile(input_file, "r", allowZip64=True) as zfp:
return zfp.read(fn)
else:
if not os.path.isdir(input_file):
raise ValueError(
"Invalid input_file, accepted inputs are ZipFile object, path to .zip file on disk, or path to extracted directory. Actual: " + input_file)
path = os.path.join(input_file, *fn.split("/"))
try:
with open(path, "rb") as f:
return f.read()
except IOError as e:
if e.errno == errno.ENOENT:
raise KeyError(fn)
def ReadFromInputFile(input_file, fn):
"""Reads the str contents of fn from input zipfile or directory."""
return ReadBytesFromInputFile(input_file, fn).decode()
def WriteBytesToInputFile(input_file, fn, data):
"""Write bytes |data| contents to fn of input zipfile or directory."""
if isinstance(input_file, zipfile.ZipFile):
with input_file.open(fn, "w") as entry_fp:
return entry_fp.write(data)
elif zipfile.is_zipfile(input_file):
with zipfile.ZipFile(input_file, "r", allowZip64=True) as zfp:
with zfp.open(fn, "w") as entry_fp:
return entry_fp.write(data)
else:
if not os.path.isdir(input_file):
raise ValueError(
"Invalid input_file, accepted inputs are ZipFile object, path to .zip file on disk, or path to extracted directory. Actual: " + input_file)
path = os.path.join(input_file, *fn.split("/"))
try:
with open(path, "wb") as f:
return f.write(data)
except IOError as e:
if e.errno == errno.ENOENT:
raise KeyError(fn)
def WriteToInputFile(input_file, fn, str: str):
"""Write str content to fn of input file or directory"""
return WriteBytesToInputFile(input_file, fn, str.encode())
def ExtractFromInputFile(input_file, fn):
"""Extracts the contents of fn from input zipfile or directory into a file."""
if isinstance(input_file, zipfile.ZipFile):
tmp_file = MakeTempFile(os.path.basename(fn))
with open(tmp_file, 'wb') as f:
f.write(input_file.read(fn))
return tmp_file
elif zipfile.is_zipfile(input_file):
with zipfile.ZipFile(input_file, "r", allowZip64=True) as zfp:
tmp_file = MakeTempFile(os.path.basename(fn))
with open(tmp_file, "wb") as fp:
fp.write(zfp.read(fn))
return tmp_file
else:
if not os.path.isdir(input_file):
raise ValueError(
"Invalid input_file, accepted inputs are ZipFile object, path to .zip file on disk, or path to extracted directory. Actual: " + input_file)
file = os.path.join(input_file, *fn.split("/"))
if not os.path.exists(file):
raise KeyError(fn)
return file
class RamdiskFormat(object):
LZ4 = 1
GZ = 2
def GetRamdiskFormat(info_dict):
if info_dict.get('lz4_ramdisks') == 'true':
ramdisk_format = RamdiskFormat.LZ4
else:
ramdisk_format = RamdiskFormat.GZ
return ramdisk_format
def LoadInfoDict(input_file, repacking=False):
"""Loads the key/value pairs from the given input target_files.
It reads `META/misc_info.txt` file in the target_files input, does validation
checks and returns the parsed key/value pairs for to the given build. It's
usually called early when working on input target_files files, e.g. when
generating OTAs, or signing builds. Note that the function may be called
against an old target_files file (i.e. from past dessert releases). So the
property parsing needs to be backward compatible.
In a `META/misc_info.txt`, a few properties are stored as links to the files
in the PRODUCT_OUT directory. It works fine with the build system. However,
they are no longer available when (re)generating images from target_files zip.
When `repacking` is True, redirect these properties to the actual files in the
unzipped directory.
Args:
input_file: The input target_files file, which could be an open
zipfile.ZipFile instance, or a str for the dir that contains the files
unzipped from a target_files file.
repacking: Whether it's trying repack an target_files file after loading the
info dict (default: False). If so, it will rewrite a few loaded
properties (e.g. selinux_fc, root_dir) to point to the actual files in
target_files file. When doing repacking, `input_file` must be a dir.
Returns:
A dict that contains the parsed key/value pairs.
Raises:
AssertionError: On invalid input arguments.
ValueError: On malformed input values.
"""
if repacking:
assert isinstance(input_file, str), \
"input_file must be a path str when doing repacking"
def read_helper(fn):
return ReadFromInputFile(input_file, fn)
try:
d = LoadDictionaryFromLines(read_helper("META/misc_info.txt").split("\n"))
except KeyError:
raise ValueError("Failed to find META/misc_info.txt in input target-files")
if "recovery_api_version" not in d:
raise ValueError("Failed to find 'recovery_api_version'")
if "fstab_version" not in d:
raise ValueError("Failed to find 'fstab_version'")
if repacking:
# "selinux_fc" properties should point to the file_contexts files
# (file_contexts.bin) under META/.
for key in d:
if key.endswith("selinux_fc"):
fc_basename = os.path.basename(d[key])
fc_config = os.path.join(input_file, "META", fc_basename)
assert os.path.exists(fc_config)
d[key] = fc_config
# Similarly we need to redirect "root_dir", and "root_fs_config".
d["root_dir"] = os.path.join(input_file, "ROOT")
d["root_fs_config"] = os.path.join(
input_file, "META", "root_filesystem_config.txt")
# Redirect {partition}_base_fs_file for each of the named partitions.
for part_name in ["system", "vendor", "system_ext", "product", "odm",
"vendor_dlkm", "odm_dlkm", "system_dlkm"]:
key_name = part_name + "_base_fs_file"
if key_name not in d:
continue
basename = os.path.basename(d[key_name])
base_fs_file = os.path.join(input_file, "META", basename)
if os.path.exists(base_fs_file):
d[key_name] = base_fs_file
else:
logger.warning(
"Failed to find %s base fs file: %s", part_name, base_fs_file)
del d[key_name]
def makeint(key):
if key in d:
d[key] = int(d[key], 0)
makeint("recovery_api_version")
makeint("blocksize")
makeint("system_size")
makeint("vendor_size")
makeint("userdata_size")
makeint("cache_size")
makeint("recovery_size")
makeint("fstab_version")
boot_images = "boot.img"
if "boot_images" in d:
boot_images = d["boot_images"]
for b in boot_images.split():
makeint(b.replace(".img", "_size"))
# Load recovery fstab if applicable.
d["fstab"] = _FindAndLoadRecoveryFstab(d, input_file, read_helper)
ramdisk_format = GetRamdiskFormat(d)
# Tries to load the build props for all partitions with care_map, including
# system and vendor.
for partition in PARTITIONS_WITH_BUILD_PROP:
partition_prop = "{}.build.prop".format(partition)
d[partition_prop] = PartitionBuildProps.FromInputFile(
input_file, partition, ramdisk_format=ramdisk_format)
d["build.prop"] = d["system.build.prop"]
if d.get("avb_enable") == "true":
# Set the vbmeta digest if exists
try:
d["vbmeta_digest"] = read_helper("META/vbmeta_digest.txt").rstrip()
except KeyError:
pass
try:
d["ab_partitions"] = read_helper("META/ab_partitions.txt").split("\n")
except KeyError:
logger.warning("Can't find META/ab_partitions.txt")
return d
def LoadListFromFile(file_path):
with open(file_path) as f:
return f.read().splitlines()
def LoadDictionaryFromFile(file_path):
lines = LoadListFromFile(file_path)
return LoadDictionaryFromLines(lines)
def LoadDictionaryFromLines(lines):
d = {}
for line in lines:
line = line.strip()
if not line or line.startswith("#"):
continue
if "=" in line:
name, value = line.split("=", 1)
d[name] = value
return d
class PartitionBuildProps(object):
"""The class holds the build prop of a particular partition.
This class loads the build.prop and holds the build properties for a given
partition. It also partially recognizes the 'import' statement in the
build.prop; and calculates alternative values of some specific build
properties during runtime.
Attributes:
input_file: a zipped target-file or an unzipped target-file directory.
partition: name of the partition.
props_allow_override: a list of build properties to search for the
alternative values during runtime.
build_props: a dict of build properties for the given partition.
prop_overrides: a set of props that are overridden by import.
placeholder_values: A dict of runtime variables' values to replace the
placeholders in the build.prop file. We expect exactly one value for