blob: 240e5c94bbd8f5092197b2ea5a9b84aca45162ec [file] [log] [blame]
Doug Zongker3c84f562014-07-31 11:06:30 -07001#!/usr/bin/env python
2#
3# Copyright (C) 2014 The Android Open Source Project
4#
5# Licensed under the Apache License, Version 2.0 (the "License");
6# you may not use this file except in compliance with the License.
7# You may obtain a copy of the License at
8#
9# http://www.apache.org/licenses/LICENSE-2.0
10#
11# Unless required by applicable law or agreed to in writing, software
12# distributed under the License is distributed on an "AS IS" BASIS,
13# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14# See the License for the specific language governing permissions and
15# limitations under the License.
16
17"""
18Given a target-files zipfile that does not contain images (ie, does
19not have an IMAGES/ top-level subdirectory), produce the images and
20add them to the zipfile.
21
Tianjie Xub48589a2016-08-03 19:21:52 -070022Usage: add_img_to_target_files [flag] target_files
23
24 -a (--add_missing)
25 Build and add missing images to "IMAGES/". If this option is
26 not specified, this script will simply exit when "IMAGES/"
27 directory exists in the target file.
28
29 -r (--rebuild_recovery)
30 Rebuild the recovery patch and write it to the system image. Only
31 meaningful when system image needs to be rebuilt.
32
33 --replace_verity_private_key
34 Replace the private key used for verity signing. (same as the option
35 in sign_target_files_apks)
36
37 --replace_verity_public_key
38 Replace the certificate (public key) used for verity verification. (same
39 as the option in sign_target_files_apks)
40
41 --is_signing
42 Skip building & adding the images for "userdata" and "cache" if we
43 are signing the target files.
Doug Zongker3c84f562014-07-31 11:06:30 -070044"""
45
Tao Bao89fbb0f2017-01-10 10:47:58 -080046from __future__ import print_function
47
Tao Bao822f5842015-09-30 16:01:14 -070048import datetime
Tao Bao2b6dfd62017-09-27 17:17:43 -070049import hashlib
Doug Zongker3c84f562014-07-31 11:06:30 -070050import os
David Zeuthend995f4b2016-01-29 16:59:17 -050051import shlex
Ying Wang2a048392015-06-25 13:56:53 -070052import shutil
David Zeuthend995f4b2016-01-29 16:59:17 -050053import subprocess
Tao Bao6b9fef52017-12-01 16:13:22 -080054import sys
Tao Baod86e3112017-09-22 15:45:33 -070055import uuid
Doug Zongker3c84f562014-07-31 11:06:30 -070056import zipfile
57
Doug Zongker3c84f562014-07-31 11:06:30 -070058import build_image
59import common
Tianjie Xuf1a13182017-01-19 17:39:30 -080060import rangelib
Tianjie Xucfa86222016-03-07 16:31:19 -080061import sparse_img
Doug Zongker3c84f562014-07-31 11:06:30 -070062
Tao Bao6b9fef52017-12-01 16:13:22 -080063if sys.hexversion < 0x02070000:
64 print("Python 2.7 or newer is required.", file=sys.stderr)
65 sys.exit(1)
66
Doug Zongker3c84f562014-07-31 11:06:30 -070067OPTIONS = common.OPTIONS
68
Michael Runge2e0d8fc2014-11-13 21:41:08 -080069OPTIONS.add_missing = False
70OPTIONS.rebuild_recovery = False
Tianjie Xu9ac4cb02017-06-09 16:58:03 -070071OPTIONS.replace_updated_files_list = []
Baligh Uddin59f4ff12015-09-16 21:20:30 -070072OPTIONS.replace_verity_public_key = False
73OPTIONS.replace_verity_private_key = False
Tianjie Xub48589a2016-08-03 19:21:52 -070074OPTIONS.is_signing = False
Doug Zongker3c84f562014-07-31 11:06:30 -070075
Dan Willemsen2ee00d52017-03-05 19:51:56 -080076
Tao Baoa2ff4c92018-01-17 12:14:43 -080077# Partitions that should have their care_map added to META/care_map.txt.
Jaekyun Seokb7735d82017-11-27 17:04:47 +090078PARTITIONS_WITH_CARE_MAP = ('system', 'vendor', 'product')
Tao Baoa2ff4c92018-01-17 12:14:43 -080079
80
Dan Willemsen2ee00d52017-03-05 19:51:56 -080081class OutputFile(object):
82 def __init__(self, output_zip, input_dir, prefix, name):
83 self._output_zip = output_zip
84 self.input_name = os.path.join(input_dir, prefix, name)
85
86 if self._output_zip:
87 self._zip_name = os.path.join(prefix, name)
88
89 root, suffix = os.path.splitext(name)
90 self.name = common.MakeTempFile(prefix=root + '-', suffix=suffix)
91 else:
92 self.name = self.input_name
93
94 def Write(self):
95 if self._output_zip:
96 common.ZipWrite(self._output_zip, self.name, self._zip_name)
97
98
Tianjie Xucfa86222016-03-07 16:31:19 -080099def GetCareMap(which, imgname):
Tao Baoa2ff4c92018-01-17 12:14:43 -0800100 """Generates the care_map for the given partition."""
101 assert which in PARTITIONS_WITH_CARE_MAP
Tianjie Xucfa86222016-03-07 16:31:19 -0800102
103 simg = sparse_img.SparseImage(imgname)
Tianjie Xuf1a13182017-01-19 17:39:30 -0800104 care_map_ranges = simg.care_map
105 key = which + "_adjusted_partition_size"
106 adjusted_blocks = OPTIONS.info_dict.get(key)
107 if adjusted_blocks:
108 assert adjusted_blocks > 0, "blocks should be positive for " + which
109 care_map_ranges = care_map_ranges.intersect(rangelib.RangeSet(
110 "0-%d" % (adjusted_blocks,)))
111
Tao Baoa2ff4c92018-01-17 12:14:43 -0800112 return [which, care_map_ranges.to_string_raw()]
Tianjie Xucfa86222016-03-07 16:31:19 -0800113
114
Michael Runge2e0d8fc2014-11-13 21:41:08 -0800115def AddSystem(output_zip, prefix="IMAGES/", recovery_img=None, boot_img=None):
Doug Zongker3c84f562014-07-31 11:06:30 -0700116 """Turn the contents of SYSTEM into a system image and store it in
David Zeuthend995f4b2016-01-29 16:59:17 -0500117 output_zip. Returns the name of the system image file."""
Michael Runge2e0d8fc2014-11-13 21:41:08 -0800118
Dan Willemsen2ee00d52017-03-05 19:51:56 -0800119 img = OutputFile(output_zip, OPTIONS.input_tmp, prefix, "system.img")
120 if os.path.exists(img.input_name):
Tao Bao89fbb0f2017-01-10 10:47:58 -0800121 print("system.img already exists in %s, no need to rebuild..." % (prefix,))
Dan Willemsen2ee00d52017-03-05 19:51:56 -0800122 return img.input_name
Michael Runge2e0d8fc2014-11-13 21:41:08 -0800123
124 def output_sink(fn, data):
Dan Albert8b72aef2015-03-23 19:13:21 -0700125 ofile = open(os.path.join(OPTIONS.input_tmp, "SYSTEM", fn), "w")
126 ofile.write(data)
127 ofile.close()
Michael Runge2e0d8fc2014-11-13 21:41:08 -0800128
Tianjie Xu38af07f2017-05-25 17:38:53 -0700129 arc_name = "SYSTEM/" + fn
130 if arc_name in output_zip.namelist():
Tianjie Xu9ac4cb02017-06-09 16:58:03 -0700131 OPTIONS.replace_updated_files_list.append(arc_name)
Tianjie Xu38af07f2017-05-25 17:38:53 -0700132 else:
133 common.ZipWrite(output_zip, ofile.name, arc_name)
134
Michael Runge2e0d8fc2014-11-13 21:41:08 -0800135 if OPTIONS.rebuild_recovery:
Tao Bao89fbb0f2017-01-10 10:47:58 -0800136 print("Building new recovery patch")
Dan Albert8b72aef2015-03-23 19:13:21 -0700137 common.MakeRecoveryPatch(OPTIONS.input_tmp, output_sink, recovery_img,
138 boot_img, info_dict=OPTIONS.info_dict)
Michael Runge2e0d8fc2014-11-13 21:41:08 -0800139
Dan Willemsen2ee00d52017-03-05 19:51:56 -0800140 block_list = OutputFile(output_zip, OPTIONS.input_tmp, prefix, "system.map")
141 CreateImage(OPTIONS.input_tmp, OPTIONS.info_dict, "system", img,
142 block_list=block_list)
David Zeuthend995f4b2016-01-29 16:59:17 -0500143
Dan Willemsen2ee00d52017-03-05 19:51:56 -0800144 return img.name
Doug Zongkerfc44a512014-08-26 13:10:25 -0700145
146
Alex Light4e358ab2016-06-16 14:47:10 -0700147def AddSystemOther(output_zip, prefix="IMAGES/"):
148 """Turn the contents of SYSTEM_OTHER into a system_other image
149 and store it in output_zip."""
150
Dan Willemsen2ee00d52017-03-05 19:51:56 -0800151 img = OutputFile(output_zip, OPTIONS.input_tmp, prefix, "system_other.img")
152 if os.path.exists(img.input_name):
Tao Bao89fbb0f2017-01-10 10:47:58 -0800153 print("system_other.img already exists in %s, no need to rebuild..." % (
154 prefix,))
Alex Light4e358ab2016-06-16 14:47:10 -0700155 return
156
Dan Willemsen2ee00d52017-03-05 19:51:56 -0800157 CreateImage(OPTIONS.input_tmp, OPTIONS.info_dict, "system_other", img)
Alex Light4e358ab2016-06-16 14:47:10 -0700158
159
Doug Zongkerfc44a512014-08-26 13:10:25 -0700160def AddVendor(output_zip, prefix="IMAGES/"):
161 """Turn the contents of VENDOR into a vendor image and store in it
162 output_zip."""
Michael Runge2e0d8fc2014-11-13 21:41:08 -0800163
Dan Willemsen2ee00d52017-03-05 19:51:56 -0800164 img = OutputFile(output_zip, OPTIONS.input_tmp, prefix, "vendor.img")
165 if os.path.exists(img.input_name):
Tao Bao89fbb0f2017-01-10 10:47:58 -0800166 print("vendor.img already exists in %s, no need to rebuild..." % (prefix,))
Dan Willemsen2ee00d52017-03-05 19:51:56 -0800167 return img.input_name
Michael Runge2e0d8fc2014-11-13 21:41:08 -0800168
Dan Willemsen2ee00d52017-03-05 19:51:56 -0800169 block_list = OutputFile(output_zip, OPTIONS.input_tmp, prefix, "vendor.map")
170 CreateImage(OPTIONS.input_tmp, OPTIONS.info_dict, "vendor", img,
171 block_list=block_list)
172 return img.name
Doug Zongker3c84f562014-07-31 11:06:30 -0700173
Yueyao Zhu889ee5e2017-05-12 17:50:46 -0700174
Jaekyun Seokb7735d82017-11-27 17:04:47 +0900175def AddProduct(output_zip, prefix="IMAGES/"):
176 """Turn the contents of PRODUCT into a product image and store it in output_zip."""
177
178 img = OutputFile(output_zip, OPTIONS.input_tmp, prefix, "product.img")
179 if os.path.exists(img.input_name):
180 print("product.img already exists in %s, no need to rebuild..." % (prefix,))
181 return img.input_name
182
183 block_list = OutputFile(output_zip, OPTIONS.input_tmp, prefix, "product.map")
184 CreateImage(OPTIONS.input_tmp, OPTIONS.info_dict, "product", img,
185 block_list=block_list)
186 return img.name
187
188
Tao Baoc633ed02017-05-30 21:46:33 -0700189def AddDtbo(output_zip, prefix="IMAGES/"):
190 """Adds the DTBO image.
191
192 Uses the image under prefix if it already exists. Otherwise looks for the
193 image under PREBUILT_IMAGES/, signs it as needed, and returns the image name.
194 """
195
196 img = OutputFile(output_zip, OPTIONS.input_tmp, prefix, "dtbo.img")
197 if os.path.exists(img.input_name):
198 print("dtbo.img already exists in %s, no need to rebuild..." % (prefix,))
199 return img.input_name
200
201 dtbo_prebuilt_path = os.path.join(
202 OPTIONS.input_tmp, "PREBUILT_IMAGES", "dtbo.img")
203 assert os.path.exists(dtbo_prebuilt_path)
204 shutil.copy(dtbo_prebuilt_path, img.name)
205
206 # AVB-sign the image as needed.
Bowgo Tsai3e599ea2017-05-26 18:30:04 +0800207 if OPTIONS.info_dict.get("avb_enable") == "true":
Tao Baoc633ed02017-05-30 21:46:33 -0700208 avbtool = os.getenv('AVBTOOL') or OPTIONS.info_dict["avb_avbtool"]
Tao Bao3ebfdde2017-05-23 23:06:55 -0700209 part_size = OPTIONS.info_dict["dtbo_size"]
Tao Baoc633ed02017-05-30 21:46:33 -0700210 # The AVB hash footer will be replaced if already present.
211 cmd = [avbtool, "add_hash_footer", "--image", img.name,
212 "--partition_size", str(part_size), "--partition_name", "dtbo"]
Bowgo Tsai3e599ea2017-05-26 18:30:04 +0800213 common.AppendAVBSigningArgs(cmd, "dtbo")
214 args = OPTIONS.info_dict.get("avb_dtbo_add_hash_footer_args")
Tao Baoc633ed02017-05-30 21:46:33 -0700215 if args and args.strip():
216 cmd.extend(shlex.split(args))
217 p = common.Run(cmd, stdout=subprocess.PIPE)
218 p.communicate()
219 assert p.returncode == 0, \
220 "avbtool add_hash_footer of %s failed" % (img.name,)
221
222 img.Write()
223 return img.name
224
Doug Zongker3c84f562014-07-31 11:06:30 -0700225
Dan Willemsen2ee00d52017-03-05 19:51:56 -0800226def CreateImage(input_dir, info_dict, what, output_file, block_list=None):
Tao Bao89fbb0f2017-01-10 10:47:58 -0800227 print("creating " + what + ".img...")
Doug Zongker3c84f562014-07-31 11:06:30 -0700228
Doug Zongker3c84f562014-07-31 11:06:30 -0700229 image_props = build_image.ImagePropFromGlobalDict(info_dict, what)
230 fstab = info_dict["fstab"]
Tianjie Xucfa86222016-03-07 16:31:19 -0800231 mount_point = "/" + what
232 if fstab and mount_point in fstab:
233 image_props["fs_type"] = fstab[mount_point].fs_type
Doug Zongker3c84f562014-07-31 11:06:30 -0700234
Tao Bao822f5842015-09-30 16:01:14 -0700235 # Use a fixed timestamp (01/01/2009) when packaging the image.
236 # Bug: 24377993
237 epoch = datetime.datetime.fromtimestamp(0)
238 timestamp = (datetime.datetime(2009, 1, 1) - epoch).total_seconds()
239 image_props["timestamp"] = int(timestamp)
240
Doug Zongker3c84f562014-07-31 11:06:30 -0700241 if what == "system":
242 fs_config_prefix = ""
243 else:
244 fs_config_prefix = what + "_"
245
246 fs_config = os.path.join(
247 input_dir, "META/" + fs_config_prefix + "filesystem_config.txt")
Dan Albert8b72aef2015-03-23 19:13:21 -0700248 if not os.path.exists(fs_config):
249 fs_config = None
Doug Zongker3c84f562014-07-31 11:06:30 -0700250
Ying Wanga2292c92015-03-24 19:07:40 -0700251 # Override values loaded from info_dict.
252 if fs_config:
253 image_props["fs_config"] = fs_config
Ying Wanga2292c92015-03-24 19:07:40 -0700254 if block_list:
Dan Willemsen2ee00d52017-03-05 19:51:56 -0800255 image_props["block_list"] = block_list.name
Ying Wanga2292c92015-03-24 19:07:40 -0700256
Tao Baod86e3112017-09-22 15:45:33 -0700257 # Use repeatable ext4 FS UUID and hash_seed UUID (based on partition name and
258 # build fingerprint).
259 uuid_seed = what + "-"
260 if "build.prop" in info_dict:
261 build_prop = info_dict["build.prop"]
262 if "ro.build.fingerprint" in build_prop:
263 uuid_seed += build_prop["ro.build.fingerprint"]
264 elif "ro.build.thumbprint" in build_prop:
265 uuid_seed += build_prop["ro.build.thumbprint"]
266 image_props["uuid"] = str(uuid.uuid5(uuid.NAMESPACE_URL, uuid_seed))
267 hash_seed = "hash_seed-" + uuid_seed
268 image_props["hash_seed"] = str(uuid.uuid5(uuid.NAMESPACE_URL, hash_seed))
269
Tao Baofa863c82017-05-23 23:49:03 -0700270 succ = build_image.BuildImage(os.path.join(input_dir, what.upper()),
Dan Willemsen2ee00d52017-03-05 19:51:56 -0800271 image_props, output_file.name)
Doug Zongker3c84f562014-07-31 11:06:30 -0700272 assert succ, "build " + what + ".img image failed"
273
Dan Willemsen2ee00d52017-03-05 19:51:56 -0800274 output_file.Write()
275 if block_list:
276 block_list.Write()
277
Tianjie Xu6b2e1552017-06-01 11:32:32 -0700278 # Set the 'adjusted_partition_size' that excludes the verity blocks of the
279 # given image. When avb is enabled, this size is the max image size returned
280 # by the avb tool.
Tianjie Xuf1a13182017-01-19 17:39:30 -0800281 is_verity_partition = "verity_block_device" in image_props
Tianjie Xu6b2e1552017-06-01 11:32:32 -0700282 verity_supported = (image_props.get("verity") == "true" or
Bowgo Tsai3e599ea2017-05-26 18:30:04 +0800283 image_props.get("avb_enable") == "true")
Tianjie Xu6b2e1552017-06-01 11:32:32 -0700284 is_avb_enable = image_props.get("avb_hashtree_enable") == "true"
285 if verity_supported and (is_verity_partition or is_avb_enable):
Tianjie Xuf1a13182017-01-19 17:39:30 -0800286 adjusted_blocks_value = image_props.get("partition_size")
287 if adjusted_blocks_value:
288 adjusted_blocks_key = what + "_adjusted_partition_size"
289 info_dict[adjusted_blocks_key] = int(adjusted_blocks_value)/4096 - 1
290
Doug Zongker3c84f562014-07-31 11:06:30 -0700291
292def AddUserdata(output_zip, prefix="IMAGES/"):
Ying Wang2a048392015-06-25 13:56:53 -0700293 """Create a userdata image and store it in output_zip.
294
295 In most case we just create and store an empty userdata.img;
296 But the invoker can also request to create userdata.img with real
297 data from the target files, by setting "userdata_img_with_data=true"
298 in OPTIONS.info_dict.
299 """
Doug Zongker3c84f562014-07-31 11:06:30 -0700300
Dan Willemsen2ee00d52017-03-05 19:51:56 -0800301 img = OutputFile(output_zip, OPTIONS.input_tmp, prefix, "userdata.img")
302 if os.path.exists(img.input_name):
Tao Bao89fbb0f2017-01-10 10:47:58 -0800303 print("userdata.img already exists in %s, no need to rebuild..." % (
304 prefix,))
Michael Runge2e0d8fc2014-11-13 21:41:08 -0800305 return
306
Elliott Hughes305b0882016-06-15 17:04:54 -0700307 # Skip userdata.img if no size.
Tao Bao2c15d9e2015-07-09 11:51:16 -0700308 image_props = build_image.ImagePropFromGlobalDict(OPTIONS.info_dict, "data")
Elliott Hughes305b0882016-06-15 17:04:54 -0700309 if not image_props.get("partition_size"):
Doug Zongker3c84f562014-07-31 11:06:30 -0700310 return
311
Tao Bao89fbb0f2017-01-10 10:47:58 -0800312 print("creating userdata.img...")
Doug Zongker3c84f562014-07-31 11:06:30 -0700313
Tao Bao822f5842015-09-30 16:01:14 -0700314 # Use a fixed timestamp (01/01/2009) when packaging the image.
315 # Bug: 24377993
316 epoch = datetime.datetime.fromtimestamp(0)
317 timestamp = (datetime.datetime(2009, 1, 1) - epoch).total_seconds()
318 image_props["timestamp"] = int(timestamp)
319
Tao Baofa863c82017-05-23 23:49:03 -0700320 if OPTIONS.info_dict.get("userdata_img_with_data") == "true":
321 user_dir = os.path.join(OPTIONS.input_tmp, "DATA")
Ying Wang2a048392015-06-25 13:56:53 -0700322 else:
Tao Bao1c830bf2017-12-25 10:43:47 -0800323 user_dir = common.MakeTempDir()
Ying Wang2a048392015-06-25 13:56:53 -0700324
Doug Zongker3c84f562014-07-31 11:06:30 -0700325 fstab = OPTIONS.info_dict["fstab"]
326 if fstab:
Dan Albert8b72aef2015-03-23 19:13:21 -0700327 image_props["fs_type"] = fstab["/data"].fs_type
Doug Zongker3c84f562014-07-31 11:06:30 -0700328 succ = build_image.BuildImage(user_dir, image_props, img.name)
329 assert succ, "build userdata.img image failed"
330
331 common.CheckSize(img.name, "userdata.img", OPTIONS.info_dict)
Dan Willemsen2ee00d52017-03-05 19:51:56 -0800332 img.Write()
Doug Zongker3c84f562014-07-31 11:06:30 -0700333
334
Bowgo Tsai3e599ea2017-05-26 18:30:04 +0800335def AppendVBMetaArgsForPartition(cmd, partition, img_path, public_key_dir):
336 if not img_path:
337 return
338
339 # Check if chain partition is used.
340 key_path = OPTIONS.info_dict.get("avb_" + partition + "_key_path")
341 if key_path:
342 # extract public key in AVB format to be included in vbmeta.img
343 avbtool = os.getenv('AVBTOOL') or OPTIONS.info_dict["avb_avbtool"]
344 public_key_path = os.path.join(public_key_dir, "%s.avbpubkey" % partition)
345 p = common.Run([avbtool, "extract_public_key", "--key", key_path,
346 "--output", public_key_path],
347 stdout=subprocess.PIPE, stderr=subprocess.PIPE)
348 p.communicate()
349 assert p.returncode == 0, \
350 "avbtool extract_public_key fail for partition: %r" % partition
351
352 rollback_index_location = OPTIONS.info_dict[
353 "avb_" + partition + "_rollback_index_location"]
354 cmd.extend(["--chain_partition", "%s:%s:%s" % (
355 partition, rollback_index_location, public_key_path)])
356 else:
357 cmd.extend(["--include_descriptors_from_image", img_path])
358
359
Tao Baobf70c312017-07-11 17:27:55 -0700360def AddVBMeta(output_zip, partitions, prefix="IMAGES/"):
361 """Creates a VBMeta image and store it in output_zip.
362
363 Args:
364 output_zip: The output zip file, which needs to be already open.
365 partitions: A dict that's keyed by partition names with image paths as
366 values. Only valid partition names are accepted, which include 'boot',
367 'recovery', 'system', 'vendor', 'dtbo'.
368 """
Dan Willemsen2ee00d52017-03-05 19:51:56 -0800369 img = OutputFile(output_zip, OPTIONS.input_tmp, prefix, "vbmeta.img")
Tao Bao262bf3f2017-07-11 17:27:55 -0700370 if os.path.exists(img.input_name):
371 print("vbmeta.img already exists in %s; not rebuilding..." % (prefix,))
372 return img.input_name
373
Tao Baoc633ed02017-05-30 21:46:33 -0700374 avbtool = os.getenv('AVBTOOL') or OPTIONS.info_dict["avb_avbtool"]
Bowgo Tsai3e599ea2017-05-26 18:30:04 +0800375 cmd = [avbtool, "make_vbmeta_image", "--output", img.name]
376 common.AppendAVBSigningArgs(cmd, "vbmeta")
377
Tao Bao1c830bf2017-12-25 10:43:47 -0800378 public_key_dir = common.MakeTempDir(prefix="avbpubkey-")
Tao Baobf70c312017-07-11 17:27:55 -0700379 for partition, path in partitions.items():
380 assert partition in common.AVB_PARTITIONS, 'Unknown partition: %s' % (
381 partition,)
382 assert os.path.exists(path), 'Failed to find %s for partition %s' % (
383 path, partition)
384 AppendVBMetaArgsForPartition(cmd, partition, path, public_key_dir)
Bowgo Tsai3e599ea2017-05-26 18:30:04 +0800385
386 args = OPTIONS.info_dict.get("avb_vbmeta_args")
David Zeuthen2ce63ed2016-09-15 13:43:54 -0400387 if args and args.strip():
Tao Bao9a5f4192017-07-20 23:51:16 -0700388 split_args = shlex.split(args)
389 for index, arg in enumerate(split_args[:-1]):
390 # Sanity check that the image file exists. Some images might be defined
391 # as a path relative to source tree, which may not be available at the
392 # same location when running this script (we have the input target_files
393 # zip only). For such cases, we additionally scan other locations (e.g.
394 # IMAGES/, RADIO/, etc) before bailing out.
395 if arg == '--include_descriptors_from_image':
396 image_path = split_args[index + 1]
397 if os.path.exists(image_path):
398 continue
399 found = False
Tao Bao6b9fef52017-12-01 16:13:22 -0800400 for dir_name in ['IMAGES', 'RADIO', 'VENDOR_IMAGES', 'PREBUILT_IMAGES']:
Tao Bao9a5f4192017-07-20 23:51:16 -0700401 alt_path = os.path.join(
Tao Bao6b9fef52017-12-01 16:13:22 -0800402 OPTIONS.input_tmp, dir_name, os.path.basename(image_path))
Tao Bao9a5f4192017-07-20 23:51:16 -0700403 if os.path.exists(alt_path):
404 split_args[index + 1] = alt_path
405 found = True
406 break
407 assert found, 'failed to find %s' % (image_path,)
408 cmd.extend(split_args)
Bowgo Tsai3e599ea2017-05-26 18:30:04 +0800409
David Zeuthen2ce63ed2016-09-15 13:43:54 -0400410 p = common.Run(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
411 p.communicate()
412 assert p.returncode == 0, "avbtool make_vbmeta_image failed"
Dan Willemsen2ee00d52017-03-05 19:51:56 -0800413 img.Write()
David Zeuthen2ce63ed2016-09-15 13:43:54 -0400414
415
David Zeuthen25328622016-04-08 15:08:03 -0400416def AddPartitionTable(output_zip, prefix="IMAGES/"):
417 """Create a partition table image and store it in output_zip."""
418
Dan Willemsen2ee00d52017-03-05 19:51:56 -0800419 img = OutputFile(output_zip, OPTIONS.input_tmp, prefix, "partition-table.img")
420 bpt = OutputFile(output_zip, OPTIONS.input_tmp, prefix, "partition-table.bpt")
David Zeuthen25328622016-04-08 15:08:03 -0400421
422 # use BPTTOOL from environ, or "bpttool" if empty or not set.
423 bpttool = os.getenv("BPTTOOL") or "bpttool"
Dan Willemsen2ee00d52017-03-05 19:51:56 -0800424 cmd = [bpttool, "make_table", "--output_json", bpt.name,
425 "--output_gpt", img.name]
David Zeuthen25328622016-04-08 15:08:03 -0400426 input_files_str = OPTIONS.info_dict["board_bpt_input_files"]
427 input_files = input_files_str.split(" ")
428 for i in input_files:
429 cmd.extend(["--input", i])
430 disk_size = OPTIONS.info_dict.get("board_bpt_disk_size")
431 if disk_size:
432 cmd.extend(["--disk_size", disk_size])
433 args = OPTIONS.info_dict.get("board_bpt_make_table_args")
434 if args:
435 cmd.extend(shlex.split(args))
436
437 p = common.Run(cmd, stdout=subprocess.PIPE)
438 p.communicate()
439 assert p.returncode == 0, "bpttool make_table failed"
440
Dan Willemsen2ee00d52017-03-05 19:51:56 -0800441 img.Write()
442 bpt.Write()
David Zeuthen25328622016-04-08 15:08:03 -0400443
444
Doug Zongker3c84f562014-07-31 11:06:30 -0700445def AddCache(output_zip, prefix="IMAGES/"):
446 """Create an empty cache image and store it in output_zip."""
447
Dan Willemsen2ee00d52017-03-05 19:51:56 -0800448 img = OutputFile(output_zip, OPTIONS.input_tmp, prefix, "cache.img")
449 if os.path.exists(img.input_name):
Tao Bao89fbb0f2017-01-10 10:47:58 -0800450 print("cache.img already exists in %s, no need to rebuild..." % (prefix,))
Michael Runge2e0d8fc2014-11-13 21:41:08 -0800451 return
452
Tao Bao2c15d9e2015-07-09 11:51:16 -0700453 image_props = build_image.ImagePropFromGlobalDict(OPTIONS.info_dict, "cache")
Doug Zongker3c84f562014-07-31 11:06:30 -0700454 # The build system has to explicitly request for cache.img.
455 if "fs_type" not in image_props:
456 return
457
Tao Bao89fbb0f2017-01-10 10:47:58 -0800458 print("creating cache.img...")
Doug Zongker3c84f562014-07-31 11:06:30 -0700459
Tao Bao822f5842015-09-30 16:01:14 -0700460 # Use a fixed timestamp (01/01/2009) when packaging the image.
461 # Bug: 24377993
462 epoch = datetime.datetime.fromtimestamp(0)
463 timestamp = (datetime.datetime(2009, 1, 1) - epoch).total_seconds()
464 image_props["timestamp"] = int(timestamp)
465
Tao Bao1c830bf2017-12-25 10:43:47 -0800466 user_dir = common.MakeTempDir()
Doug Zongker3c84f562014-07-31 11:06:30 -0700467
468 fstab = OPTIONS.info_dict["fstab"]
469 if fstab:
Dan Albert8b72aef2015-03-23 19:13:21 -0700470 image_props["fs_type"] = fstab["/cache"].fs_type
Doug Zongker3c84f562014-07-31 11:06:30 -0700471 succ = build_image.BuildImage(user_dir, image_props, img.name)
472 assert succ, "build cache.img image failed"
473
474 common.CheckSize(img.name, "cache.img", OPTIONS.info_dict)
Dan Willemsen2ee00d52017-03-05 19:51:56 -0800475 img.Write()
Doug Zongker3c84f562014-07-31 11:06:30 -0700476
477
Tao Baobea20ac2018-01-17 17:57:49 -0800478def AddRadioImagesForAbOta(output_zip, ab_partitions):
479 """Adds the radio images needed for A/B OTA to the output file.
480
481 It parses the list of A/B partitions, looks for the missing ones from RADIO/
482 or VENDOR_IMAGES/ dirs, and copies them to IMAGES/ of the output file (or
483 dir).
484
485 It also ensures that on returning from the function all the listed A/B
486 partitions must have their images available under IMAGES/.
487
488 Args:
489 output_zip: The output zip file (needs to be already open), or None to
490 write images to OPTIONS.input_tmp/.
491 ab_partitions: The list of A/B partitions.
492
493 Raises:
494 AssertionError: If it can't find an image.
495 """
496 for partition in ab_partitions:
497 img_name = partition.strip() + ".img"
498 prebuilt_path = os.path.join(OPTIONS.input_tmp, "IMAGES", img_name)
499 if os.path.exists(prebuilt_path):
500 print("%s already exists, no need to overwrite..." % (img_name,))
501 continue
502
503 img_radio_path = os.path.join(OPTIONS.input_tmp, "RADIO", img_name)
504 if os.path.exists(img_radio_path):
505 if output_zip:
Tao Baoa2ff4c92018-01-17 12:14:43 -0800506 common.ZipWrite(output_zip, img_radio_path, "IMAGES/" + img_name)
Tao Baobea20ac2018-01-17 17:57:49 -0800507 else:
508 shutil.copy(img_radio_path, prebuilt_path)
Tao Baoa2ff4c92018-01-17 12:14:43 -0800509 continue
Tao Baobea20ac2018-01-17 17:57:49 -0800510
Tao Baoa2ff4c92018-01-17 12:14:43 -0800511 # Walk through VENDOR_IMAGES/ since files could be under subdirs.
512 img_vendor_dir = os.path.join(OPTIONS.input_tmp, "VENDOR_IMAGES")
513 for root, _, files in os.walk(img_vendor_dir):
514 if img_name in files:
515 if output_zip:
516 common.ZipWrite(output_zip, os.path.join(root, img_name),
517 "IMAGES/" + img_name)
518 else:
519 shutil.copy(os.path.join(root, img_name), prebuilt_path)
520 break
521
522 # Assert that the image is present under IMAGES/ now.
Tao Baobea20ac2018-01-17 17:57:49 -0800523 if output_zip:
524 # Zip spec says: All slashes MUST be forward slashes.
525 img_path = 'IMAGES/' + img_name
526 assert img_path in output_zip.namelist(), "cannot find " + img_name
527 else:
528 img_path = os.path.join(OPTIONS.input_tmp, "IMAGES", img_name)
529 assert os.path.exists(img_path), "cannot find " + img_name
530
531
532def AddCareMapTxtForAbOta(output_zip, ab_partitions, image_paths):
533 """Generates and adds care_map.txt for system and vendor partitions.
534
535 Args:
536 output_zip: The output zip file (needs to be already open), or None to
537 write images to OPTIONS.input_tmp/.
538 ab_partitions: The list of A/B partitions.
539 image_paths: A map from the partition name to the image path.
540 """
541 care_map_list = []
542 for partition in ab_partitions:
543 partition = partition.strip()
Tao Baoa2ff4c92018-01-17 12:14:43 -0800544 if partition not in PARTITIONS_WITH_CARE_MAP:
545 continue
546
547 verity_block_device = "{}_verity_block_device".format(partition)
548 avb_hashtree_enable = "avb_{}_hashtree_enable".format(partition)
549 if (verity_block_device in OPTIONS.info_dict or
550 OPTIONS.info_dict.get(avb_hashtree_enable) == "true"):
551 image_path = image_paths[partition]
552 assert os.path.exists(image_path)
553 care_map_list += GetCareMap(partition, image_path)
Tao Baobea20ac2018-01-17 17:57:49 -0800554
555 if care_map_list:
556 care_map_path = "META/care_map.txt"
557 if output_zip and care_map_path not in output_zip.namelist():
558 common.ZipWriteStr(output_zip, care_map_path, '\n'.join(care_map_list))
559 else:
560 with open(os.path.join(OPTIONS.input_tmp, care_map_path), 'w') as fp:
561 fp.write('\n'.join(care_map_list))
562 if output_zip:
563 OPTIONS.replace_updated_files_list.append(care_map_path)
564
565
566def AddPackRadioImages(output_zip, images):
567 """Copies images listed in META/pack_radioimages.txt from RADIO/ to IMAGES/.
568
569 Args:
570 output_zip: The output zip file (needs to be already open), or None to
571 write images to OPTIONS.input_tmp/.
572 images: A list of image names.
573
574 Raises:
575 AssertionError: If a listed image can't be found.
576 """
577 for image in images:
578 img_name = image.strip()
579 _, ext = os.path.splitext(img_name)
580 if not ext:
581 img_name += ".img"
Tao Baoa2ff4c92018-01-17 12:14:43 -0800582
Tao Baobea20ac2018-01-17 17:57:49 -0800583 prebuilt_path = os.path.join(OPTIONS.input_tmp, "IMAGES", img_name)
584 if os.path.exists(prebuilt_path):
585 print("%s already exists, no need to overwrite..." % (img_name,))
586 continue
587
588 img_radio_path = os.path.join(OPTIONS.input_tmp, "RADIO", img_name)
589 assert os.path.exists(img_radio_path), \
590 "Failed to find %s at %s" % (img_name, img_radio_path)
Tao Baoa2ff4c92018-01-17 12:14:43 -0800591
Tao Baobea20ac2018-01-17 17:57:49 -0800592 if output_zip:
Tao Baoa2ff4c92018-01-17 12:14:43 -0800593 common.ZipWrite(output_zip, img_radio_path, "IMAGES/" + img_name)
Tao Baobea20ac2018-01-17 17:57:49 -0800594 else:
595 shutil.copy(img_radio_path, prebuilt_path)
596
597
Tianjie Xu9ac4cb02017-06-09 16:58:03 -0700598def ReplaceUpdatedFiles(zip_filename, files_list):
Tao Bao89d7ab22017-12-14 17:05:33 -0800599 """Updates all the ZIP entries listed in files_list.
Tianjie Xu38af07f2017-05-25 17:38:53 -0700600
Tianjie Xu9ac4cb02017-06-09 16:58:03 -0700601 For now the list includes META/care_map.txt, and the related files under
602 SYSTEM/ after rebuilding recovery.
603 """
Tao Bao89d7ab22017-12-14 17:05:33 -0800604 common.ZipDelete(zip_filename, files_list)
Tianjie Xu38af07f2017-05-25 17:38:53 -0700605 output_zip = zipfile.ZipFile(zip_filename, "a",
606 compression=zipfile.ZIP_DEFLATED,
607 allowZip64=True)
Tianjie Xu9ac4cb02017-06-09 16:58:03 -0700608 for item in files_list:
Tianjie Xu38af07f2017-05-25 17:38:53 -0700609 file_path = os.path.join(OPTIONS.input_tmp, item)
610 assert os.path.exists(file_path)
611 common.ZipWrite(output_zip, file_path, arcname=item)
612 common.ZipClose(output_zip)
613
614
Doug Zongker3c84f562014-07-31 11:06:30 -0700615def AddImagesToTargetFiles(filename):
Tao Baoae396d92017-11-20 11:56:43 -0800616 """Creates and adds images (boot/recovery/system/...) to a target_files.zip.
617
618 It works with either a zip file (zip mode), or a directory that contains the
619 files to be packed into a target_files.zip (dir mode). The latter is used when
620 being called from build/make/core/Makefile.
621
622 The images will be created under IMAGES/ in the input target_files.zip.
623
624 Args:
625 filename: the target_files.zip, or the zip root directory.
626 """
Dan Willemsen2ee00d52017-03-05 19:51:56 -0800627 if os.path.isdir(filename):
628 OPTIONS.input_tmp = os.path.abspath(filename)
629 input_zip = None
630 else:
631 OPTIONS.input_tmp, input_zip = common.UnzipTemp(filename)
Doug Zongkerfc44a512014-08-26 13:10:25 -0700632
Michael Runge2e0d8fc2014-11-13 21:41:08 -0800633 if not OPTIONS.add_missing:
Dan Willemsen2ee00d52017-03-05 19:51:56 -0800634 if os.path.isdir(os.path.join(OPTIONS.input_tmp, "IMAGES")):
635 print("target_files appears to already contain images.")
636 sys.exit(1)
Doug Zongkerfc44a512014-08-26 13:10:25 -0700637
Jaekyun Seokb7735d82017-11-27 17:04:47 +0900638 # {vendor,product}.img is unlike system.img or system_other.img. Because it could
639 # be built from source, or dropped into target_files.zip as a prebuilt blob.
640 # We consider either of them as {vendor,product}.img being available, which could
641 # be used when generating vbmeta.img for AVB.
Tao Baob22afea2017-09-12 12:39:09 -0700642 has_vendor = (os.path.isdir(os.path.join(OPTIONS.input_tmp, "VENDOR")) or
643 os.path.exists(os.path.join(OPTIONS.input_tmp, "IMAGES",
644 "vendor.img")))
Jaekyun Seokb7735d82017-11-27 17:04:47 +0900645 has_product = (os.path.isdir(os.path.join(OPTIONS.input_tmp, "PRODUCT")) or
646 os.path.exists(os.path.join(OPTIONS.input_tmp, "IMAGES",
647 "product.img")))
Dan Willemsen2ee00d52017-03-05 19:51:56 -0800648 has_system_other = os.path.isdir(os.path.join(OPTIONS.input_tmp,
649 "SYSTEM_OTHER"))
Doug Zongker3c84f562014-07-31 11:06:30 -0700650
Dan Willemsen2ee00d52017-03-05 19:51:56 -0800651 if input_zip:
652 OPTIONS.info_dict = common.LoadInfoDict(input_zip, OPTIONS.input_tmp)
Alex Light4e358ab2016-06-16 14:47:10 -0700653
Dan Willemsen2ee00d52017-03-05 19:51:56 -0800654 common.ZipClose(input_zip)
655 output_zip = zipfile.ZipFile(filename, "a",
656 compression=zipfile.ZIP_DEFLATED,
657 allowZip64=True)
658 else:
659 OPTIONS.info_dict = common.LoadInfoDict(filename, filename)
660 output_zip = None
Tao Baoae396d92017-11-20 11:56:43 -0800661
662 # Always make input_tmp/IMAGES available, since we may stage boot / recovery
663 # images there even under zip mode. The directory will be cleaned up as part
664 # of OPTIONS.input_tmp.
665 images_dir = os.path.join(OPTIONS.input_tmp, "IMAGES")
666 if not os.path.isdir(images_dir):
667 os.makedirs(images_dir)
Doug Zongker3c84f562014-07-31 11:06:30 -0700668
Tao Baodb45efa2015-10-27 19:25:18 -0700669 has_recovery = (OPTIONS.info_dict.get("no_recovery") != "true")
670
Tao Bao2b6dfd62017-09-27 17:17:43 -0700671 if OPTIONS.info_dict.get("avb_enable") == "true":
672 fp = None
673 if "build.prop" in OPTIONS.info_dict:
674 build_prop = OPTIONS.info_dict["build.prop"]
675 if "ro.build.fingerprint" in build_prop:
676 fp = build_prop["ro.build.fingerprint"]
677 elif "ro.build.thumbprint" in build_prop:
678 fp = build_prop["ro.build.thumbprint"]
679 if fp:
680 OPTIONS.info_dict["avb_salt"] = hashlib.sha256(fp).hexdigest()
681
Tao Baobf70c312017-07-11 17:27:55 -0700682 # A map between partition names and their paths, which could be used when
683 # generating AVB vbmeta image.
684 partitions = dict()
685
Doug Zongkerfc44a512014-08-26 13:10:25 -0700686 def banner(s):
Tao Bao89fbb0f2017-01-10 10:47:58 -0800687 print("\n\n++++ " + s + " ++++\n\n")
Doug Zongker3c84f562014-07-31 11:06:30 -0700688
Tao Bao262bf3f2017-07-11 17:27:55 -0700689 banner("boot")
690 # common.GetBootableImage() returns the image directly if present.
691 boot_image = common.GetBootableImage(
692 "IMAGES/boot.img", "boot.img", OPTIONS.input_tmp, "BOOT")
693 # boot.img may be unavailable in some targets (e.g. aosp_arm64).
694 if boot_image:
Tao Baobf70c312017-07-11 17:27:55 -0700695 partitions['boot'] = os.path.join(OPTIONS.input_tmp, "IMAGES", "boot.img")
696 if not os.path.exists(partitions['boot']):
Tao Bao262bf3f2017-07-11 17:27:55 -0700697 boot_image.WriteToDir(OPTIONS.input_tmp)
Dan Willemsen2ee00d52017-03-05 19:51:56 -0800698 if output_zip:
699 boot_image.AddToZip(output_zip)
Doug Zongker3c84f562014-07-31 11:06:30 -0700700
Michael Runge2e0d8fc2014-11-13 21:41:08 -0800701 recovery_image = None
Tao Baodb45efa2015-10-27 19:25:18 -0700702 if has_recovery:
703 banner("recovery")
Tao Bao262bf3f2017-07-11 17:27:55 -0700704 recovery_image = common.GetBootableImage(
705 "IMAGES/recovery.img", "recovery.img", OPTIONS.input_tmp, "RECOVERY")
706 assert recovery_image, "Failed to create recovery.img."
Tao Baobf70c312017-07-11 17:27:55 -0700707 partitions['recovery'] = os.path.join(
Tao Bao262bf3f2017-07-11 17:27:55 -0700708 OPTIONS.input_tmp, "IMAGES", "recovery.img")
Tao Baobf70c312017-07-11 17:27:55 -0700709 if not os.path.exists(partitions['recovery']):
Tao Bao262bf3f2017-07-11 17:27:55 -0700710 recovery_image.WriteToDir(OPTIONS.input_tmp)
711 if output_zip:
712 recovery_image.AddToZip(output_zip)
Doug Zongker3c84f562014-07-31 11:06:30 -0700713
Tao Baod42e97e2016-11-30 12:11:57 -0800714 banner("recovery (two-step image)")
715 # The special recovery.img for two-step package use.
716 recovery_two_step_image = common.GetBootableImage(
717 "IMAGES/recovery-two-step.img", "recovery-two-step.img",
718 OPTIONS.input_tmp, "RECOVERY", two_step_image=True)
Tao Bao262bf3f2017-07-11 17:27:55 -0700719 assert recovery_two_step_image, "Failed to create recovery-two-step.img."
720 recovery_two_step_image_path = os.path.join(
721 OPTIONS.input_tmp, "IMAGES", "recovery-two-step.img")
722 if not os.path.exists(recovery_two_step_image_path):
723 recovery_two_step_image.WriteToDir(OPTIONS.input_tmp)
Dan Willemsen2ee00d52017-03-05 19:51:56 -0800724 if output_zip:
725 recovery_two_step_image.AddToZip(output_zip)
Tao Baod42e97e2016-11-30 12:11:57 -0800726
Doug Zongkerfc44a512014-08-26 13:10:25 -0700727 banner("system")
Tao Baobea20ac2018-01-17 17:57:49 -0800728 partitions['system'] = AddSystem(
Tao Baoc633ed02017-05-30 21:46:33 -0700729 output_zip, recovery_img=recovery_image, boot_img=boot_image)
Tao Baobf70c312017-07-11 17:27:55 -0700730
Doug Zongkerfc44a512014-08-26 13:10:25 -0700731 if has_vendor:
732 banner("vendor")
Tao Baobea20ac2018-01-17 17:57:49 -0800733 partitions['vendor'] = AddVendor(output_zip)
Tao Baobf70c312017-07-11 17:27:55 -0700734
Jaekyun Seokb7735d82017-11-27 17:04:47 +0900735 if has_product:
736 banner("product")
737 partitions['product'] = AddProduct(output_zip)
738
Alex Light4e358ab2016-06-16 14:47:10 -0700739 if has_system_other:
740 banner("system_other")
741 AddSystemOther(output_zip)
Tao Baobf70c312017-07-11 17:27:55 -0700742
Tianjie Xub48589a2016-08-03 19:21:52 -0700743 if not OPTIONS.is_signing:
744 banner("userdata")
745 AddUserdata(output_zip)
746 banner("cache")
747 AddCache(output_zip)
Tao Baoc633ed02017-05-30 21:46:33 -0700748
749 if OPTIONS.info_dict.get("board_bpt_enable") == "true":
David Zeuthen25328622016-04-08 15:08:03 -0400750 banner("partition-table")
751 AddPartitionTable(output_zip)
Tao Baoc633ed02017-05-30 21:46:33 -0700752
Tao Baoc633ed02017-05-30 21:46:33 -0700753 if OPTIONS.info_dict.get("has_dtbo") == "true":
754 banner("dtbo")
Tao Baobf70c312017-07-11 17:27:55 -0700755 partitions['dtbo'] = AddDtbo(output_zip)
Tao Baoc633ed02017-05-30 21:46:33 -0700756
Bowgo Tsai3e599ea2017-05-26 18:30:04 +0800757 if OPTIONS.info_dict.get("avb_enable") == "true":
David Zeuthen2ce63ed2016-09-15 13:43:54 -0400758 banner("vbmeta")
Tao Baobf70c312017-07-11 17:27:55 -0700759 AddVBMeta(output_zip, partitions)
Doug Zongker3c84f562014-07-31 11:06:30 -0700760
Tianjie Xuaaca4212016-06-28 14:34:03 -0700761 banner("radio")
Tao Baobea20ac2018-01-17 17:57:49 -0800762 ab_partitions_txt = os.path.join(OPTIONS.input_tmp, "META",
763 "ab_partitions.txt")
764 if os.path.exists(ab_partitions_txt):
765 with open(ab_partitions_txt, 'r') as f:
766 ab_partitions = f.readlines()
Tianjie Xucfa86222016-03-07 16:31:19 -0800767
Tao Baobea20ac2018-01-17 17:57:49 -0800768 # For devices using A/B update, copy over images from RADIO/ and/or
769 # VENDOR_IMAGES/ to IMAGES/ and make sure we have all the needed
770 # images ready under IMAGES/. All images should have '.img' as extension.
771 AddRadioImagesForAbOta(output_zip, ab_partitions)
Tianjie Xuaaca4212016-06-28 14:34:03 -0700772
Tao Baobea20ac2018-01-17 17:57:49 -0800773 # Generate care_map.txt for system and vendor partitions (if present), then
774 # write this file to target_files package.
775 AddCareMapTxtForAbOta(output_zip, ab_partitions, partitions)
Tianjie Xucfa86222016-03-07 16:31:19 -0800776
Tao Bao95a95c32017-06-16 15:30:23 -0700777 # Radio images that need to be packed into IMAGES/, and product-img.zip.
Tao Baobea20ac2018-01-17 17:57:49 -0800778 pack_radioimages_txt = os.path.join(
Tao Bao95a95c32017-06-16 15:30:23 -0700779 OPTIONS.input_tmp, "META", "pack_radioimages.txt")
Tao Baobea20ac2018-01-17 17:57:49 -0800780 if os.path.exists(pack_radioimages_txt):
781 with open(pack_radioimages_txt, 'r') as f:
782 AddPackRadioImages(output_zip, f.readlines())
Tao Bao95a95c32017-06-16 15:30:23 -0700783
Dan Willemsen2ee00d52017-03-05 19:51:56 -0800784 if output_zip:
785 common.ZipClose(output_zip)
Tianjie Xu9ac4cb02017-06-09 16:58:03 -0700786 if OPTIONS.replace_updated_files_list:
787 ReplaceUpdatedFiles(output_zip.filename,
788 OPTIONS.replace_updated_files_list)
Tianjie Xu38af07f2017-05-25 17:38:53 -0700789
Doug Zongker3c84f562014-07-31 11:06:30 -0700790
Doug Zongker3c84f562014-07-31 11:06:30 -0700791def main(argv):
Baligh Uddin59f4ff12015-09-16 21:20:30 -0700792 def option_handler(o, a):
Michael Runge2e0d8fc2014-11-13 21:41:08 -0800793 if o in ("-a", "--add_missing"):
794 OPTIONS.add_missing = True
795 elif o in ("-r", "--rebuild_recovery",):
796 OPTIONS.rebuild_recovery = True
Baligh Uddin59f4ff12015-09-16 21:20:30 -0700797 elif o == "--replace_verity_private_key":
798 OPTIONS.replace_verity_private_key = (True, a)
799 elif o == "--replace_verity_public_key":
800 OPTIONS.replace_verity_public_key = (True, a)
Tianjie Xub48589a2016-08-03 19:21:52 -0700801 elif o == "--is_signing":
802 OPTIONS.is_signing = True
Michael Runge2e0d8fc2014-11-13 21:41:08 -0800803 else:
804 return False
805 return True
806
Dan Albert8b72aef2015-03-23 19:13:21 -0700807 args = common.ParseOptions(
808 argv, __doc__, extra_opts="ar",
Baligh Uddin59f4ff12015-09-16 21:20:30 -0700809 extra_long_opts=["add_missing", "rebuild_recovery",
810 "replace_verity_public_key=",
811 "replace_verity_private_key=",
Tao Bao45810422016-10-17 16:20:12 -0700812 "is_signing"],
Dan Albert8b72aef2015-03-23 19:13:21 -0700813 extra_option_handler=option_handler)
Michael Runge2e0d8fc2014-11-13 21:41:08 -0800814
Doug Zongker3c84f562014-07-31 11:06:30 -0700815
816 if len(args) != 1:
817 common.Usage(__doc__)
818 sys.exit(1)
819
820 AddImagesToTargetFiles(args[0])
Tao Bao89fbb0f2017-01-10 10:47:58 -0800821 print("done.")
Doug Zongker3c84f562014-07-31 11:06:30 -0700822
823if __name__ == '__main__':
824 try:
825 common.CloseInheritedPipes()
826 main(sys.argv[1:])
Dan Albert8b72aef2015-03-23 19:13:21 -0700827 except common.ExternalError as e:
Tao Bao89fbb0f2017-01-10 10:47:58 -0800828 print("\n ERROR: %s\n" % (e,))
Doug Zongker3c84f562014-07-31 11:06:30 -0700829 sys.exit(1)
Doug Zongkerfc44a512014-08-26 13:10:25 -0700830 finally:
831 common.Cleanup()