blob: bf1fc98441304c224c57eec2b7fc228210b3f3fb [file] [log] [blame]
Kelvin Zhang576efc52020-12-01 12:06:40 -05001#
2# Copyright (C) 2020 The Android Open Source Project
3#
4# Licensed under the Apache License, Version 2.0 (the "License");
5# you may not use this file except in compliance with the License.
6# You may obtain a copy of the License at
7#
8# http://www.apache.org/licenses/LICENSE-2.0
9#
10# Unless required by applicable law or agreed to in writing, software
11# distributed under the License is distributed on an "AS IS" BASIS,
12# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13# See the License for the specific language governing permissions and
14# limitations under the License.
15#
16
17"""Tools for running host side simulation of an OTA update."""
18
19
20from __future__ import print_function
21
22import argparse
23import filecmp
24import os
25import shutil
26import subprocess
27import sys
28import tempfile
29import zipfile
30
31import update_payload
32
33
34def extract_file(zip_file_path, entry_name, target_file_path):
35 """Extract a file from zip archive into |target_file_path|"""
36 with open(target_file_path, 'wb') as out_fp:
37 if isinstance(zip_file_path, zipfile.ZipFile):
38 with zip_file_path.open(entry_name) as fp:
39 shutil.copyfileobj(fp, out_fp)
40 elif os.path.isdir(zip_file_path):
41 with open(os.path.join(zip_file_path, entry_name), "rb") as fp:
42 shutil.copyfileobj(fp, out_fp)
43
Kelvin Zhang8c856552021-09-07 21:15:49 -070044
Kelvin Zhang576efc52020-12-01 12:06:40 -050045def is_sparse_image(filepath):
46 with open(filepath, 'rb') as fp:
47 # Magic for android sparse image format
48 # https://source.android.com/devices/bootloader/images
49 return fp.read(4) == b'\x3A\xFF\x26\xED'
50
Kelvin Zhang8c856552021-09-07 21:15:49 -070051
Kelvin Zhang5ebe2962021-09-24 14:13:28 -070052def extract_img(zip_archive: zipfile.ZipFile, img_name, output_path):
Kelvin Zhang576efc52020-12-01 12:06:40 -050053 entry_name = "IMAGES/" + img_name + ".img"
Kelvin Zhang5ebe2962021-09-24 14:13:28 -070054 try:
55 extract_file(zip_archive, entry_name, output_path)
56 except (KeyError, FileNotFoundError) as e:
57 print("Faild to extract", img_name, "from IMAGES/ dir, trying RADIO/", e)
58 extract_file(zip_archive, "RADIO/" + img_name + ".img", output_path)
Kelvin Zhang576efc52020-12-01 12:06:40 -050059 if is_sparse_image(output_path):
60 raw_img_path = output_path + ".raw"
61 subprocess.check_output(["simg2img", output_path, raw_img_path])
62 os.rename(raw_img_path, output_path)
63
Kelvin Zhang8c856552021-09-07 21:15:49 -070064
65def run_ota(source, target, payload_path, tempdir, output_dir):
Kelvin Zhang576efc52020-12-01 12:06:40 -050066 """Run an OTA on host side"""
67 payload = update_payload.Payload(payload_path)
68 payload.Init()
Kelvin Zhang8c856552021-09-07 21:15:49 -070069 if source and zipfile.is_zipfile(source):
Kelvin Zhang576efc52020-12-01 12:06:40 -050070 source = zipfile.ZipFile(source)
Kelvin Zhang8c856552021-09-07 21:15:49 -070071 if target and zipfile.is_zipfile(target):
Kelvin Zhang576efc52020-12-01 12:06:40 -050072 target = zipfile.ZipFile(target)
Kelvin Zhang8c856552021-09-07 21:15:49 -070073 source_exist = source and (isinstance(
74 source, zipfile.ZipFile) or os.path.exists(source))
75 target_exist = target and (isinstance(
76 target, zipfile.ZipFile) or os.path.exists(target))
Kelvin Zhang576efc52020-12-01 12:06:40 -050077
78 old_partitions = []
79 new_partitions = []
80 expected_new_partitions = []
81 for part in payload.manifest.partitions:
82 name = part.partition_name
83 old_image = os.path.join(tempdir, "source_" + name + ".img")
84 new_image = os.path.join(tempdir, "target_" + name + ".img")
Kelvin Zhang8c856552021-09-07 21:15:49 -070085 if part.HasField("old_partition_info"):
86 assert source_exist, \
87 "source target file must point to a valid zipfile or directory " + \
88 source
89 print("Extracting source image for", name)
90 extract_img(source, name, old_image)
91 if target_exist:
92 print("Extracting target image for", name)
93 extract_img(target, name, new_image)
Kelvin Zhang576efc52020-12-01 12:06:40 -050094
95 old_partitions.append(old_image)
96 scratch_image_name = new_image + ".actual"
97 new_partitions.append(scratch_image_name)
98 with open(scratch_image_name, "wb") as fp:
99 fp.truncate(part.new_partition_info.size)
100 expected_new_partitions.append(new_image)
101
102 delta_generator_args = ["delta_generator", "--in_file=" + payload_path]
103 partition_names = [
104 part.partition_name for part in payload.manifest.partitions
105 ]
Kelvin Zhang5ebe2962021-09-24 14:13:28 -0700106 if payload.manifest.partial_update:
Kelvin Zhang8c856552021-09-07 21:15:49 -0700107 delta_generator_args.append("--is_partial_update")
108 if payload.is_incremental:
109 delta_generator_args.append("--old_partitions=" + ":".join(old_partitions))
Kelvin Zhang576efc52020-12-01 12:06:40 -0500110 delta_generator_args.append("--partition_names=" + ":".join(partition_names))
Kelvin Zhang576efc52020-12-01 12:06:40 -0500111 delta_generator_args.append("--new_partitions=" + ":".join(new_partitions))
112
Kelvin Zhang596a3202022-03-07 14:13:42 -0800113 print("Running ", " ".join(delta_generator_args))
Kelvin Zhang576efc52020-12-01 12:06:40 -0500114 subprocess.check_output(delta_generator_args)
115
116 valid = True
Kelvin Zhang8c856552021-09-07 21:15:49 -0700117 if not target_exist:
118 for part in new_partitions:
119 print("Output written to", part)
120 shutil.copy(part, output_dir)
121 return
Kelvin Zhang576efc52020-12-01 12:06:40 -0500122 for (expected_part, actual_part, part_name) in \
Kelvin Zhang8c856552021-09-07 21:15:49 -0700123 zip(expected_new_partitions, new_partitions, partition_names):
Kelvin Zhang576efc52020-12-01 12:06:40 -0500124 if filecmp.cmp(expected_part, actual_part):
125 print("Partition `{}` is valid".format(part_name))
126 else:
127 valid = False
128 print(
129 "Partition `{}` is INVALID expected image: {} actual image: {}"
130 .format(part_name, expected_part, actual_part))
131
132 if not valid and sys.stdout.isatty():
133 input("Paused to investigate invalid partitions, press any key to exit.")
134
135
136def main():
137 parser = argparse.ArgumentParser(
138 description="Run host side simulation of OTA package")
139 parser.add_argument(
140 "--source",
141 help="Target file zip for the source build",
Kelvin Zhang8c856552021-09-07 21:15:49 -0700142 required=False)
Kelvin Zhang576efc52020-12-01 12:06:40 -0500143 parser.add_argument(
144 "--target",
145 help="Target file zip for the target build",
Kelvin Zhang8c856552021-09-07 21:15:49 -0700146 required=False)
147 parser.add_argument(
148 "-o",
149 dest="output_dir",
150 help="Output directory to put all images, current directory by default"
151 )
Kelvin Zhang576efc52020-12-01 12:06:40 -0500152 parser.add_argument(
153 "payload",
154 help="payload.bin for the OTA package, or a zip of OTA package itself",
155 nargs=1)
156 args = parser.parse_args()
157 print(args)
158
Kelvin Zhang576efc52020-12-01 12:06:40 -0500159 # pylint: disable=no-member
160 with tempfile.TemporaryDirectory() as tempdir:
161 payload_path = args.payload[0]
162 if zipfile.is_zipfile(payload_path):
163 with zipfile.ZipFile(payload_path, "r") as zfp:
164 payload_entry_name = 'payload.bin'
165 zfp.extract(payload_entry_name, tempdir)
166 payload_path = os.path.join(tempdir, payload_entry_name)
Kelvin Zhang8c856552021-09-07 21:15:49 -0700167 if args.output_dir is None:
168 args.output_dir = "."
169 if not os.path.exists(args.output_dir):
170 os.makedirs(args.output_dir, exist_ok=True)
171 assert os.path.isdir(args.output_dir)
172 run_ota(args.source, args.target, payload_path, tempdir, args.output_dir)
Kelvin Zhang576efc52020-12-01 12:06:40 -0500173
174
175if __name__ == '__main__':
176 main()