blob: d7d1bc81da83361aa7f54341481efc0aa7675f8d [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
Doug Zongker3c84f562014-07-31 11:06:30 -070049import os
David Zeuthend995f4b2016-01-29 16:59:17 -050050import shlex
Ying Wang2a048392015-06-25 13:56:53 -070051import shutil
David Zeuthend995f4b2016-01-29 16:59:17 -050052import subprocess
Tao Bao6b9fef52017-12-01 16:13:22 -080053import sys
Tao Baod86e3112017-09-22 15:45:33 -070054import uuid
Doug Zongker3c84f562014-07-31 11:06:30 -070055import zipfile
56
Doug Zongker3c84f562014-07-31 11:06:30 -070057import build_image
58import common
Tianjie Xuf1a13182017-01-19 17:39:30 -080059import rangelib
Tianjie Xucfa86222016-03-07 16:31:19 -080060import sparse_img
Doug Zongker3c84f562014-07-31 11:06:30 -070061
Tao Bao6b9fef52017-12-01 16:13:22 -080062if sys.hexversion < 0x02070000:
63 print("Python 2.7 or newer is required.", file=sys.stderr)
64 sys.exit(1)
65
Doug Zongker3c84f562014-07-31 11:06:30 -070066OPTIONS = common.OPTIONS
67
Michael Runge2e0d8fc2014-11-13 21:41:08 -080068OPTIONS.add_missing = False
69OPTIONS.rebuild_recovery = False
Tianjie Xu9ac4cb02017-06-09 16:58:03 -070070OPTIONS.replace_updated_files_list = []
Baligh Uddin59f4ff12015-09-16 21:20:30 -070071OPTIONS.replace_verity_public_key = False
72OPTIONS.replace_verity_private_key = False
Tianjie Xub48589a2016-08-03 19:21:52 -070073OPTIONS.is_signing = False
Doug Zongker3c84f562014-07-31 11:06:30 -070074
Bryan Henrye6d547d2018-07-31 18:32:00 -070075# Use a fixed timestamp (01/01/2009 00:00:00 UTC) for files when packaging
76# images. (b/24377993, b/80600931)
Tao Baoe30a6a62018-08-27 10:57:19 -070077FIXED_FILE_TIMESTAMP = int((
78 datetime.datetime(2009, 1, 1, 0, 0, 0, 0, None) -
79 datetime.datetime.utcfromtimestamp(0)).total_seconds())
Tao Baoa2ff4c92018-01-17 12:14:43 -080080
Bowgo Tsaid624fa62017-11-14 23:42:30 +080081
Dan Willemsen2ee00d52017-03-05 19:51:56 -080082class OutputFile(object):
83 def __init__(self, output_zip, input_dir, prefix, name):
84 self._output_zip = output_zip
85 self.input_name = os.path.join(input_dir, prefix, name)
86
87 if self._output_zip:
88 self._zip_name = os.path.join(prefix, name)
89
90 root, suffix = os.path.splitext(name)
91 self.name = common.MakeTempFile(prefix=root + '-', suffix=suffix)
92 else:
93 self.name = self.input_name
94
95 def Write(self):
96 if self._output_zip:
97 common.ZipWrite(self._output_zip, self.name, self._zip_name)
98
Tao Baoe30a6a62018-08-27 10:57:19 -070099
Tianjie Xucfa86222016-03-07 16:31:19 -0800100def GetCareMap(which, imgname):
Tao Bao63c18fe2018-02-21 23:45:43 -0800101 """Returns the care_map string for the given partition.
102
103 Args:
104 which: The partition name, must be listed in PARTITIONS_WITH_CARE_MAP.
105 imgname: The filename of the image.
106
107 Returns:
108 (which, care_map_ranges): care_map_ranges is the raw string of the care_map
109 RangeSet.
110 """
Tianjie Xu861f4132018-09-12 11:49:33 -0700111 assert which in common.PARTITIONS_WITH_CARE_MAP
Tianjie Xucfa86222016-03-07 16:31:19 -0800112
113 simg = sparse_img.SparseImage(imgname)
Tianjie Xuf1a13182017-01-19 17:39:30 -0800114 care_map_ranges = simg.care_map
Tao Bao35f4ebc2018-09-27 15:31:11 -0700115 key = which + "_image_blocks"
116 image_blocks = OPTIONS.info_dict.get(key)
117 if image_blocks:
118 assert image_blocks > 0, "blocks for {} must be positive".format(which)
119 care_map_ranges = care_map_ranges.intersect(
120 rangelib.RangeSet("0-{}".format(image_blocks)))
Tianjie Xuf1a13182017-01-19 17:39:30 -0800121
Tao Baoa2ff4c92018-01-17 12:14:43 -0800122 return [which, care_map_ranges.to_string_raw()]
Tianjie Xucfa86222016-03-07 16:31:19 -0800123
124
Tao Bao886d8832018-02-27 11:46:19 -0800125def AddSystem(output_zip, recovery_img=None, boot_img=None):
Doug Zongker3c84f562014-07-31 11:06:30 -0700126 """Turn the contents of SYSTEM into a system image and store it in
David Zeuthend995f4b2016-01-29 16:59:17 -0500127 output_zip. Returns the name of the system image file."""
Michael Runge2e0d8fc2014-11-13 21:41:08 -0800128
Tao Bao886d8832018-02-27 11:46:19 -0800129 img = OutputFile(output_zip, OPTIONS.input_tmp, "IMAGES", "system.img")
Dan Willemsen2ee00d52017-03-05 19:51:56 -0800130 if os.path.exists(img.input_name):
Tao Bao886d8832018-02-27 11:46:19 -0800131 print("system.img already exists; no need to rebuild...")
Dan Willemsen2ee00d52017-03-05 19:51:56 -0800132 return img.input_name
Michael Runge2e0d8fc2014-11-13 21:41:08 -0800133
134 def output_sink(fn, data):
Dan Albert8b72aef2015-03-23 19:13:21 -0700135 ofile = open(os.path.join(OPTIONS.input_tmp, "SYSTEM", fn), "w")
136 ofile.write(data)
137 ofile.close()
Michael Runge2e0d8fc2014-11-13 21:41:08 -0800138
Tianjie Xu38af07f2017-05-25 17:38:53 -0700139 arc_name = "SYSTEM/" + fn
140 if arc_name in output_zip.namelist():
Tianjie Xu9ac4cb02017-06-09 16:58:03 -0700141 OPTIONS.replace_updated_files_list.append(arc_name)
Tianjie Xu38af07f2017-05-25 17:38:53 -0700142 else:
143 common.ZipWrite(output_zip, ofile.name, arc_name)
144
Michael Runge2e0d8fc2014-11-13 21:41:08 -0800145 if OPTIONS.rebuild_recovery:
Tao Bao89fbb0f2017-01-10 10:47:58 -0800146 print("Building new recovery patch")
Dan Albert8b72aef2015-03-23 19:13:21 -0700147 common.MakeRecoveryPatch(OPTIONS.input_tmp, output_sink, recovery_img,
148 boot_img, info_dict=OPTIONS.info_dict)
Michael Runge2e0d8fc2014-11-13 21:41:08 -0800149
Tao Bao886d8832018-02-27 11:46:19 -0800150 block_list = OutputFile(output_zip, OPTIONS.input_tmp, "IMAGES", "system.map")
Dan Willemsen2ee00d52017-03-05 19:51:56 -0800151 CreateImage(OPTIONS.input_tmp, OPTIONS.info_dict, "system", img,
152 block_list=block_list)
David Zeuthend995f4b2016-01-29 16:59:17 -0500153
Dan Willemsen2ee00d52017-03-05 19:51:56 -0800154 return img.name
Doug Zongkerfc44a512014-08-26 13:10:25 -0700155
156
Tao Bao886d8832018-02-27 11:46:19 -0800157def AddSystemOther(output_zip):
Alex Light4e358ab2016-06-16 14:47:10 -0700158 """Turn the contents of SYSTEM_OTHER into a system_other image
159 and store it in output_zip."""
160
Tao Bao886d8832018-02-27 11:46:19 -0800161 img = OutputFile(output_zip, OPTIONS.input_tmp, "IMAGES", "system_other.img")
Dan Willemsen2ee00d52017-03-05 19:51:56 -0800162 if os.path.exists(img.input_name):
Tao Bao886d8832018-02-27 11:46:19 -0800163 print("system_other.img already exists; no need to rebuild...")
Alex Light4e358ab2016-06-16 14:47:10 -0700164 return
165
Dan Willemsen2ee00d52017-03-05 19:51:56 -0800166 CreateImage(OPTIONS.input_tmp, OPTIONS.info_dict, "system_other", img)
Alex Light4e358ab2016-06-16 14:47:10 -0700167
168
Tao Bao886d8832018-02-27 11:46:19 -0800169def AddVendor(output_zip):
Doug Zongkerfc44a512014-08-26 13:10:25 -0700170 """Turn the contents of VENDOR into a vendor image and store in it
171 output_zip."""
Michael Runge2e0d8fc2014-11-13 21:41:08 -0800172
Tao Bao886d8832018-02-27 11:46:19 -0800173 img = OutputFile(output_zip, OPTIONS.input_tmp, "IMAGES", "vendor.img")
Dan Willemsen2ee00d52017-03-05 19:51:56 -0800174 if os.path.exists(img.input_name):
Tao Bao886d8832018-02-27 11:46:19 -0800175 print("vendor.img already exists; no need to rebuild...")
Dan Willemsen2ee00d52017-03-05 19:51:56 -0800176 return img.input_name
Michael Runge2e0d8fc2014-11-13 21:41:08 -0800177
Tao Bao886d8832018-02-27 11:46:19 -0800178 block_list = OutputFile(output_zip, OPTIONS.input_tmp, "IMAGES", "vendor.map")
Dan Willemsen2ee00d52017-03-05 19:51:56 -0800179 CreateImage(OPTIONS.input_tmp, OPTIONS.info_dict, "vendor", img,
180 block_list=block_list)
181 return img.name
Doug Zongker3c84f562014-07-31 11:06:30 -0700182
Yueyao Zhu889ee5e2017-05-12 17:50:46 -0700183
Tao Bao886d8832018-02-27 11:46:19 -0800184def AddProduct(output_zip):
185 """Turn the contents of PRODUCT into a product image and store it in
186 output_zip."""
Jaekyun Seokb7735d82017-11-27 17:04:47 +0900187
Tao Bao886d8832018-02-27 11:46:19 -0800188 img = OutputFile(output_zip, OPTIONS.input_tmp, "IMAGES", "product.img")
Jaekyun Seokb7735d82017-11-27 17:04:47 +0900189 if os.path.exists(img.input_name):
Tao Bao886d8832018-02-27 11:46:19 -0800190 print("product.img already exists; no need to rebuild...")
Jaekyun Seokb7735d82017-11-27 17:04:47 +0900191 return img.input_name
192
Tao Bao886d8832018-02-27 11:46:19 -0800193 block_list = OutputFile(
194 output_zip, OPTIONS.input_tmp, "IMAGES", "product.map")
195 CreateImage(
196 OPTIONS.input_tmp, OPTIONS.info_dict, "product", img,
197 block_list=block_list)
Jaekyun Seokb7735d82017-11-27 17:04:47 +0900198 return img.name
199
200
Dario Freni5f681e12018-05-29 13:09:01 +0100201def AddProductServices(output_zip):
Dario Freni924af7d2018-08-17 00:56:14 +0100202 """Turn the contents of PRODUCT_SERVICES into a product_services image and
Dario Freni5f681e12018-05-29 13:09:01 +0100203 store it in output_zip."""
204
205 img = OutputFile(output_zip, OPTIONS.input_tmp, "IMAGES",
Dario Freni924af7d2018-08-17 00:56:14 +0100206 "product_services.img")
Dario Freni5f681e12018-05-29 13:09:01 +0100207 if os.path.exists(img.input_name):
Dario Freni924af7d2018-08-17 00:56:14 +0100208 print("product_services.img already exists; no need to rebuild...")
Dario Freni5f681e12018-05-29 13:09:01 +0100209 return img.input_name
210
211 block_list = OutputFile(
Dario Freni924af7d2018-08-17 00:56:14 +0100212 output_zip, OPTIONS.input_tmp, "IMAGES", "product_services.map")
Dario Freni5f681e12018-05-29 13:09:01 +0100213 CreateImage(
Dario Freni924af7d2018-08-17 00:56:14 +0100214 OPTIONS.input_tmp, OPTIONS.info_dict, "product_services", img,
Dario Freni5f681e12018-05-29 13:09:01 +0100215 block_list=block_list)
216 return img.name
217
218
Bowgo Tsaid624fa62017-11-14 23:42:30 +0800219def AddOdm(output_zip):
220 """Turn the contents of ODM into an odm image and store it in output_zip."""
221
222 img = OutputFile(output_zip, OPTIONS.input_tmp, "IMAGES", "odm.img")
223 if os.path.exists(img.input_name):
224 print("odm.img already exists; no need to rebuild...")
225 return img.input_name
226
227 block_list = OutputFile(
228 output_zip, OPTIONS.input_tmp, "IMAGES", "odm.map")
229 CreateImage(
230 OPTIONS.input_tmp, OPTIONS.info_dict, "odm", img,
231 block_list=block_list)
232 return img.name
233
234
Tao Bao886d8832018-02-27 11:46:19 -0800235def AddDtbo(output_zip):
Tao Baoc633ed02017-05-30 21:46:33 -0700236 """Adds the DTBO image.
237
Tao Bao886d8832018-02-27 11:46:19 -0800238 Uses the image under IMAGES/ if it already exists. Otherwise looks for the
Tao Baoc633ed02017-05-30 21:46:33 -0700239 image under PREBUILT_IMAGES/, signs it as needed, and returns the image name.
240 """
Tao Bao886d8832018-02-27 11:46:19 -0800241 img = OutputFile(output_zip, OPTIONS.input_tmp, "IMAGES", "dtbo.img")
Tao Baoc633ed02017-05-30 21:46:33 -0700242 if os.path.exists(img.input_name):
Tao Bao886d8832018-02-27 11:46:19 -0800243 print("dtbo.img already exists; no need to rebuild...")
Tao Baoc633ed02017-05-30 21:46:33 -0700244 return img.input_name
245
246 dtbo_prebuilt_path = os.path.join(
247 OPTIONS.input_tmp, "PREBUILT_IMAGES", "dtbo.img")
248 assert os.path.exists(dtbo_prebuilt_path)
249 shutil.copy(dtbo_prebuilt_path, img.name)
250
251 # AVB-sign the image as needed.
Bowgo Tsai3e599ea2017-05-26 18:30:04 +0800252 if OPTIONS.info_dict.get("avb_enable") == "true":
Tao Baoc633ed02017-05-30 21:46:33 -0700253 avbtool = os.getenv('AVBTOOL') or OPTIONS.info_dict["avb_avbtool"]
Tao Bao3ebfdde2017-05-23 23:06:55 -0700254 part_size = OPTIONS.info_dict["dtbo_size"]
Tao Baoc633ed02017-05-30 21:46:33 -0700255 # The AVB hash footer will be replaced if already present.
256 cmd = [avbtool, "add_hash_footer", "--image", img.name,
257 "--partition_size", str(part_size), "--partition_name", "dtbo"]
Bowgo Tsai3e599ea2017-05-26 18:30:04 +0800258 common.AppendAVBSigningArgs(cmd, "dtbo")
259 args = OPTIONS.info_dict.get("avb_dtbo_add_hash_footer_args")
Tao Baoc633ed02017-05-30 21:46:33 -0700260 if args and args.strip():
261 cmd.extend(shlex.split(args))
262 p = common.Run(cmd, stdout=subprocess.PIPE)
263 p.communicate()
264 assert p.returncode == 0, \
265 "avbtool add_hash_footer of %s failed" % (img.name,)
266
267 img.Write()
268 return img.name
269
Doug Zongker3c84f562014-07-31 11:06:30 -0700270
Dan Willemsen2ee00d52017-03-05 19:51:56 -0800271def CreateImage(input_dir, info_dict, what, output_file, block_list=None):
Tao Bao89fbb0f2017-01-10 10:47:58 -0800272 print("creating " + what + ".img...")
Doug Zongker3c84f562014-07-31 11:06:30 -0700273
Doug Zongker3c84f562014-07-31 11:06:30 -0700274 image_props = build_image.ImagePropFromGlobalDict(info_dict, what)
275 fstab = info_dict["fstab"]
Tianjie Xucfa86222016-03-07 16:31:19 -0800276 mount_point = "/" + what
277 if fstab and mount_point in fstab:
278 image_props["fs_type"] = fstab[mount_point].fs_type
Doug Zongker3c84f562014-07-31 11:06:30 -0700279
Bryan Henrye6d547d2018-07-31 18:32:00 -0700280 image_props["timestamp"] = FIXED_FILE_TIMESTAMP
Tao Bao822f5842015-09-30 16:01:14 -0700281
Doug Zongker3c84f562014-07-31 11:06:30 -0700282 if what == "system":
283 fs_config_prefix = ""
284 else:
285 fs_config_prefix = what + "_"
286
287 fs_config = os.path.join(
288 input_dir, "META/" + fs_config_prefix + "filesystem_config.txt")
Dan Albert8b72aef2015-03-23 19:13:21 -0700289 if not os.path.exists(fs_config):
290 fs_config = None
Doug Zongker3c84f562014-07-31 11:06:30 -0700291
Ying Wanga2292c92015-03-24 19:07:40 -0700292 # Override values loaded from info_dict.
293 if fs_config:
294 image_props["fs_config"] = fs_config
Ying Wanga2292c92015-03-24 19:07:40 -0700295 if block_list:
Dan Willemsen2ee00d52017-03-05 19:51:56 -0800296 image_props["block_list"] = block_list.name
Ying Wanga2292c92015-03-24 19:07:40 -0700297
Tao Baod86e3112017-09-22 15:45:33 -0700298 # Use repeatable ext4 FS UUID and hash_seed UUID (based on partition name and
299 # build fingerprint).
300 uuid_seed = what + "-"
301 if "build.prop" in info_dict:
302 build_prop = info_dict["build.prop"]
303 if "ro.build.fingerprint" in build_prop:
304 uuid_seed += build_prop["ro.build.fingerprint"]
305 elif "ro.build.thumbprint" in build_prop:
306 uuid_seed += build_prop["ro.build.thumbprint"]
307 image_props["uuid"] = str(uuid.uuid5(uuid.NAMESPACE_URL, uuid_seed))
308 hash_seed = "hash_seed-" + uuid_seed
309 image_props["hash_seed"] = str(uuid.uuid5(uuid.NAMESPACE_URL, hash_seed))
310
Tao Baoc6bd70a2018-09-27 16:58:00 -0700311 build_image.BuildImage(
312 os.path.join(input_dir, what.upper()), image_props, output_file.name)
Doug Zongker3c84f562014-07-31 11:06:30 -0700313
Dan Willemsen2ee00d52017-03-05 19:51:56 -0800314 output_file.Write()
315 if block_list:
316 block_list.Write()
317
Tao Bao35f4ebc2018-09-27 15:31:11 -0700318 # Set the '_image_blocks' that excludes the verity metadata blocks of the
319 # given image. When AVB is enabled, this size is the max image size returned
320 # by the AVB tool.
Tianjie Xuf1a13182017-01-19 17:39:30 -0800321 is_verity_partition = "verity_block_device" in image_props
Tianjie Xu6b2e1552017-06-01 11:32:32 -0700322 verity_supported = (image_props.get("verity") == "true" or
Bowgo Tsai3e599ea2017-05-26 18:30:04 +0800323 image_props.get("avb_enable") == "true")
Tianjie Xu6b2e1552017-06-01 11:32:32 -0700324 is_avb_enable = image_props.get("avb_hashtree_enable") == "true"
325 if verity_supported and (is_verity_partition or is_avb_enable):
Tao Bao35f4ebc2018-09-27 15:31:11 -0700326 image_size = image_props.get("image_size")
327 if image_size:
328 image_blocks_key = what + "_image_blocks"
329 info_dict[image_blocks_key] = int(image_size) / 4096 - 1
Tianjie Xuf1a13182017-01-19 17:39:30 -0800330
Doug Zongker3c84f562014-07-31 11:06:30 -0700331
Tao Bao886d8832018-02-27 11:46:19 -0800332def AddUserdata(output_zip):
Ying Wang2a048392015-06-25 13:56:53 -0700333 """Create a userdata image and store it in output_zip.
334
335 In most case we just create and store an empty userdata.img;
336 But the invoker can also request to create userdata.img with real
337 data from the target files, by setting "userdata_img_with_data=true"
338 in OPTIONS.info_dict.
339 """
Doug Zongker3c84f562014-07-31 11:06:30 -0700340
Tao Bao886d8832018-02-27 11:46:19 -0800341 img = OutputFile(output_zip, OPTIONS.input_tmp, "IMAGES", "userdata.img")
Dan Willemsen2ee00d52017-03-05 19:51:56 -0800342 if os.path.exists(img.input_name):
Tao Bao886d8832018-02-27 11:46:19 -0800343 print("userdata.img already exists; no need to rebuild...")
Michael Runge2e0d8fc2014-11-13 21:41:08 -0800344 return
345
Elliott Hughes305b0882016-06-15 17:04:54 -0700346 # Skip userdata.img if no size.
Tao Bao2c15d9e2015-07-09 11:51:16 -0700347 image_props = build_image.ImagePropFromGlobalDict(OPTIONS.info_dict, "data")
Elliott Hughes305b0882016-06-15 17:04:54 -0700348 if not image_props.get("partition_size"):
Doug Zongker3c84f562014-07-31 11:06:30 -0700349 return
350
Tao Bao89fbb0f2017-01-10 10:47:58 -0800351 print("creating userdata.img...")
Doug Zongker3c84f562014-07-31 11:06:30 -0700352
Bryan Henrye6d547d2018-07-31 18:32:00 -0700353 image_props["timestamp"] = FIXED_FILE_TIMESTAMP
Tao Bao822f5842015-09-30 16:01:14 -0700354
Tao Baofa863c82017-05-23 23:49:03 -0700355 if OPTIONS.info_dict.get("userdata_img_with_data") == "true":
356 user_dir = os.path.join(OPTIONS.input_tmp, "DATA")
Ying Wang2a048392015-06-25 13:56:53 -0700357 else:
Tao Bao1c830bf2017-12-25 10:43:47 -0800358 user_dir = common.MakeTempDir()
Ying Wang2a048392015-06-25 13:56:53 -0700359
Doug Zongker3c84f562014-07-31 11:06:30 -0700360 fstab = OPTIONS.info_dict["fstab"]
361 if fstab:
Dan Albert8b72aef2015-03-23 19:13:21 -0700362 image_props["fs_type"] = fstab["/data"].fs_type
Tao Baoc6bd70a2018-09-27 16:58:00 -0700363 build_image.BuildImage(user_dir, image_props, img.name)
Doug Zongker3c84f562014-07-31 11:06:30 -0700364
365 common.CheckSize(img.name, "userdata.img", OPTIONS.info_dict)
Dan Willemsen2ee00d52017-03-05 19:51:56 -0800366 img.Write()
Doug Zongker3c84f562014-07-31 11:06:30 -0700367
368
Tao Bao3e53ef72018-07-22 21:57:56 -0700369def AppendVBMetaArgsForPartition(cmd, partition, image):
370 """Appends the VBMeta arguments for partition.
Bowgo Tsai3e599ea2017-05-26 18:30:04 +0800371
Tao Bao3e53ef72018-07-22 21:57:56 -0700372 It sets up the VBMeta argument by including the partition descriptor from the
373 given 'image', or by configuring the partition as a chained partition.
374
375 Args:
376 cmd: A list of command args that will be used to generate the vbmeta image.
377 The argument for the partition will be appended to the list.
378 partition: The name of the partition (e.g. "system").
379 image: The path to the partition image.
380 """
Bowgo Tsai3e599ea2017-05-26 18:30:04 +0800381 # Check if chain partition is used.
382 key_path = OPTIONS.info_dict.get("avb_" + partition + "_key_path")
383 if key_path:
Tao Bao02a08592018-07-22 12:40:45 -0700384 chained_partition_arg = common.GetAvbChainedPartitionArg(
385 partition, OPTIONS.info_dict)
386 cmd.extend(["--chain_partition", chained_partition_arg])
Bowgo Tsai3e599ea2017-05-26 18:30:04 +0800387 else:
Tao Bao3e53ef72018-07-22 21:57:56 -0700388 cmd.extend(["--include_descriptors_from_image", image])
Bowgo Tsai3e599ea2017-05-26 18:30:04 +0800389
390
Tao Bao744c4c72018-08-20 21:09:07 -0700391def AddVBMeta(output_zip, partitions, name, needed_partitions):
392 """Creates a VBMeta image and stores it in output_zip.
393
394 It generates the requested VBMeta image. The requested image could be for
395 top-level or chained VBMeta image, which is determined based on the name.
Tao Baobf70c312017-07-11 17:27:55 -0700396
397 Args:
398 output_zip: The output zip file, which needs to be already open.
399 partitions: A dict that's keyed by partition names with image paths as
Tao Bao3e53ef72018-07-22 21:57:56 -0700400 values. Only valid partition names are accepted, as listed in
401 common.AVB_PARTITIONS.
Tao Bao744c4c72018-08-20 21:09:07 -0700402 name: Name of the VBMeta partition, e.g. 'vbmeta', 'vbmeta_mainline'.
403 needed_partitions: Partitions whose descriptors should be included into the
404 generated VBMeta image.
405
406 Raises:
407 AssertionError: On invalid input args.
Tao Baobf70c312017-07-11 17:27:55 -0700408 """
Tao Bao744c4c72018-08-20 21:09:07 -0700409 assert needed_partitions, "Needed partitions must be specified"
410
411 img = OutputFile(
412 output_zip, OPTIONS.input_tmp, "IMAGES", "{}.img".format(name))
Tao Bao262bf3f2017-07-11 17:27:55 -0700413 if os.path.exists(img.input_name):
Tao Bao744c4c72018-08-20 21:09:07 -0700414 print("{}.img already exists; not rebuilding...".format(name))
Tao Bao262bf3f2017-07-11 17:27:55 -0700415 return img.input_name
416
Tao Baoc633ed02017-05-30 21:46:33 -0700417 avbtool = os.getenv('AVBTOOL') or OPTIONS.info_dict["avb_avbtool"]
Bowgo Tsai3e599ea2017-05-26 18:30:04 +0800418 cmd = [avbtool, "make_vbmeta_image", "--output", img.name]
Tao Bao744c4c72018-08-20 21:09:07 -0700419 common.AppendAVBSigningArgs(cmd, name)
Bowgo Tsai3e599ea2017-05-26 18:30:04 +0800420
Tao Baobf70c312017-07-11 17:27:55 -0700421 for partition, path in partitions.items():
Tao Bao744c4c72018-08-20 21:09:07 -0700422 if partition not in needed_partitions:
423 continue
Tao Bao3e53ef72018-07-22 21:57:56 -0700424 assert partition in common.AVB_PARTITIONS, \
425 'Unknown partition: {}'.format(partition)
426 assert os.path.exists(path), \
427 'Failed to find {} for {}'.format(path, partition)
428 AppendVBMetaArgsForPartition(cmd, partition, path)
Bowgo Tsai3e599ea2017-05-26 18:30:04 +0800429
Tao Bao744c4c72018-08-20 21:09:07 -0700430 args = OPTIONS.info_dict.get("avb_{}_args".format(name))
David Zeuthen2ce63ed2016-09-15 13:43:54 -0400431 if args and args.strip():
Tao Bao9a5f4192017-07-20 23:51:16 -0700432 split_args = shlex.split(args)
433 for index, arg in enumerate(split_args[:-1]):
434 # Sanity check that the image file exists. Some images might be defined
435 # as a path relative to source tree, which may not be available at the
436 # same location when running this script (we have the input target_files
437 # zip only). For such cases, we additionally scan other locations (e.g.
438 # IMAGES/, RADIO/, etc) before bailing out.
439 if arg == '--include_descriptors_from_image':
440 image_path = split_args[index + 1]
441 if os.path.exists(image_path):
442 continue
443 found = False
Tao Bao36d7c562018-04-17 18:26:41 -0700444 for dir_name in ['IMAGES', 'RADIO', 'PREBUILT_IMAGES']:
Tao Bao9a5f4192017-07-20 23:51:16 -0700445 alt_path = os.path.join(
Tao Bao6b9fef52017-12-01 16:13:22 -0800446 OPTIONS.input_tmp, dir_name, os.path.basename(image_path))
Tao Bao9a5f4192017-07-20 23:51:16 -0700447 if os.path.exists(alt_path):
448 split_args[index + 1] = alt_path
449 found = True
450 break
Tao Bao744c4c72018-08-20 21:09:07 -0700451 assert found, 'Failed to find {}'.format(image_path)
Tao Bao9a5f4192017-07-20 23:51:16 -0700452 cmd.extend(split_args)
Bowgo Tsai3e599ea2017-05-26 18:30:04 +0800453
Bryan Henry69d3feb2018-04-14 23:07:46 -0700454 p = common.Run(cmd, stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
455 stdoutdata, _ = p.communicate()
456 assert p.returncode == 0, \
457 "avbtool make_vbmeta_image failed:\n{}".format(stdoutdata)
Dan Willemsen2ee00d52017-03-05 19:51:56 -0800458 img.Write()
David Zeuthen2ce63ed2016-09-15 13:43:54 -0400459
460
Tao Bao886d8832018-02-27 11:46:19 -0800461def AddPartitionTable(output_zip):
David Zeuthen25328622016-04-08 15:08:03 -0400462 """Create a partition table image and store it in output_zip."""
463
Tao Bao886d8832018-02-27 11:46:19 -0800464 img = OutputFile(
465 output_zip, OPTIONS.input_tmp, "IMAGES", "partition-table.img")
466 bpt = OutputFile(
Bryan Henryf130a232018-04-26 11:59:33 -0700467 output_zip, OPTIONS.input_tmp, "META", "partition-table.bpt")
David Zeuthen25328622016-04-08 15:08:03 -0400468
469 # use BPTTOOL from environ, or "bpttool" if empty or not set.
470 bpttool = os.getenv("BPTTOOL") or "bpttool"
Dan Willemsen2ee00d52017-03-05 19:51:56 -0800471 cmd = [bpttool, "make_table", "--output_json", bpt.name,
472 "--output_gpt", img.name]
David Zeuthen25328622016-04-08 15:08:03 -0400473 input_files_str = OPTIONS.info_dict["board_bpt_input_files"]
474 input_files = input_files_str.split(" ")
475 for i in input_files:
476 cmd.extend(["--input", i])
477 disk_size = OPTIONS.info_dict.get("board_bpt_disk_size")
478 if disk_size:
479 cmd.extend(["--disk_size", disk_size])
480 args = OPTIONS.info_dict.get("board_bpt_make_table_args")
481 if args:
482 cmd.extend(shlex.split(args))
483
Bryan Henry69d3feb2018-04-14 23:07:46 -0700484 p = common.Run(cmd, stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
485 stdoutdata, _ = p.communicate()
486 assert p.returncode == 0, \
487 "bpttool make_table failed:\n{}".format(stdoutdata)
David Zeuthen25328622016-04-08 15:08:03 -0400488
Dan Willemsen2ee00d52017-03-05 19:51:56 -0800489 img.Write()
490 bpt.Write()
David Zeuthen25328622016-04-08 15:08:03 -0400491
492
Tao Bao886d8832018-02-27 11:46:19 -0800493def AddCache(output_zip):
Doug Zongker3c84f562014-07-31 11:06:30 -0700494 """Create an empty cache image and store it in output_zip."""
495
Tao Bao886d8832018-02-27 11:46:19 -0800496 img = OutputFile(output_zip, OPTIONS.input_tmp, "IMAGES", "cache.img")
Dan Willemsen2ee00d52017-03-05 19:51:56 -0800497 if os.path.exists(img.input_name):
Tao Bao886d8832018-02-27 11:46:19 -0800498 print("cache.img already exists; no need to rebuild...")
Michael Runge2e0d8fc2014-11-13 21:41:08 -0800499 return
500
Tao Bao2c15d9e2015-07-09 11:51:16 -0700501 image_props = build_image.ImagePropFromGlobalDict(OPTIONS.info_dict, "cache")
Doug Zongker3c84f562014-07-31 11:06:30 -0700502 # The build system has to explicitly request for cache.img.
503 if "fs_type" not in image_props:
504 return
505
Tao Bao89fbb0f2017-01-10 10:47:58 -0800506 print("creating cache.img...")
Doug Zongker3c84f562014-07-31 11:06:30 -0700507
Bryan Henrye6d547d2018-07-31 18:32:00 -0700508 image_props["timestamp"] = FIXED_FILE_TIMESTAMP
Tao Bao822f5842015-09-30 16:01:14 -0700509
Tao Bao1c830bf2017-12-25 10:43:47 -0800510 user_dir = common.MakeTempDir()
Doug Zongker3c84f562014-07-31 11:06:30 -0700511
512 fstab = OPTIONS.info_dict["fstab"]
513 if fstab:
Dan Albert8b72aef2015-03-23 19:13:21 -0700514 image_props["fs_type"] = fstab["/cache"].fs_type
Tao Baoc6bd70a2018-09-27 16:58:00 -0700515 build_image.BuildImage(user_dir, image_props, img.name)
Doug Zongker3c84f562014-07-31 11:06:30 -0700516
517 common.CheckSize(img.name, "cache.img", OPTIONS.info_dict)
Dan Willemsen2ee00d52017-03-05 19:51:56 -0800518 img.Write()
Doug Zongker3c84f562014-07-31 11:06:30 -0700519
520
Tao Bao5277d102018-04-17 23:47:21 -0700521def CheckAbOtaImages(output_zip, ab_partitions):
522 """Checks that all the listed A/B partitions have their images available.
Tao Baobea20ac2018-01-17 17:57:49 -0800523
Tao Bao5277d102018-04-17 23:47:21 -0700524 The images need to be available under IMAGES/ or RADIO/, with the former takes
525 a priority.
Tao Baobea20ac2018-01-17 17:57:49 -0800526
527 Args:
528 output_zip: The output zip file (needs to be already open), or None to
Tao Bao5277d102018-04-17 23:47:21 -0700529 find images in OPTIONS.input_tmp/.
Tao Baobea20ac2018-01-17 17:57:49 -0800530 ab_partitions: The list of A/B partitions.
531
532 Raises:
533 AssertionError: If it can't find an image.
534 """
535 for partition in ab_partitions:
536 img_name = partition.strip() + ".img"
Tao Baobea20ac2018-01-17 17:57:49 -0800537
Tao Baoa2ff4c92018-01-17 12:14:43 -0800538 # Assert that the image is present under IMAGES/ now.
Tao Baobea20ac2018-01-17 17:57:49 -0800539 if output_zip:
540 # Zip spec says: All slashes MUST be forward slashes.
Tao Bao5277d102018-04-17 23:47:21 -0700541 images_path = "IMAGES/" + img_name
542 radio_path = "RADIO/" + img_name
543 available = (images_path in output_zip.namelist() or
544 radio_path in output_zip.namelist())
Tao Baobea20ac2018-01-17 17:57:49 -0800545 else:
Tao Bao5277d102018-04-17 23:47:21 -0700546 images_path = os.path.join(OPTIONS.input_tmp, "IMAGES", img_name)
547 radio_path = os.path.join(OPTIONS.input_tmp, "RADIO", img_name)
548 available = os.path.exists(images_path) or os.path.exists(radio_path)
549
550 assert available, "Failed to find " + img_name
Tao Baobea20ac2018-01-17 17:57:49 -0800551
552
Tianjie Xu4c05f4a2018-09-14 16:24:41 -0700553def AddCareMapForAbOta(output_zip, ab_partitions, image_paths):
Tianjie Xu861f4132018-09-12 11:49:33 -0700554 """Generates and adds care_map.pb for a/b partition that has care_map.
Tao Baobea20ac2018-01-17 17:57:49 -0800555
556 Args:
557 output_zip: The output zip file (needs to be already open), or None to
Tianjie Xu4c05f4a2018-09-14 16:24:41 -0700558 write care_map.pb to OPTIONS.input_tmp/.
Tao Baobea20ac2018-01-17 17:57:49 -0800559 ab_partitions: The list of A/B partitions.
560 image_paths: A map from the partition name to the image path.
561 """
562 care_map_list = []
563 for partition in ab_partitions:
564 partition = partition.strip()
Tianjie Xu861f4132018-09-12 11:49:33 -0700565 if partition not in common.PARTITIONS_WITH_CARE_MAP:
Tao Baoa2ff4c92018-01-17 12:14:43 -0800566 continue
567
568 verity_block_device = "{}_verity_block_device".format(partition)
569 avb_hashtree_enable = "avb_{}_hashtree_enable".format(partition)
570 if (verity_block_device in OPTIONS.info_dict or
571 OPTIONS.info_dict.get(avb_hashtree_enable) == "true"):
572 image_path = image_paths[partition]
573 assert os.path.exists(image_path)
574 care_map_list += GetCareMap(partition, image_path)
Tao Baobea20ac2018-01-17 17:57:49 -0800575
Tianjie Xu861f4132018-09-12 11:49:33 -0700576 # adds fingerprint field to the care_map
577 build_props = OPTIONS.info_dict.get(partition + ".build.prop", {})
578 prop_name_list = ["ro.{}.build.fingerprint".format(partition),
579 "ro.{}.build.thumbprint".format(partition)]
580
581 present_props = [x for x in prop_name_list if x in build_props]
582 if not present_props:
583 print("Warning: fingerprint is not present for partition {}".
584 format(partition))
585 property_id, fingerprint = "unknown", "unknown"
586 else:
587 property_id = present_props[0]
588 fingerprint = build_props[property_id]
589 care_map_list += [property_id, fingerprint]
590
Tianjie Xuccbae482018-08-15 14:28:27 -0700591 if not care_map_list:
592 return
593
594 # Converts the list into proto buf message by calling care_map_generator; and
595 # writes the result to a temp file.
596 temp_care_map_text = common.MakeTempFile(prefix="caremap_text-",
597 suffix=".txt")
598 with open(temp_care_map_text, 'w') as text_file:
599 text_file.write('\n'.join(care_map_list))
600
Tianjie Xu861f4132018-09-12 11:49:33 -0700601 temp_care_map = common.MakeTempFile(prefix="caremap-", suffix=".pb")
602 care_map_gen_cmd = ["care_map_generator", temp_care_map_text, temp_care_map]
Tianjie Xuccbae482018-08-15 14:28:27 -0700603 p = common.Run(care_map_gen_cmd, stdout=subprocess.PIPE,
604 stderr=subprocess.STDOUT)
605 output, _ = p.communicate()
Tianjie Xuccbae482018-08-15 14:28:27 -0700606 if OPTIONS.verbose:
607 print(output.rstrip())
Tianjie Xu861f4132018-09-12 11:49:33 -0700608 assert p.returncode == 0, "Failed to generate the care_map proto message."
Tianjie Xuccbae482018-08-15 14:28:27 -0700609
Tianjie Xu4c05f4a2018-09-14 16:24:41 -0700610 care_map_path = "META/care_map.pb"
Tianjie Xuccbae482018-08-15 14:28:27 -0700611 if output_zip and care_map_path not in output_zip.namelist():
612 common.ZipWrite(output_zip, temp_care_map, arcname=care_map_path)
613 else:
614 shutil.copy(temp_care_map, os.path.join(OPTIONS.input_tmp, care_map_path))
615 if output_zip:
616 OPTIONS.replace_updated_files_list.append(care_map_path)
Tao Baobea20ac2018-01-17 17:57:49 -0800617
618
619def AddPackRadioImages(output_zip, images):
620 """Copies images listed in META/pack_radioimages.txt from RADIO/ to IMAGES/.
621
622 Args:
623 output_zip: The output zip file (needs to be already open), or None to
624 write images to OPTIONS.input_tmp/.
625 images: A list of image names.
626
627 Raises:
628 AssertionError: If a listed image can't be found.
629 """
630 for image in images:
631 img_name = image.strip()
632 _, ext = os.path.splitext(img_name)
633 if not ext:
634 img_name += ".img"
Tao Baoa2ff4c92018-01-17 12:14:43 -0800635
Tao Baobea20ac2018-01-17 17:57:49 -0800636 prebuilt_path = os.path.join(OPTIONS.input_tmp, "IMAGES", img_name)
637 if os.path.exists(prebuilt_path):
638 print("%s already exists, no need to overwrite..." % (img_name,))
639 continue
640
641 img_radio_path = os.path.join(OPTIONS.input_tmp, "RADIO", img_name)
642 assert os.path.exists(img_radio_path), \
643 "Failed to find %s at %s" % (img_name, img_radio_path)
Tao Baoa2ff4c92018-01-17 12:14:43 -0800644
Tao Baobea20ac2018-01-17 17:57:49 -0800645 if output_zip:
Tao Baoa2ff4c92018-01-17 12:14:43 -0800646 common.ZipWrite(output_zip, img_radio_path, "IMAGES/" + img_name)
Tao Baobea20ac2018-01-17 17:57:49 -0800647 else:
648 shutil.copy(img_radio_path, prebuilt_path)
649
650
David Anderson1ef03e22018-08-30 13:11:47 -0700651def AddSuperEmpty(output_zip):
652 """Create a super_empty.img and store it in output_zip."""
653
654 img = OutputFile(output_zip, OPTIONS.input_tmp, "IMAGES", "super_empty.img")
655 cmd = [OPTIONS.info_dict.get('lpmake')]
656 cmd += shlex.split(OPTIONS.info_dict.get('lpmake_args').strip())
657 cmd += ['--output', img.name]
658
659 p = common.Run(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
660 stdoutdata, _ = p.communicate()
661 assert p.returncode == 0, \
662 "lpmake tool failed:\n{}".format(stdoutdata)
663
664 img.Write()
665
666
Tianjie Xu9ac4cb02017-06-09 16:58:03 -0700667def ReplaceUpdatedFiles(zip_filename, files_list):
Tao Bao89d7ab22017-12-14 17:05:33 -0800668 """Updates all the ZIP entries listed in files_list.
Tianjie Xu38af07f2017-05-25 17:38:53 -0700669
Tianjie Xu4c05f4a2018-09-14 16:24:41 -0700670 For now the list includes META/care_map.pb, and the related files under
Tianjie Xu9ac4cb02017-06-09 16:58:03 -0700671 SYSTEM/ after rebuilding recovery.
672 """
Tao Bao89d7ab22017-12-14 17:05:33 -0800673 common.ZipDelete(zip_filename, files_list)
Tianjie Xu38af07f2017-05-25 17:38:53 -0700674 output_zip = zipfile.ZipFile(zip_filename, "a",
675 compression=zipfile.ZIP_DEFLATED,
676 allowZip64=True)
Tianjie Xu9ac4cb02017-06-09 16:58:03 -0700677 for item in files_list:
Tianjie Xu38af07f2017-05-25 17:38:53 -0700678 file_path = os.path.join(OPTIONS.input_tmp, item)
679 assert os.path.exists(file_path)
680 common.ZipWrite(output_zip, file_path, arcname=item)
681 common.ZipClose(output_zip)
682
683
Doug Zongker3c84f562014-07-31 11:06:30 -0700684def AddImagesToTargetFiles(filename):
Tao Baoae396d92017-11-20 11:56:43 -0800685 """Creates and adds images (boot/recovery/system/...) to a target_files.zip.
686
687 It works with either a zip file (zip mode), or a directory that contains the
688 files to be packed into a target_files.zip (dir mode). The latter is used when
689 being called from build/make/core/Makefile.
690
691 The images will be created under IMAGES/ in the input target_files.zip.
692
693 Args:
Tao Baodba59ee2018-01-09 13:21:02 -0800694 filename: the target_files.zip, or the zip root directory.
Tao Baoae396d92017-11-20 11:56:43 -0800695 """
Dan Willemsen2ee00d52017-03-05 19:51:56 -0800696 if os.path.isdir(filename):
697 OPTIONS.input_tmp = os.path.abspath(filename)
Dan Willemsen2ee00d52017-03-05 19:51:56 -0800698 else:
Tao Baodba59ee2018-01-09 13:21:02 -0800699 OPTIONS.input_tmp = common.UnzipTemp(filename)
Doug Zongkerfc44a512014-08-26 13:10:25 -0700700
Michael Runge2e0d8fc2014-11-13 21:41:08 -0800701 if not OPTIONS.add_missing:
Dan Willemsen2ee00d52017-03-05 19:51:56 -0800702 if os.path.isdir(os.path.join(OPTIONS.input_tmp, "IMAGES")):
703 print("target_files appears to already contain images.")
704 sys.exit(1)
Doug Zongkerfc44a512014-08-26 13:10:25 -0700705
Tao Bao410ad8b2018-08-24 12:08:38 -0700706 OPTIONS.info_dict = common.LoadInfoDict(OPTIONS.input_tmp, repacking=True)
Tao Baodba59ee2018-01-09 13:21:02 -0800707
708 has_recovery = OPTIONS.info_dict.get("no_recovery") != "true"
709
Dario Freni924af7d2018-08-17 00:56:14 +0100710 # {vendor,odm,product,product_services}.img are unlike system.img or
Dario Freni5f681e12018-05-29 13:09:01 +0100711 # system_other.img. Because it could be built from source, or dropped into
712 # target_files.zip as a prebuilt blob. We consider either of them as
Dario Freni924af7d2018-08-17 00:56:14 +0100713 # {vendor,product,product_services}.img being available, which could be
Dario Freni5f681e12018-05-29 13:09:01 +0100714 # used when generating vbmeta.img for AVB.
Tao Baob22afea2017-09-12 12:39:09 -0700715 has_vendor = (os.path.isdir(os.path.join(OPTIONS.input_tmp, "VENDOR")) or
716 os.path.exists(os.path.join(OPTIONS.input_tmp, "IMAGES",
717 "vendor.img")))
Bowgo Tsaid624fa62017-11-14 23:42:30 +0800718 has_odm = (os.path.isdir(os.path.join(OPTIONS.input_tmp, "ODM")) or
Tao Bao744c4c72018-08-20 21:09:07 -0700719 os.path.exists(os.path.join(OPTIONS.input_tmp, "IMAGES",
720 "odm.img")))
Jaekyun Seokb7735d82017-11-27 17:04:47 +0900721 has_product = (os.path.isdir(os.path.join(OPTIONS.input_tmp, "PRODUCT")) or
722 os.path.exists(os.path.join(OPTIONS.input_tmp, "IMAGES",
723 "product.img")))
Yifan Hongebc041a2018-07-26 16:02:52 -0700724 has_product_services = (os.path.isdir(os.path.join(OPTIONS.input_tmp,
Yifan Hong35be6ca2018-08-17 21:01:25 +0000725 "PRODUCT_SERVICES")) or
Yifan Hongebc041a2018-07-26 16:02:52 -0700726 os.path.exists(os.path.join(OPTIONS.input_tmp,
727 "IMAGES",
Dario Freni924af7d2018-08-17 00:56:14 +0100728 "product_services.img")))
Dan Willemsen2ee00d52017-03-05 19:51:56 -0800729 has_system_other = os.path.isdir(os.path.join(OPTIONS.input_tmp,
730 "SYSTEM_OTHER"))
Doug Zongker3c84f562014-07-31 11:06:30 -0700731
Tao Baodba59ee2018-01-09 13:21:02 -0800732 # Set up the output destination. It writes to the given directory for dir
733 # mode; otherwise appends to the given ZIP.
734 if os.path.isdir(filename):
735 output_zip = None
736 else:
Dan Willemsen2ee00d52017-03-05 19:51:56 -0800737 output_zip = zipfile.ZipFile(filename, "a",
738 compression=zipfile.ZIP_DEFLATED,
739 allowZip64=True)
Tao Baoae396d92017-11-20 11:56:43 -0800740
741 # Always make input_tmp/IMAGES available, since we may stage boot / recovery
742 # images there even under zip mode. The directory will be cleaned up as part
743 # of OPTIONS.input_tmp.
744 images_dir = os.path.join(OPTIONS.input_tmp, "IMAGES")
745 if not os.path.isdir(images_dir):
746 os.makedirs(images_dir)
Doug Zongker3c84f562014-07-31 11:06:30 -0700747
Tao Baobf70c312017-07-11 17:27:55 -0700748 # A map between partition names and their paths, which could be used when
749 # generating AVB vbmeta image.
750 partitions = dict()
751
Doug Zongkerfc44a512014-08-26 13:10:25 -0700752 def banner(s):
Tao Bao89fbb0f2017-01-10 10:47:58 -0800753 print("\n\n++++ " + s + " ++++\n\n")
Doug Zongker3c84f562014-07-31 11:06:30 -0700754
Tao Bao262bf3f2017-07-11 17:27:55 -0700755 banner("boot")
756 # common.GetBootableImage() returns the image directly if present.
757 boot_image = common.GetBootableImage(
758 "IMAGES/boot.img", "boot.img", OPTIONS.input_tmp, "BOOT")
759 # boot.img may be unavailable in some targets (e.g. aosp_arm64).
760 if boot_image:
Tao Baobf70c312017-07-11 17:27:55 -0700761 partitions['boot'] = os.path.join(OPTIONS.input_tmp, "IMAGES", "boot.img")
762 if not os.path.exists(partitions['boot']):
Tao Bao262bf3f2017-07-11 17:27:55 -0700763 boot_image.WriteToDir(OPTIONS.input_tmp)
Dan Willemsen2ee00d52017-03-05 19:51:56 -0800764 if output_zip:
765 boot_image.AddToZip(output_zip)
Doug Zongker3c84f562014-07-31 11:06:30 -0700766
Michael Runge2e0d8fc2014-11-13 21:41:08 -0800767 recovery_image = None
Tao Baodb45efa2015-10-27 19:25:18 -0700768 if has_recovery:
769 banner("recovery")
Tao Bao262bf3f2017-07-11 17:27:55 -0700770 recovery_image = common.GetBootableImage(
771 "IMAGES/recovery.img", "recovery.img", OPTIONS.input_tmp, "RECOVERY")
772 assert recovery_image, "Failed to create recovery.img."
Tao Baobf70c312017-07-11 17:27:55 -0700773 partitions['recovery'] = os.path.join(
Tao Bao262bf3f2017-07-11 17:27:55 -0700774 OPTIONS.input_tmp, "IMAGES", "recovery.img")
Tao Baobf70c312017-07-11 17:27:55 -0700775 if not os.path.exists(partitions['recovery']):
Tao Bao262bf3f2017-07-11 17:27:55 -0700776 recovery_image.WriteToDir(OPTIONS.input_tmp)
777 if output_zip:
778 recovery_image.AddToZip(output_zip)
Doug Zongker3c84f562014-07-31 11:06:30 -0700779
Tao Baod42e97e2016-11-30 12:11:57 -0800780 banner("recovery (two-step image)")
781 # The special recovery.img for two-step package use.
782 recovery_two_step_image = common.GetBootableImage(
783 "IMAGES/recovery-two-step.img", "recovery-two-step.img",
784 OPTIONS.input_tmp, "RECOVERY", two_step_image=True)
Tao Bao262bf3f2017-07-11 17:27:55 -0700785 assert recovery_two_step_image, "Failed to create recovery-two-step.img."
786 recovery_two_step_image_path = os.path.join(
787 OPTIONS.input_tmp, "IMAGES", "recovery-two-step.img")
788 if not os.path.exists(recovery_two_step_image_path):
789 recovery_two_step_image.WriteToDir(OPTIONS.input_tmp)
Dan Willemsen2ee00d52017-03-05 19:51:56 -0800790 if output_zip:
791 recovery_two_step_image.AddToZip(output_zip)
Tao Baod42e97e2016-11-30 12:11:57 -0800792
Doug Zongkerfc44a512014-08-26 13:10:25 -0700793 banner("system")
Tao Baobea20ac2018-01-17 17:57:49 -0800794 partitions['system'] = AddSystem(
Tao Baoc633ed02017-05-30 21:46:33 -0700795 output_zip, recovery_img=recovery_image, boot_img=boot_image)
Tao Baobf70c312017-07-11 17:27:55 -0700796
Doug Zongkerfc44a512014-08-26 13:10:25 -0700797 if has_vendor:
798 banner("vendor")
Tao Baobea20ac2018-01-17 17:57:49 -0800799 partitions['vendor'] = AddVendor(output_zip)
Tao Baobf70c312017-07-11 17:27:55 -0700800
Jaekyun Seokb7735d82017-11-27 17:04:47 +0900801 if has_product:
802 banner("product")
803 partitions['product'] = AddProduct(output_zip)
804
Yifan Hongebc041a2018-07-26 16:02:52 -0700805 if has_product_services:
Dario Freni924af7d2018-08-17 00:56:14 +0100806 banner("product_services")
807 partitions['product_services'] = AddProductServices(output_zip)
Dario Freni5f681e12018-05-29 13:09:01 +0100808
Bowgo Tsaid624fa62017-11-14 23:42:30 +0800809 if has_odm:
810 banner("odm")
811 partitions['odm'] = AddOdm(output_zip)
812
Alex Light4e358ab2016-06-16 14:47:10 -0700813 if has_system_other:
814 banner("system_other")
815 AddSystemOther(output_zip)
Tao Baobf70c312017-07-11 17:27:55 -0700816
Tianjie Xub48589a2016-08-03 19:21:52 -0700817 if not OPTIONS.is_signing:
818 banner("userdata")
819 AddUserdata(output_zip)
820 banner("cache")
821 AddCache(output_zip)
Tao Baoc633ed02017-05-30 21:46:33 -0700822
823 if OPTIONS.info_dict.get("board_bpt_enable") == "true":
David Zeuthen25328622016-04-08 15:08:03 -0400824 banner("partition-table")
825 AddPartitionTable(output_zip)
Tao Baoc633ed02017-05-30 21:46:33 -0700826
Tao Baoc633ed02017-05-30 21:46:33 -0700827 if OPTIONS.info_dict.get("has_dtbo") == "true":
828 banner("dtbo")
Tao Baobf70c312017-07-11 17:27:55 -0700829 partitions['dtbo'] = AddDtbo(output_zip)
Tao Baoc633ed02017-05-30 21:46:33 -0700830
Bowgo Tsai3e599ea2017-05-26 18:30:04 +0800831 if OPTIONS.info_dict.get("avb_enable") == "true":
Tao Bao744c4c72018-08-20 21:09:07 -0700832 # vbmeta_partitions includes the partitions that should be included into
833 # top-level vbmeta.img, which are the ones that are not included in any
834 # chained VBMeta image plus the chained VBMeta images themselves.
835 vbmeta_partitions = common.AVB_PARTITIONS[:]
836
837 vbmeta_mainline = OPTIONS.info_dict.get("avb_vbmeta_mainline", "").strip()
838 if vbmeta_mainline:
839 banner("vbmeta_mainline")
840 AddVBMeta(
841 output_zip, partitions, "vbmeta_mainline", vbmeta_mainline.split())
842 vbmeta_partitions = [
843 item for item in vbmeta_partitions
844 if item not in vbmeta_mainline.split()]
845 vbmeta_partitions.append("vbmeta_mainline")
846
847 vbmeta_vendor = OPTIONS.info_dict.get("avb_vbmeta_vendor", "").strip()
848 if vbmeta_vendor:
849 banner("vbmeta_vendor")
850 AddVBMeta(
851 output_zip, partitions, "vbmeta_vendor", vbmeta_vendor.split())
852 vbmeta_partitions = [
853 item for item in vbmeta_partitions
854 if item not in vbmeta_vendor.split()]
855 vbmeta_partitions.append("vbmeta_vendor")
856
David Zeuthen2ce63ed2016-09-15 13:43:54 -0400857 banner("vbmeta")
Tao Bao744c4c72018-08-20 21:09:07 -0700858 AddVBMeta(output_zip, partitions, "vbmeta", vbmeta_partitions)
Doug Zongker3c84f562014-07-31 11:06:30 -0700859
David Anderson1ef03e22018-08-30 13:11:47 -0700860 if OPTIONS.info_dict.get("super_size"):
861 banner("super_empty")
862 AddSuperEmpty(output_zip)
863
Tianjie Xuaaca4212016-06-28 14:34:03 -0700864 banner("radio")
Tao Baobea20ac2018-01-17 17:57:49 -0800865 ab_partitions_txt = os.path.join(OPTIONS.input_tmp, "META",
866 "ab_partitions.txt")
867 if os.path.exists(ab_partitions_txt):
868 with open(ab_partitions_txt, 'r') as f:
869 ab_partitions = f.readlines()
Tianjie Xucfa86222016-03-07 16:31:19 -0800870
Tao Bao5277d102018-04-17 23:47:21 -0700871 # For devices using A/B update, make sure we have all the needed images
872 # ready under IMAGES/ or RADIO/.
873 CheckAbOtaImages(output_zip, ab_partitions)
Tianjie Xuaaca4212016-06-28 14:34:03 -0700874
Tianjie Xu861f4132018-09-12 11:49:33 -0700875 # Generate care_map.pb for ab_partitions, then write this file to
876 # target_files package.
Tianjie Xu4c05f4a2018-09-14 16:24:41 -0700877 AddCareMapForAbOta(output_zip, ab_partitions, partitions)
Tianjie Xucfa86222016-03-07 16:31:19 -0800878
Tao Bao95a95c32017-06-16 15:30:23 -0700879 # Radio images that need to be packed into IMAGES/, and product-img.zip.
Tao Baobea20ac2018-01-17 17:57:49 -0800880 pack_radioimages_txt = os.path.join(
Tao Bao95a95c32017-06-16 15:30:23 -0700881 OPTIONS.input_tmp, "META", "pack_radioimages.txt")
Tao Baobea20ac2018-01-17 17:57:49 -0800882 if os.path.exists(pack_radioimages_txt):
883 with open(pack_radioimages_txt, 'r') as f:
884 AddPackRadioImages(output_zip, f.readlines())
Tao Bao95a95c32017-06-16 15:30:23 -0700885
Dan Willemsen2ee00d52017-03-05 19:51:56 -0800886 if output_zip:
887 common.ZipClose(output_zip)
Tianjie Xu9ac4cb02017-06-09 16:58:03 -0700888 if OPTIONS.replace_updated_files_list:
889 ReplaceUpdatedFiles(output_zip.filename,
890 OPTIONS.replace_updated_files_list)
Tianjie Xu38af07f2017-05-25 17:38:53 -0700891
Doug Zongker3c84f562014-07-31 11:06:30 -0700892
Doug Zongker3c84f562014-07-31 11:06:30 -0700893def main(argv):
Baligh Uddin59f4ff12015-09-16 21:20:30 -0700894 def option_handler(o, a):
Michael Runge2e0d8fc2014-11-13 21:41:08 -0800895 if o in ("-a", "--add_missing"):
896 OPTIONS.add_missing = True
897 elif o in ("-r", "--rebuild_recovery",):
898 OPTIONS.rebuild_recovery = True
Baligh Uddin59f4ff12015-09-16 21:20:30 -0700899 elif o == "--replace_verity_private_key":
900 OPTIONS.replace_verity_private_key = (True, a)
901 elif o == "--replace_verity_public_key":
902 OPTIONS.replace_verity_public_key = (True, a)
Tianjie Xub48589a2016-08-03 19:21:52 -0700903 elif o == "--is_signing":
904 OPTIONS.is_signing = True
Michael Runge2e0d8fc2014-11-13 21:41:08 -0800905 else:
906 return False
907 return True
908
Dan Albert8b72aef2015-03-23 19:13:21 -0700909 args = common.ParseOptions(
910 argv, __doc__, extra_opts="ar",
Baligh Uddin59f4ff12015-09-16 21:20:30 -0700911 extra_long_opts=["add_missing", "rebuild_recovery",
912 "replace_verity_public_key=",
913 "replace_verity_private_key=",
Tao Bao45810422016-10-17 16:20:12 -0700914 "is_signing"],
Dan Albert8b72aef2015-03-23 19:13:21 -0700915 extra_option_handler=option_handler)
Michael Runge2e0d8fc2014-11-13 21:41:08 -0800916
Doug Zongker3c84f562014-07-31 11:06:30 -0700917
918 if len(args) != 1:
919 common.Usage(__doc__)
920 sys.exit(1)
921
922 AddImagesToTargetFiles(args[0])
Tao Bao89fbb0f2017-01-10 10:47:58 -0800923 print("done.")
Doug Zongker3c84f562014-07-31 11:06:30 -0700924
925if __name__ == '__main__':
926 try:
927 common.CloseInheritedPipes()
928 main(sys.argv[1:])
Dan Albert8b72aef2015-03-23 19:13:21 -0700929 except common.ExternalError as e:
Tao Bao89fbb0f2017-01-10 10:47:58 -0800930 print("\n ERROR: %s\n" % (e,))
Doug Zongker3c84f562014-07-31 11:06:30 -0700931 sys.exit(1)
Doug Zongkerfc44a512014-08-26 13:10:25 -0700932 finally:
933 common.Cleanup()