-
Notifications
You must be signed in to change notification settings - Fork 0
/
ota_amlogic.py
2022 lines (1643 loc) · 75.6 KB
/
ota_amlogic.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/env python
#
# 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.
"""
Given a target-files zipfile, produces an OTA package that installs
that build. An incremental OTA is produced if -i is given, otherwise
a full OTA is produced.
Usage: ota_from_target_files [flags] input_target_files output_ota_package
-k (--package_key) <key> Key to use to sign the package (default is
the value of default_system_dev_certificate from the input
target-files's META/misc_info.txt, or
"build/target/product/security/testkey" if that value is not
specified).
For incremental OTAs, the default value is based on the source
target-file, not the target build.
-i (--incremental_from) <file>
Generate an incremental OTA using the given target-files zip as
the starting build.
--full_radio
When generating an incremental OTA, always include a full copy of
radio image. This option is only meaningful when -i is specified,
because a full radio is always included in a full OTA if applicable.
--full_bootloader
Similar to --full_radio. When generating an incremental OTA, always
include a full copy of bootloader image.
--verify
Remount and verify the checksums of the files written to the system and
vendor (if used) partitions. Non-A/B incremental OTAs only.
-o (--oem_settings) <main_file[,additional_files...]>
Comma seperated list of files used to specify the expected OEM-specific
properties on the OEM partition of the intended device. Multiple expected
values can be used by providing multiple files. Only the first dict will
be used to compute fingerprint, while the rest will be used to assert
OEM-specific properties.
--oem_no_mount
For devices with OEM-specific properties but without an OEM partition,
do not mount the OEM partition in the updater-script. This should be
very rarely used, since it's expected to have a dedicated OEM partition
for OEM-specific properties. Only meaningful when -o is specified.
--wipe_user_data
Generate an OTA package that will wipe the user data partition
when installed.
--downgrade
Intentionally generate an incremental OTA that updates from a newer build
to an older one (e.g. downgrading from P preview back to O MR1).
"ota-downgrade=yes" will be set in the package metadata file. A data wipe
will always be enforced when using this flag, so "ota-wipe=yes" will also
be included in the metadata file. The update-binary in the source build
will be used in the OTA package, unless --binary flag is specified. Please
also check the comment for --override_timestamp below.
--override_timestamp
Intentionally generate an incremental OTA that updates from a newer build
to an older one (based on timestamp comparison), by setting the downgrade
flag in the package metadata. This differs from --downgrade flag, as we
don't enforce a data wipe with this flag. Because we know for sure this is
NOT an actual downgrade case, but two builds happen to be cut in a reverse
order (e.g. from two branches). A legit use case is that we cut a new
build C (after having A and B), but want to enfore an update path of A ->
C -> B. Specifying --downgrade may not help since that would enforce a
data wipe for C -> B update.
We used to set a fake timestamp in the package metadata for this flow. But
now we consolidate the two cases (i.e. an actual downgrade, or a downgrade
based on timestamp) with the same "ota-downgrade=yes" flag, with the
difference being whether "ota-wipe=yes" is set.
-e (--extra_script) <file>
Insert the contents of file at the end of the update script.
-2 (--two_step)
Generate a 'two-step' OTA package, where recovery is updated
first, so that any changes made to the system partition are done
using the new recovery (new kernel, etc.).
--include_secondary
Additionally include the payload for secondary slot images (default:
False). Only meaningful when generating A/B OTAs.
By default, an A/B OTA package doesn't contain the images for the
secondary slot (e.g. system_other.img). Specifying this flag allows
generating a separate payload that will install secondary slot images.
Such a package needs to be applied in a two-stage manner, with a reboot
in-between. During the first stage, the updater applies the primary
payload only. Upon finishing, it reboots the device into the newly updated
slot. It then continues to install the secondary payload to the inactive
slot, but without switching the active slot at the end (needs the matching
support in update_engine, i.e. SWITCH_SLOT_ON_REBOOT flag).
Due to the special install procedure, the secondary payload will be always
generated as a full payload.
--block
Generate a block-based OTA for non-A/B device. We have deprecated the
support for file-based OTA since O. Block-based OTA will be used by
default for all non-A/B devices. Keeping this flag here to not break
existing callers.
-b (--binary) <file>
Use the given binary as the update-binary in the output package,
instead of the binary in the build's target_files. Use for
development only.
-t (--worker_threads) <int>
Specifies the number of worker-threads that will be used when
generating patches for incremental updates (defaults to 3).
--stash_threshold <float>
Specifies the threshold that will be used to compute the maximum
allowed stash size (defaults to 0.8).
--log_diff <file>
Generate a log file that shows the differences in the source and target
builds for an incremental package. This option is only meaningful when
-i is specified.
--payload_signer <signer>
Specify the signer when signing the payload and metadata for A/B OTAs.
By default (i.e. without this flag), it calls 'openssl pkeyutl' to sign
with the package private key. If the private key cannot be accessed
directly, a payload signer that knows how to do that should be specified.
The signer will be supplied with "-inkey <path_to_key>",
"-in <input_file>" and "-out <output_file>" parameters.
--payload_signer_args <args>
Specify the arguments needed for payload signer.
--skip_postinstall
Skip the postinstall hooks when generating an A/B OTA package (default:
False). Note that this discards ALL the hooks, including non-optional
ones. Should only be used if caller knows it's safe to do so (e.g. all the
postinstall work is to dexopt apps and a data wipe will happen immediately
after). Only meaningful when generating A/B OTAs.
"""
from __future__ import print_function
import multiprocessing
import os.path
import shlex
import shutil
import struct
import subprocess
import sys
import tempfile
import zipfile
import sys
sys.path.append('build/tools/releasetools')
import common
import edify_generator
import sparse_img
if sys.hexversion < 0x02070000:
print("Python 2.7 or newer is required.", file=sys.stderr)
sys.exit(1)
OPTIONS = common.OPTIONS
OPTIONS.package_key = None
OPTIONS.incremental_source = None
OPTIONS.verify = False
OPTIONS.patch_threshold = 0.95
OPTIONS.wipe_user_data = False
OPTIONS.downgrade = False
OPTIONS.extra_script = None
OPTIONS.worker_threads = multiprocessing.cpu_count() // 2
if OPTIONS.worker_threads == 0:
OPTIONS.worker_threads = 1
OPTIONS.two_step = False
OPTIONS.include_secondary = False
OPTIONS.no_signing = False
OPTIONS.block_based = True
OPTIONS.updater_binary = None
OPTIONS.oem_source = None
OPTIONS.oem_no_mount = False
OPTIONS.full_radio = False
OPTIONS.full_bootloader = False
# Stash size cannot exceed cache_size * threshold.
OPTIONS.cache_size = None
OPTIONS.stash_threshold = 0.8
OPTIONS.log_diff = None
OPTIONS.payload_signer = None
OPTIONS.payload_signer_args = []
OPTIONS.extracted_input = None
OPTIONS.key_passwords = []
OPTIONS.skip_postinstall = False
METADATA_NAME = 'META-INF/com/android/metadata'
POSTINSTALL_CONFIG = 'META/postinstall_config.txt'
UNZIP_PATTERN = ['IMAGES/*', 'META/*']
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 GetVendorBuildProp().
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.
"""
def __init__(self, info_dict, oem_dicts):
"""Initializes a BuildInfo instance with the given dicts.
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).
"""
self.info_dict = info_dict
self.oem_dicts = oem_dicts
self._is_ab = info_dict.get("ab_update") == "true"
self._oem_props = info_dict.get("oem_fingerprint_properties")
if self._oem_props:
assert oem_dicts, "OEM source required for this build"
# These two should be computed only after setting self._oem_props.
self._device = self.GetOemProperty("ro.product.device")
self._fingerprint = self.CalculateFingerprint()
@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 oem_props(self):
return self._oem_props
def __getitem__(self, key):
return self.info_dict[key]
def get(self, key, default=None):
return self.info_dict.get(key, default)
def GetBuildProp(self, prop):
"""Returns the inquired build property."""
try:
return self.info_dict.get("build.prop", {})[prop]
except KeyError:
raise common.ExternalError("couldn't find %s in build.prop" % (prop,))
def GetVendorBuildProp(self, prop):
"""Returns the inquired vendor build property."""
try:
return self.info_dict.get("vendor.build.prop", {})[prop]
except KeyError:
raise common.ExternalError(
"couldn't find %s in vendor.build.prop" % (prop,))
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 CalculateFingerprint(self):
if self.oem_props is None:
return self.GetBuildProp("ro.build.fingerprint")
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 common.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 common.ExternalError(
"The OEM file is missing the property %s" % (prop,))
script.AssertOemProperty(prop, values, oem_no_mount)
class PayloadSigner(object):
"""A class that wraps the payload signing works.
When generating a Payload, hashes of the payload and metadata files will be
signed with the device key, either by calling an external payload signer or
by calling openssl with the package key. This class provides a unified
interface, so that callers can just call PayloadSigner.Sign().
If an external payload signer has been specified (OPTIONS.payload_signer), it
calls the signer with the provided args (OPTIONS.payload_signer_args). Note
that the signing key should be provided as part of the payload_signer_args.
Otherwise without an external signer, it uses the package key
(OPTIONS.package_key) and calls openssl for the signing works.
"""
def __init__(self):
if OPTIONS.payload_signer is None:
# Prepare the payload signing key.
private_key = OPTIONS.package_key + OPTIONS.private_key_suffix
pw = OPTIONS.key_passwords[OPTIONS.package_key]
cmd = ["openssl", "pkcs8", "-in", private_key, "-inform", "DER"]
cmd.extend(["-passin", "pass:" + pw] if pw else ["-nocrypt"])
signing_key = common.MakeTempFile(prefix="key-", suffix=".key")
cmd.extend(["-out", signing_key])
get_signing_key = common.Run(cmd, verbose=False, stdout=subprocess.PIPE,
stderr=subprocess.STDOUT)
stdoutdata, _ = get_signing_key.communicate()
assert get_signing_key.returncode == 0, \
"Failed to get signing key: {}".format(stdoutdata)
self.signer = "openssl"
self.signer_args = ["pkeyutl", "-sign", "-inkey", signing_key,
"-pkeyopt", "digest:sha256"]
else:
self.signer = OPTIONS.payload_signer
self.signer_args = OPTIONS.payload_signer_args
def Sign(self, in_file):
"""Signs the given input file. Returns the output filename."""
out_file = common.MakeTempFile(prefix="signed-", suffix=".bin")
cmd = [self.signer] + self.signer_args + ['-in', in_file, '-out', out_file]
signing = common.Run(cmd, stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
stdoutdata, _ = signing.communicate()
assert signing.returncode == 0, \
"Failed to sign the input file: {}".format(stdoutdata)
return out_file
class Payload(object):
"""Manages the creation and the signing of an A/B OTA Payload."""
PAYLOAD_BIN = 'payload.bin'
PAYLOAD_PROPERTIES_TXT = 'payload_properties.txt'
SECONDARY_PAYLOAD_BIN = 'secondary/payload.bin'
SECONDARY_PAYLOAD_PROPERTIES_TXT = 'secondary/payload_properties.txt'
def __init__(self, secondary=False):
"""Initializes a Payload instance.
Args:
secondary: Whether it's generating a secondary payload (default: False).
"""
# The place where the output from the subprocess should go.
self._log_file = sys.stdout if OPTIONS.verbose else subprocess.PIPE
self.payload_file = None
self.payload_properties = None
self.secondary = secondary
def Generate(self, target_file, source_file=None, additional_args=None):
"""Generates a payload from the given target-files zip(s).
Args:
target_file: The filename of the target build target-files zip.
source_file: The filename of the source build target-files zip; or None if
generating a full OTA.
additional_args: A list of additional args that should be passed to
brillo_update_payload script; or None.
"""
if additional_args is None:
additional_args = []
payload_file = common.MakeTempFile(prefix="payload-", suffix=".bin")
cmd = ["brillo_update_payload", "generate",
"--payload", payload_file,
"--target_image", target_file]
if source_file is not None:
cmd.extend(["--source_image", source_file])
cmd.extend(additional_args)
p = common.Run(cmd, stdout=self._log_file, stderr=subprocess.STDOUT)
stdoutdata, _ = p.communicate()
assert p.returncode == 0, \
"brillo_update_payload generate failed: {}".format(stdoutdata)
self.payload_file = payload_file
self.payload_properties = None
def Sign(self, payload_signer):
"""Generates and signs the hashes of the payload and metadata.
Args:
payload_signer: A PayloadSigner() instance that serves the signing work.
Raises:
AssertionError: On any failure when calling brillo_update_payload script.
"""
assert isinstance(payload_signer, PayloadSigner)
# 1. Generate hashes of the payload and metadata files.
payload_sig_file = common.MakeTempFile(prefix="sig-", suffix=".bin")
metadata_sig_file = common.MakeTempFile(prefix="sig-", suffix=".bin")
cmd = ["brillo_update_payload", "hash",
"--unsigned_payload", self.payload_file,
"--signature_size", "256",
"--metadata_hash_file", metadata_sig_file,
"--payload_hash_file", payload_sig_file]
p1 = common.Run(cmd, stdout=self._log_file, stderr=subprocess.STDOUT)
p1.communicate()
assert p1.returncode == 0, "brillo_update_payload hash failed"
# 2. Sign the hashes.
signed_payload_sig_file = payload_signer.Sign(payload_sig_file)
signed_metadata_sig_file = payload_signer.Sign(metadata_sig_file)
# 3. Insert the signatures back into the payload file.
signed_payload_file = common.MakeTempFile(prefix="signed-payload-",
suffix=".bin")
cmd = ["brillo_update_payload", "sign",
"--unsigned_payload", self.payload_file,
"--payload", signed_payload_file,
"--signature_size", "256",
"--metadata_signature_file", signed_metadata_sig_file,
"--payload_signature_file", signed_payload_sig_file]
p1 = common.Run(cmd, stdout=self._log_file, stderr=subprocess.STDOUT)
p1.communicate()
assert p1.returncode == 0, "brillo_update_payload sign failed"
# 4. Dump the signed payload properties.
properties_file = common.MakeTempFile(prefix="payload-properties-",
suffix=".txt")
cmd = ["brillo_update_payload", "properties",
"--payload", signed_payload_file,
"--properties_file", properties_file]
p1 = common.Run(cmd, stdout=self._log_file, stderr=subprocess.STDOUT)
p1.communicate()
assert p1.returncode == 0, "brillo_update_payload properties failed"
if self.secondary:
with open(properties_file, "a") as f:
f.write("SWITCH_SLOT_ON_REBOOT=0\n")
if OPTIONS.wipe_user_data:
with open(properties_file, "a") as f:
f.write("POWERWASH=1\n")
self.payload_file = signed_payload_file
self.payload_properties = properties_file
def WriteToZip(self, output_zip):
"""Writes the payload to the given zip.
Args:
output_zip: The output ZipFile instance.
"""
assert self.payload_file is not None
assert self.payload_properties is not None
if self.secondary:
payload_arcname = Payload.SECONDARY_PAYLOAD_BIN
payload_properties_arcname = Payload.SECONDARY_PAYLOAD_PROPERTIES_TXT
else:
payload_arcname = Payload.PAYLOAD_BIN
payload_properties_arcname = Payload.PAYLOAD_PROPERTIES_TXT
# Add the signed payload file and properties into the zip. In order to
# support streaming, we pack them as ZIP_STORED. So these entries can be
# read directly with the offset and length pairs.
common.ZipWrite(output_zip, self.payload_file, arcname=payload_arcname,
compress_type=zipfile.ZIP_STORED)
common.ZipWrite(output_zip, self.payload_properties,
arcname=payload_properties_arcname,
compress_type=zipfile.ZIP_STORED)
def SignOutput(temp_zip_name, output_zip_name):
pw = OPTIONS.key_passwords[OPTIONS.package_key]
common.SignFile(temp_zip_name, output_zip_name, OPTIONS.package_key, pw,
whole_file=True)
def _LoadOemDicts(oem_source):
"""Returns the list of loaded OEM properties dict."""
if not oem_source:
return None
oem_dicts = []
for oem_file in oem_source:
with open(oem_file) as fp:
oem_dicts.append(common.LoadDictionaryFromLines(fp.readlines()))
return oem_dicts
def _WriteRecoveryImageToBoot(script, output_zip):
"""Find and write recovery image to /boot in two-step OTA.
In two-step OTAs, we write recovery image to /boot as the first step so that
we can reboot to there and install a new recovery image to /recovery.
A special "recovery-two-step.img" will be preferred, which encodes the correct
path of "/boot". Otherwise the device may show "device is corrupt" message
when booting into /boot.
Fall back to using the regular recovery.img if the two-step recovery image
doesn't exist. Note that rebuilding the special image at this point may be
infeasible, because we don't have the desired boot signer and keys when
calling ota_from_target_files.py.
"""
recovery_two_step_img_name = "recovery-two-step.img"
recovery_two_step_img_path = os.path.join(
OPTIONS.input_tmp, "IMAGES", recovery_two_step_img_name)
if os.path.exists(recovery_two_step_img_path):
recovery_two_step_img = common.GetBootableImage(
recovery_two_step_img_name, recovery_two_step_img_name,
OPTIONS.input_tmp, "RECOVERY")
common.ZipWriteStr(
output_zip, recovery_two_step_img_name, recovery_two_step_img.data)
print("two-step package: using %s in stage 1/3" % (
recovery_two_step_img_name,))
script.WriteRawImage("/boot", recovery_two_step_img_name)
else:
print("two-step package: using recovery.img in stage 1/3")
# The "recovery.img" entry has been written into package earlier.
script.WriteRawImage("/boot", "recovery.img")
def HasRecoveryPatch(target_files_zip):
namelist = [name for name in target_files_zip.namelist()]
return ("SYSTEM/recovery-from-boot.p" in namelist or
"SYSTEM/etc/recovery.img" in namelist)
def HasVendorPartition(target_files_zip):
try:
target_files_zip.getinfo("VENDOR/")
return True
except KeyError:
return False
def ZipOtherImage(which, tmpdir, output):
"""Returns an image object from IMAGES.
'which' partition eg "logo", "dtb". A prebuilt image and file
map must already exist in tmpdir.
"""
amlogic_img_path = os.path.join(tmpdir, "IMAGES", which + ".img")
if os.path.exists(amlogic_img_path):
f = open(amlogic_img_path, "rb")
data = f.read()
f.close()
common.ZipWriteStr(output, which + ".img", data)
def HasTrebleEnabled(target_files_zip, target_info):
return (HasVendorPartition(target_files_zip) and
target_info.GetBuildProp("ro.treble.enabled") == "true")
def WriteFingerprintAssertion(script, target_info, source_info):
source_oem_props = source_info.oem_props
target_oem_props = target_info.oem_props
if source_oem_props is None and target_oem_props is None:
script.AssertSomeFingerprint(
source_info.fingerprint, target_info.fingerprint)
elif source_oem_props is not None and target_oem_props is not None:
script.AssertSomeThumbprint(
target_info.GetBuildProp("ro.build.thumbprint"),
source_info.GetBuildProp("ro.build.thumbprint"))
elif source_oem_props is None and target_oem_props is not None:
script.AssertFingerprintOrThumbprint(
source_info.fingerprint,
target_info.GetBuildProp("ro.build.thumbprint"))
else:
script.AssertFingerprintOrThumbprint(
target_info.fingerprint,
source_info.GetBuildProp("ro.build.thumbprint"))
def AddCompatibilityArchiveIfTrebleEnabled(target_zip, output_zip, target_info,
source_info=None):
"""Adds compatibility info into the output zip if it's Treble-enabled target.
Metadata used for on-device compatibility verification is retrieved from
target_zip then added to compatibility.zip which is added to the output_zip
archive.
Compatibility archive should only be included for devices that have enabled
Treble support.
Args:
target_zip: Zip file containing the source files to be included for OTA.
output_zip: Zip file that will be sent for OTA.
target_info: The BuildInfo instance that holds the target build info.
source_info: The BuildInfo instance that holds the source build info, if
generating an incremental OTA; None otherwise.
"""
def AddCompatibilityArchive(system_updated, vendor_updated):
"""Adds compatibility info based on system/vendor update status.
Args:
system_updated: If True, the system image will be updated and therefore
its metadata should be included.
vendor_updated: If True, the vendor image will be updated and therefore
its metadata should be included.
"""
# Determine what metadata we need. Files are names relative to META/.
compatibility_files = []
vendor_metadata = ("vendor_manifest.xml", "vendor_matrix.xml")
system_metadata = ("system_manifest.xml", "system_matrix.xml")
if vendor_updated:
compatibility_files += vendor_metadata
if system_updated:
compatibility_files += system_metadata
# Create new archive.
compatibility_archive = tempfile.NamedTemporaryFile()
compatibility_archive_zip = zipfile.ZipFile(
compatibility_archive, "w", compression=zipfile.ZIP_DEFLATED)
# Add metadata.
for file_name in compatibility_files:
target_file_name = "META/" + file_name
if target_file_name in target_zip.namelist():
data = target_zip.read(target_file_name)
common.ZipWriteStr(compatibility_archive_zip, file_name, data)
# Ensure files are written before we copy into output_zip.
compatibility_archive_zip.close()
# Only add the archive if we have any compatibility info.
if compatibility_archive_zip.namelist():
common.ZipWrite(output_zip, compatibility_archive.name,
arcname="compatibility.zip",
compress_type=zipfile.ZIP_STORED)
# Will only proceed if the target has enabled the Treble support (as well as
# having a /vendor partition).
if not HasTrebleEnabled(target_zip, target_info):
return
# We don't support OEM thumbprint in Treble world (which calculates
# fingerprints in a different way as shown in CalculateFingerprint()).
assert not target_info.oem_props
# Full OTA carries the info for system/vendor both.
if source_info is None:
AddCompatibilityArchive(True, True)
return
assert not source_info.oem_props
source_fp = source_info.fingerprint
target_fp = target_info.fingerprint
system_updated = source_fp != target_fp
source_fp_vendor = source_info.GetVendorBuildProp(
"ro.vendor.build.fingerprint")
target_fp_vendor = target_info.GetVendorBuildProp(
"ro.vendor.build.fingerprint")
vendor_updated = source_fp_vendor != target_fp_vendor
AddCompatibilityArchive(system_updated, vendor_updated)
def WriteFullOTAPackage(input_zip, output_file):
target_info = BuildInfo(OPTIONS.info_dict, OPTIONS.oem_dicts)
# We don't know what version it will be installed on top of. We expect the API
# just won't change very often. Similarly for fstab, it might have changed in
# the target build.
target_api_version = target_info["recovery_api_version"]
script = edify_generator.EdifyGenerator(target_api_version, target_info)
if target_info.oem_props and not OPTIONS.oem_no_mount:
target_info.WriteMountOemScript(script)
metadata = GetPackageMetadata(target_info)
if not OPTIONS.no_signing:
staging_file = common.MakeTempFile(suffix='.zip')
else:
staging_file = output_file
output_zip = zipfile.ZipFile(
staging_file, "w", compression=zipfile.ZIP_DEFLATED)
device_specific = common.DeviceSpecificParams(
input_zip=input_zip,
input_version=target_api_version,
output_zip=output_zip,
script=script,
input_tmp=OPTIONS.input_tmp,
metadata=metadata,
info_dict=OPTIONS.info_dict)
#assert HasRecoveryPatch(input_zip)
# Assertions (e.g. downgrade check, device properties check).
ts = target_info.GetBuildProp("ro.build.date.utc")
ts_text = target_info.GetBuildProp("ro.build.date")
script.AssertOlderBuild(ts, ts_text)
target_info.WriteDeviceAssertions(script, OPTIONS.oem_no_mount)
device_specific.FullOTA_Assertions()
# Two-step package strategy (in chronological order, which is *not*
# the order in which the generated script has things):
#
# if stage is not "2/3" or "3/3":
# write recovery image to boot partition
# set stage to "2/3"
# reboot to boot partition and restart recovery
# else if stage is "2/3":
# write recovery image to recovery partition
# set stage to "3/3"
# reboot to recovery partition and restart recovery
# else:
# (stage must be "3/3")
# set stage to ""
# do normal full package installation:
# wipe and install system, boot image, etc.
# set up system to update recovery partition on first boot
# complete script normally
# (allow recovery to mark itself finished and reboot)
recovery_img = common.GetBootableImage("recovery.img", "recovery.img",
OPTIONS.input_tmp, "RECOVERY")
if OPTIONS.two_step:
if not target_info.get("multistage_support"):
assert False, "two-step packages not supported by this build"
fs = target_info["fstab"]["/misc"]
assert fs.fs_type.upper() == "EMMC", \
"two-step packages only supported on devices with EMMC /misc partitions"
bcb_dev = {"bcb_dev": fs.device}
common.ZipWriteStr(output_zip, "recovery.img", recovery_img.data)
script.AppendExtra("""
if get_stage("%(bcb_dev)s") == "2/3" then
""" % bcb_dev)
# Stage 2/3: Write recovery image to /recovery (currently running /boot).
script.Comment("Stage 2/3")
script.WriteRawImage("/recovery", "recovery.img")
script.AppendExtra("""
set_stage("%(bcb_dev)s", "3/3");
reboot_now("%(bcb_dev)s", "recovery");
else if get_stage("%(bcb_dev)s") == "3/3" then
""" % bcb_dev)
# Stage 3/3: Make changes.
script.Comment("Stage 3/3")
# Dump fingerprints
script.Print("Target: {}".format(target_info.fingerprint))
device_specific.FullOTA_InstallBegin()
system_progress = 0.75
if OPTIONS.wipe_user_data:
system_progress -= 0.1
if HasVendorPartition(input_zip):
system_progress -= 0.1
script.ShowProgress(system_progress, 0)
# See the notes in WriteBlockIncrementalOTAPackage().
allow_shared_blocks = target_info.get('ext4_share_dup_blocks') == "true"
# Full OTA is done as an "incremental" against an empty source image. This
# has the effect of writing new data from the package to the entire
# partition, but lets us reuse the updater code that writes incrementals to
# do it.
system_tgt = common.GetSparseImage("system", OPTIONS.input_tmp, input_zip,
allow_shared_blocks)
system_tgt.ResetFileMap()
system_diff = common.BlockDifference("system", system_tgt, src=None)
system_diff.WriteScript(script, output_zip)
boot_img = common.GetBootableImage(
"boot.img", "boot.img", OPTIONS.input_tmp, "BOOT")
if HasVendorPartition(input_zip):
script.ShowProgress(0.1, 0)
vendor_tgt = common.GetSparseImage("vendor", OPTIONS.input_tmp, input_zip,
allow_shared_blocks)
vendor_tgt.ResetFileMap()
vendor_diff = common.BlockDifference("vendor", vendor_tgt)
vendor_diff.WriteScript(script, output_zip)
#AddCompatibilityArchiveIfTrebleEnabled(input_zip, output_zip, target_info)
common.CheckSize(boot_img.data, "boot.img", target_info)
common.ZipWriteStr(output_zip, "boot.img", boot_img.data)
script.ShowProgress(0.05, 5)
script.WriteRawImage("/boot", "boot.img")
ZipOtherImage("bootloader", OPTIONS.input_tmp, output_zip)
script.ShowProgress(0.2, 10)
device_specific.FullOTA_InstallEnd()
script.AppendExtra('ui_print("update bootloader.img...");')
script.AppendExtra('write_bootloader_image(package_extract_file("bootloader.img"));')
if OPTIONS.extra_script is not None:
script.AppendExtra(OPTIONS.extra_script)
script.UnmountAll()
if OPTIONS.wipe_user_data:
script.ShowProgress(0.1, 10)
script.FormatPartition("/data")
if OPTIONS.two_step:
script.AppendExtra("""
set_stage("%(bcb_dev)s", "");
""" % bcb_dev)
script.AppendExtra("else\n")
# Stage 1/3: Nothing to verify for full OTA. Write recovery image to /boot.
script.Comment("Stage 1/3")
_WriteRecoveryImageToBoot(script, output_zip)
script.AppendExtra("""
set_stage("%(bcb_dev)s", "2/3");
reboot_now("%(bcb_dev)s", "");
endif;
endif;
""" % bcb_dev)
script.SetProgress(1)
script.AddToZip(input_zip, output_zip, input_path=OPTIONS.updater_binary)
metadata["ota-required-cache"] = str(script.required_cache)
# We haven't written the metadata entry, which will be done in
# FinalizeMetadata.
common.ZipClose(output_zip)
needed_property_files = (
NonAbOtaPropertyFiles(),
)
FinalizeMetadata(metadata, staging_file, output_file, needed_property_files)
def WriteMetadata(metadata, output_zip):
value = "".join(["%s=%s\n" % kv for kv in sorted(metadata.iteritems())])
common.ZipWriteStr(output_zip, METADATA_NAME, value,
compress_type=zipfile.ZIP_STORED)
def HandleDowngradeMetadata(metadata, target_info, source_info):
# Only incremental OTAs are allowed to reach here.
assert OPTIONS.incremental_source is not None
post_timestamp = target_info.GetBuildProp("ro.build.date.utc")
pre_timestamp = source_info.GetBuildProp("ro.build.date.utc")
is_downgrade = long(post_timestamp) < long(pre_timestamp)
if OPTIONS.downgrade:
if not is_downgrade:
raise RuntimeError(
"--downgrade or --override_timestamp specified but no downgrade "
"detected: pre: %s, post: %s" % (pre_timestamp, post_timestamp))
metadata["ota-downgrade"] = "yes"
else:
if is_downgrade:
raise RuntimeError(
"Downgrade detected based on timestamp check: pre: %s, post: %s. "
"Need to specify --override_timestamp OR --downgrade to allow "
"building the incremental." % (pre_timestamp, post_timestamp))
def GetPackageMetadata(target_info, source_info=None):
"""Generates and returns the metadata dict.
It generates a dict() that contains the info to be written into an OTA
package (META-INF/com/android/metadata). It also handles the detection of
downgrade / data wipe based on the global options.
Args:
target_info: The BuildInfo instance that holds the target build info.
source_info: The BuildInfo instance that holds the source build info, or
None if generating full OTA.
Returns:
A dict to be written into package metadata entry.
"""
assert isinstance(target_info, BuildInfo)
assert source_info is None or isinstance(source_info, BuildInfo)
metadata = {
'post-build' : target_info.fingerprint,
'post-build-incremental' : target_info.GetBuildProp(
'ro.build.version.incremental'),
'post-sdk-level' : target_info.GetBuildProp(
'ro.build.version.sdk'),
'post-security-patch-level' : target_info.GetBuildProp(
'ro.build.version.security_patch'),
}
if target_info.is_ab:
metadata['ota-type'] = 'AB'
metadata['ota-required-cache'] = '0'
else:
metadata['ota-type'] = 'BLOCK'
if OPTIONS.wipe_user_data:
metadata['ota-wipe'] = 'yes'
is_incremental = source_info is not None
if is_incremental:
metadata['pre-build'] = source_info.fingerprint
metadata['pre-build-incremental'] = source_info.GetBuildProp(
'ro.build.version.incremental')
metadata['pre-device'] = source_info.device
else:
metadata['pre-device'] = target_info.device
# Use the actual post-timestamp, even for a downgrade case.
metadata['post-timestamp'] = target_info.GetBuildProp('ro.build.date.utc')
# Detect downgrades and set up downgrade flags accordingly.
if is_incremental:
HandleDowngradeMetadata(metadata, target_info, source_info)
return metadata
class PropertyFiles(object):
"""A class that computes the property-files string for an OTA package.
A property-files string is a comma-separated string that contains the
offset/size info for an OTA package. The entries, which must be ZIP_STORED,
can be fetched directly with the package URL along with the offset/size info.
These strings can be used for streaming A/B OTAs, or allowing an updater to