blob: 2fa5f5296ee07945d591dc4513b41bbc49d6e72a [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
Tao Bao6b9fef52017-12-01 16:13:22 -080052import sys
Tao Baod86e3112017-09-22 15:45:33 -070053import uuid
Doug Zongker3c84f562014-07-31 11:06:30 -070054import zipfile
55
Doug Zongker3c84f562014-07-31 11:06:30 -070056import build_image
57import common
Tianjie Xuf1a13182017-01-19 17:39:30 -080058import rangelib
Tianjie Xucfa86222016-03-07 16:31:19 -080059import sparse_img
Doug Zongker3c84f562014-07-31 11:06:30 -070060
Tao Bao6b9fef52017-12-01 16:13:22 -080061if sys.hexversion < 0x02070000:
62 print("Python 2.7 or newer is required.", file=sys.stderr)
63 sys.exit(1)
64
Doug Zongker3c84f562014-07-31 11:06:30 -070065OPTIONS = common.OPTIONS
66
Michael Runge2e0d8fc2014-11-13 21:41:08 -080067OPTIONS.add_missing = False
68OPTIONS.rebuild_recovery = False
Tianjie Xu9ac4cb02017-06-09 16:58:03 -070069OPTIONS.replace_updated_files_list = []
Baligh Uddin59f4ff12015-09-16 21:20:30 -070070OPTIONS.replace_verity_public_key = False
71OPTIONS.replace_verity_private_key = False
Tianjie Xub48589a2016-08-03 19:21:52 -070072OPTIONS.is_signing = False
Doug Zongker3c84f562014-07-31 11:06:30 -070073
Bryan Henrye6d547d2018-07-31 18:32:00 -070074# Use a fixed timestamp (01/01/2009 00:00:00 UTC) for files when packaging
75# images. (b/24377993, b/80600931)
Tao Baoe30a6a62018-08-27 10:57:19 -070076FIXED_FILE_TIMESTAMP = int((
77 datetime.datetime(2009, 1, 1, 0, 0, 0, 0, None) -
78 datetime.datetime.utcfromtimestamp(0)).total_seconds())
Tao Baoa2ff4c92018-01-17 12:14:43 -080079
Bowgo Tsaid624fa62017-11-14 23:42:30 +080080
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
Tao Baoe30a6a62018-08-27 10:57:19 -070098
Tianjie Xucfa86222016-03-07 16:31:19 -080099def GetCareMap(which, imgname):
Tao Bao63c18fe2018-02-21 23:45:43 -0800100 """Returns the care_map string for the given partition.
101
102 Args:
103 which: The partition name, must be listed in PARTITIONS_WITH_CARE_MAP.
104 imgname: The filename of the image.
105
106 Returns:
107 (which, care_map_ranges): care_map_ranges is the raw string of the care_map
108 RangeSet.
109 """
Tianjie Xu861f4132018-09-12 11:49:33 -0700110 assert which in common.PARTITIONS_WITH_CARE_MAP
Tianjie Xucfa86222016-03-07 16:31:19 -0800111
112 simg = sparse_img.SparseImage(imgname)
Tianjie Xuf1a13182017-01-19 17:39:30 -0800113 care_map_ranges = simg.care_map
Tao Bao35f4ebc2018-09-27 15:31:11 -0700114 key = which + "_image_blocks"
115 image_blocks = OPTIONS.info_dict.get(key)
116 if image_blocks:
117 assert image_blocks > 0, "blocks for {} must be positive".format(which)
118 care_map_ranges = care_map_ranges.intersect(
119 rangelib.RangeSet("0-{}".format(image_blocks)))
Tianjie Xuf1a13182017-01-19 17:39:30 -0800120
Tao Baoa2ff4c92018-01-17 12:14:43 -0800121 return [which, care_map_ranges.to_string_raw()]
Tianjie Xucfa86222016-03-07 16:31:19 -0800122
123
Tao Bao886d8832018-02-27 11:46:19 -0800124def AddSystem(output_zip, recovery_img=None, boot_img=None):
Doug Zongker3c84f562014-07-31 11:06:30 -0700125 """Turn the contents of SYSTEM into a system image and store it in
David Zeuthend995f4b2016-01-29 16:59:17 -0500126 output_zip. Returns the name of the system image file."""
Michael Runge2e0d8fc2014-11-13 21:41:08 -0800127
Tao Bao886d8832018-02-27 11:46:19 -0800128 img = OutputFile(output_zip, OPTIONS.input_tmp, "IMAGES", "system.img")
Dan Willemsen2ee00d52017-03-05 19:51:56 -0800129 if os.path.exists(img.input_name):
Tao Bao886d8832018-02-27 11:46:19 -0800130 print("system.img already exists; no need to rebuild...")
Dan Willemsen2ee00d52017-03-05 19:51:56 -0800131 return img.input_name
Michael Runge2e0d8fc2014-11-13 21:41:08 -0800132
133 def output_sink(fn, data):
Dan Albert8b72aef2015-03-23 19:13:21 -0700134 ofile = open(os.path.join(OPTIONS.input_tmp, "SYSTEM", fn), "w")
135 ofile.write(data)
136 ofile.close()
Michael Runge2e0d8fc2014-11-13 21:41:08 -0800137
Tianjie Xu38af07f2017-05-25 17:38:53 -0700138 arc_name = "SYSTEM/" + fn
139 if arc_name in output_zip.namelist():
Tianjie Xu9ac4cb02017-06-09 16:58:03 -0700140 OPTIONS.replace_updated_files_list.append(arc_name)
Tianjie Xu38af07f2017-05-25 17:38:53 -0700141 else:
142 common.ZipWrite(output_zip, ofile.name, arc_name)
143
Michael Runge2e0d8fc2014-11-13 21:41:08 -0800144 if OPTIONS.rebuild_recovery:
Tao Bao89fbb0f2017-01-10 10:47:58 -0800145 print("Building new recovery patch")
Dan Albert8b72aef2015-03-23 19:13:21 -0700146 common.MakeRecoveryPatch(OPTIONS.input_tmp, output_sink, recovery_img,
147 boot_img, info_dict=OPTIONS.info_dict)
Michael Runge2e0d8fc2014-11-13 21:41:08 -0800148
Tao Bao886d8832018-02-27 11:46:19 -0800149 block_list = OutputFile(output_zip, OPTIONS.input_tmp, "IMAGES", "system.map")
Dan Willemsen2ee00d52017-03-05 19:51:56 -0800150 CreateImage(OPTIONS.input_tmp, OPTIONS.info_dict, "system", img,
151 block_list=block_list)
David Zeuthend995f4b2016-01-29 16:59:17 -0500152
Dan Willemsen2ee00d52017-03-05 19:51:56 -0800153 return img.name
Doug Zongkerfc44a512014-08-26 13:10:25 -0700154
155
Tao Bao886d8832018-02-27 11:46:19 -0800156def AddSystemOther(output_zip):
Alex Light4e358ab2016-06-16 14:47:10 -0700157 """Turn the contents of SYSTEM_OTHER into a system_other image
158 and store it in output_zip."""
159
Tao Bao886d8832018-02-27 11:46:19 -0800160 img = OutputFile(output_zip, OPTIONS.input_tmp, "IMAGES", "system_other.img")
Dan Willemsen2ee00d52017-03-05 19:51:56 -0800161 if os.path.exists(img.input_name):
Tao Bao886d8832018-02-27 11:46:19 -0800162 print("system_other.img already exists; no need to rebuild...")
Alex Light4e358ab2016-06-16 14:47:10 -0700163 return
164
Dan Willemsen2ee00d52017-03-05 19:51:56 -0800165 CreateImage(OPTIONS.input_tmp, OPTIONS.info_dict, "system_other", img)
Alex Light4e358ab2016-06-16 14:47:10 -0700166
167
Tao Bao886d8832018-02-27 11:46:19 -0800168def AddVendor(output_zip):
Doug Zongkerfc44a512014-08-26 13:10:25 -0700169 """Turn the contents of VENDOR into a vendor image and store in it
170 output_zip."""
Michael Runge2e0d8fc2014-11-13 21:41:08 -0800171
Tao Bao886d8832018-02-27 11:46:19 -0800172 img = OutputFile(output_zip, OPTIONS.input_tmp, "IMAGES", "vendor.img")
Dan Willemsen2ee00d52017-03-05 19:51:56 -0800173 if os.path.exists(img.input_name):
Tao Bao886d8832018-02-27 11:46:19 -0800174 print("vendor.img already exists; no need to rebuild...")
Dan Willemsen2ee00d52017-03-05 19:51:56 -0800175 return img.input_name
Michael Runge2e0d8fc2014-11-13 21:41:08 -0800176
Tao Bao886d8832018-02-27 11:46:19 -0800177 block_list = OutputFile(output_zip, OPTIONS.input_tmp, "IMAGES", "vendor.map")
Dan Willemsen2ee00d52017-03-05 19:51:56 -0800178 CreateImage(OPTIONS.input_tmp, OPTIONS.info_dict, "vendor", img,
179 block_list=block_list)
180 return img.name
Doug Zongker3c84f562014-07-31 11:06:30 -0700181
Yueyao Zhu889ee5e2017-05-12 17:50:46 -0700182
Tao Bao886d8832018-02-27 11:46:19 -0800183def AddProduct(output_zip):
184 """Turn the contents of PRODUCT into a product image and store it in
185 output_zip."""
Jaekyun Seokb7735d82017-11-27 17:04:47 +0900186
Tao Bao886d8832018-02-27 11:46:19 -0800187 img = OutputFile(output_zip, OPTIONS.input_tmp, "IMAGES", "product.img")
Jaekyun Seokb7735d82017-11-27 17:04:47 +0900188 if os.path.exists(img.input_name):
Tao Bao886d8832018-02-27 11:46:19 -0800189 print("product.img already exists; no need to rebuild...")
Jaekyun Seokb7735d82017-11-27 17:04:47 +0900190 return img.input_name
191
Tao Bao886d8832018-02-27 11:46:19 -0800192 block_list = OutputFile(
193 output_zip, OPTIONS.input_tmp, "IMAGES", "product.map")
194 CreateImage(
195 OPTIONS.input_tmp, OPTIONS.info_dict, "product", img,
196 block_list=block_list)
Jaekyun Seokb7735d82017-11-27 17:04:47 +0900197 return img.name
198
199
Dario Freni5f681e12018-05-29 13:09:01 +0100200def AddProductServices(output_zip):
Dario Freni924af7d2018-08-17 00:56:14 +0100201 """Turn the contents of PRODUCT_SERVICES into a product_services image and
Dario Freni5f681e12018-05-29 13:09:01 +0100202 store it in output_zip."""
203
204 img = OutputFile(output_zip, OPTIONS.input_tmp, "IMAGES",
Dario Freni924af7d2018-08-17 00:56:14 +0100205 "product_services.img")
Dario Freni5f681e12018-05-29 13:09:01 +0100206 if os.path.exists(img.input_name):
Dario Freni924af7d2018-08-17 00:56:14 +0100207 print("product_services.img already exists; no need to rebuild...")
Dario Freni5f681e12018-05-29 13:09:01 +0100208 return img.input_name
209
210 block_list = OutputFile(
Dario Freni924af7d2018-08-17 00:56:14 +0100211 output_zip, OPTIONS.input_tmp, "IMAGES", "product_services.map")
Dario Freni5f681e12018-05-29 13:09:01 +0100212 CreateImage(
Dario Freni924af7d2018-08-17 00:56:14 +0100213 OPTIONS.input_tmp, OPTIONS.info_dict, "product_services", img,
Dario Freni5f681e12018-05-29 13:09:01 +0100214 block_list=block_list)
215 return img.name
216
217
Bowgo Tsaid624fa62017-11-14 23:42:30 +0800218def AddOdm(output_zip):
219 """Turn the contents of ODM into an odm image and store it in output_zip."""
220
221 img = OutputFile(output_zip, OPTIONS.input_tmp, "IMAGES", "odm.img")
222 if os.path.exists(img.input_name):
223 print("odm.img already exists; no need to rebuild...")
224 return img.input_name
225
226 block_list = OutputFile(
227 output_zip, OPTIONS.input_tmp, "IMAGES", "odm.map")
228 CreateImage(
229 OPTIONS.input_tmp, OPTIONS.info_dict, "odm", img,
230 block_list=block_list)
231 return img.name
232
233
Tao Bao886d8832018-02-27 11:46:19 -0800234def AddDtbo(output_zip):
Tao Baoc633ed02017-05-30 21:46:33 -0700235 """Adds the DTBO image.
236
Tao Bao886d8832018-02-27 11:46:19 -0800237 Uses the image under IMAGES/ if it already exists. Otherwise looks for the
Tao Baoc633ed02017-05-30 21:46:33 -0700238 image under PREBUILT_IMAGES/, signs it as needed, and returns the image name.
239 """
Tao Bao886d8832018-02-27 11:46:19 -0800240 img = OutputFile(output_zip, OPTIONS.input_tmp, "IMAGES", "dtbo.img")
Tao Baoc633ed02017-05-30 21:46:33 -0700241 if os.path.exists(img.input_name):
Tao Bao886d8832018-02-27 11:46:19 -0800242 print("dtbo.img already exists; no need to rebuild...")
Tao Baoc633ed02017-05-30 21:46:33 -0700243 return img.input_name
244
245 dtbo_prebuilt_path = os.path.join(
246 OPTIONS.input_tmp, "PREBUILT_IMAGES", "dtbo.img")
247 assert os.path.exists(dtbo_prebuilt_path)
248 shutil.copy(dtbo_prebuilt_path, img.name)
249
250 # AVB-sign the image as needed.
Bowgo Tsai3e599ea2017-05-26 18:30:04 +0800251 if OPTIONS.info_dict.get("avb_enable") == "true":
Tao Baoc633ed02017-05-30 21:46:33 -0700252 avbtool = os.getenv('AVBTOOL') or OPTIONS.info_dict["avb_avbtool"]
Tao Bao3ebfdde2017-05-23 23:06:55 -0700253 part_size = OPTIONS.info_dict["dtbo_size"]
Tao Baoc633ed02017-05-30 21:46:33 -0700254 # The AVB hash footer will be replaced if already present.
255 cmd = [avbtool, "add_hash_footer", "--image", img.name,
256 "--partition_size", str(part_size), "--partition_name", "dtbo"]
Bowgo Tsai3e599ea2017-05-26 18:30:04 +0800257 common.AppendAVBSigningArgs(cmd, "dtbo")
258 args = OPTIONS.info_dict.get("avb_dtbo_add_hash_footer_args")
Tao Baoc633ed02017-05-30 21:46:33 -0700259 if args and args.strip():
260 cmd.extend(shlex.split(args))
Tao Bao73dd4f42018-10-04 16:25:33 -0700261 proc = common.Run(cmd)
262 output, _ = proc.communicate()
263 assert proc.returncode == 0, \
264 "Failed to call 'avbtool add_hash_footer' for {}:\n{}".format(
265 img.name, output)
Tao Baoc633ed02017-05-30 21:46:33 -0700266
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
Tao Bao73dd4f42018-10-04 16:25:33 -0700454 proc = common.Run(cmd)
455 stdoutdata, _ = proc.communicate()
456 assert proc.returncode == 0, \
Bryan Henry69d3feb2018-04-14 23:07:46 -0700457 "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
Tao Bao73dd4f42018-10-04 16:25:33 -0700484 proc = common.Run(cmd)
485 stdoutdata, _ = proc.communicate()
486 assert proc.returncode == 0, \
Bryan Henry69d3feb2018-04-14 23:07:46 -0700487 "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]
Tao Bao73dd4f42018-10-04 16:25:33 -0700603 proc = common.Run(care_map_gen_cmd)
604 output, _ = proc.communicate()
605 assert proc.returncode == 0, \
606 "Failed to generate the care_map proto message:\n{}".format(output)
Tianjie Xuccbae482018-08-15 14:28:27 -0700607
Tianjie Xu4c05f4a2018-09-14 16:24:41 -0700608 care_map_path = "META/care_map.pb"
Tianjie Xuccbae482018-08-15 14:28:27 -0700609 if output_zip and care_map_path not in output_zip.namelist():
610 common.ZipWrite(output_zip, temp_care_map, arcname=care_map_path)
611 else:
612 shutil.copy(temp_care_map, os.path.join(OPTIONS.input_tmp, care_map_path))
613 if output_zip:
614 OPTIONS.replace_updated_files_list.append(care_map_path)
Tao Baobea20ac2018-01-17 17:57:49 -0800615
616
617def AddPackRadioImages(output_zip, images):
618 """Copies images listed in META/pack_radioimages.txt from RADIO/ to IMAGES/.
619
620 Args:
621 output_zip: The output zip file (needs to be already open), or None to
622 write images to OPTIONS.input_tmp/.
623 images: A list of image names.
624
625 Raises:
626 AssertionError: If a listed image can't be found.
627 """
628 for image in images:
629 img_name = image.strip()
630 _, ext = os.path.splitext(img_name)
631 if not ext:
632 img_name += ".img"
Tao Baoa2ff4c92018-01-17 12:14:43 -0800633
Tao Baobea20ac2018-01-17 17:57:49 -0800634 prebuilt_path = os.path.join(OPTIONS.input_tmp, "IMAGES", img_name)
635 if os.path.exists(prebuilt_path):
636 print("%s already exists, no need to overwrite..." % (img_name,))
637 continue
638
639 img_radio_path = os.path.join(OPTIONS.input_tmp, "RADIO", img_name)
640 assert os.path.exists(img_radio_path), \
641 "Failed to find %s at %s" % (img_name, img_radio_path)
Tao Baoa2ff4c92018-01-17 12:14:43 -0800642
Tao Baobea20ac2018-01-17 17:57:49 -0800643 if output_zip:
Tao Baoa2ff4c92018-01-17 12:14:43 -0800644 common.ZipWrite(output_zip, img_radio_path, "IMAGES/" + img_name)
Tao Baobea20ac2018-01-17 17:57:49 -0800645 else:
646 shutil.copy(img_radio_path, prebuilt_path)
647
648
David Anderson1ef03e22018-08-30 13:11:47 -0700649def AddSuperEmpty(output_zip):
650 """Create a super_empty.img and store it in output_zip."""
651
652 img = OutputFile(output_zip, OPTIONS.input_tmp, "IMAGES", "super_empty.img")
653 cmd = [OPTIONS.info_dict.get('lpmake')]
654 cmd += shlex.split(OPTIONS.info_dict.get('lpmake_args').strip())
655 cmd += ['--output', img.name]
656
Tao Bao73dd4f42018-10-04 16:25:33 -0700657 proc = common.Run(cmd)
658 stdoutdata, _ = proc.communicate()
659 assert proc.returncode == 0, \
David Anderson1ef03e22018-08-30 13:11:47 -0700660 "lpmake tool failed:\n{}".format(stdoutdata)
661
662 img.Write()
663
664
Tianjie Xu9ac4cb02017-06-09 16:58:03 -0700665def ReplaceUpdatedFiles(zip_filename, files_list):
Tao Bao89d7ab22017-12-14 17:05:33 -0800666 """Updates all the ZIP entries listed in files_list.
Tianjie Xu38af07f2017-05-25 17:38:53 -0700667
Tianjie Xu4c05f4a2018-09-14 16:24:41 -0700668 For now the list includes META/care_map.pb, and the related files under
Tianjie Xu9ac4cb02017-06-09 16:58:03 -0700669 SYSTEM/ after rebuilding recovery.
670 """
Tao Bao89d7ab22017-12-14 17:05:33 -0800671 common.ZipDelete(zip_filename, files_list)
Tianjie Xu38af07f2017-05-25 17:38:53 -0700672 output_zip = zipfile.ZipFile(zip_filename, "a",
673 compression=zipfile.ZIP_DEFLATED,
674 allowZip64=True)
Tianjie Xu9ac4cb02017-06-09 16:58:03 -0700675 for item in files_list:
Tianjie Xu38af07f2017-05-25 17:38:53 -0700676 file_path = os.path.join(OPTIONS.input_tmp, item)
677 assert os.path.exists(file_path)
678 common.ZipWrite(output_zip, file_path, arcname=item)
679 common.ZipClose(output_zip)
680
681
Doug Zongker3c84f562014-07-31 11:06:30 -0700682def AddImagesToTargetFiles(filename):
Tao Baoae396d92017-11-20 11:56:43 -0800683 """Creates and adds images (boot/recovery/system/...) to a target_files.zip.
684
685 It works with either a zip file (zip mode), or a directory that contains the
686 files to be packed into a target_files.zip (dir mode). The latter is used when
687 being called from build/make/core/Makefile.
688
689 The images will be created under IMAGES/ in the input target_files.zip.
690
691 Args:
Tao Baodba59ee2018-01-09 13:21:02 -0800692 filename: the target_files.zip, or the zip root directory.
Tao Baoae396d92017-11-20 11:56:43 -0800693 """
Dan Willemsen2ee00d52017-03-05 19:51:56 -0800694 if os.path.isdir(filename):
695 OPTIONS.input_tmp = os.path.abspath(filename)
Dan Willemsen2ee00d52017-03-05 19:51:56 -0800696 else:
Tao Baodba59ee2018-01-09 13:21:02 -0800697 OPTIONS.input_tmp = common.UnzipTemp(filename)
Doug Zongkerfc44a512014-08-26 13:10:25 -0700698
Michael Runge2e0d8fc2014-11-13 21:41:08 -0800699 if not OPTIONS.add_missing:
Dan Willemsen2ee00d52017-03-05 19:51:56 -0800700 if os.path.isdir(os.path.join(OPTIONS.input_tmp, "IMAGES")):
701 print("target_files appears to already contain images.")
702 sys.exit(1)
Doug Zongkerfc44a512014-08-26 13:10:25 -0700703
Tao Bao410ad8b2018-08-24 12:08:38 -0700704 OPTIONS.info_dict = common.LoadInfoDict(OPTIONS.input_tmp, repacking=True)
Tao Baodba59ee2018-01-09 13:21:02 -0800705
706 has_recovery = OPTIONS.info_dict.get("no_recovery") != "true"
707
Dario Freni924af7d2018-08-17 00:56:14 +0100708 # {vendor,odm,product,product_services}.img are unlike system.img or
Dario Freni5f681e12018-05-29 13:09:01 +0100709 # system_other.img. Because it could be built from source, or dropped into
710 # target_files.zip as a prebuilt blob. We consider either of them as
Dario Freni924af7d2018-08-17 00:56:14 +0100711 # {vendor,product,product_services}.img being available, which could be
Dario Freni5f681e12018-05-29 13:09:01 +0100712 # used when generating vbmeta.img for AVB.
Tao Baob22afea2017-09-12 12:39:09 -0700713 has_vendor = (os.path.isdir(os.path.join(OPTIONS.input_tmp, "VENDOR")) or
714 os.path.exists(os.path.join(OPTIONS.input_tmp, "IMAGES",
715 "vendor.img")))
Bowgo Tsaid624fa62017-11-14 23:42:30 +0800716 has_odm = (os.path.isdir(os.path.join(OPTIONS.input_tmp, "ODM")) or
Tao Bao744c4c72018-08-20 21:09:07 -0700717 os.path.exists(os.path.join(OPTIONS.input_tmp, "IMAGES",
718 "odm.img")))
Jaekyun Seokb7735d82017-11-27 17:04:47 +0900719 has_product = (os.path.isdir(os.path.join(OPTIONS.input_tmp, "PRODUCT")) or
720 os.path.exists(os.path.join(OPTIONS.input_tmp, "IMAGES",
721 "product.img")))
Yifan Hongebc041a2018-07-26 16:02:52 -0700722 has_product_services = (os.path.isdir(os.path.join(OPTIONS.input_tmp,
Yifan Hong35be6ca2018-08-17 21:01:25 +0000723 "PRODUCT_SERVICES")) or
Yifan Hongebc041a2018-07-26 16:02:52 -0700724 os.path.exists(os.path.join(OPTIONS.input_tmp,
725 "IMAGES",
Dario Freni924af7d2018-08-17 00:56:14 +0100726 "product_services.img")))
Dan Willemsen2ee00d52017-03-05 19:51:56 -0800727 has_system_other = os.path.isdir(os.path.join(OPTIONS.input_tmp,
728 "SYSTEM_OTHER"))
Doug Zongker3c84f562014-07-31 11:06:30 -0700729
Tao Baodba59ee2018-01-09 13:21:02 -0800730 # Set up the output destination. It writes to the given directory for dir
731 # mode; otherwise appends to the given ZIP.
732 if os.path.isdir(filename):
733 output_zip = None
734 else:
Dan Willemsen2ee00d52017-03-05 19:51:56 -0800735 output_zip = zipfile.ZipFile(filename, "a",
736 compression=zipfile.ZIP_DEFLATED,
737 allowZip64=True)
Tao Baoae396d92017-11-20 11:56:43 -0800738
739 # Always make input_tmp/IMAGES available, since we may stage boot / recovery
740 # images there even under zip mode. The directory will be cleaned up as part
741 # of OPTIONS.input_tmp.
742 images_dir = os.path.join(OPTIONS.input_tmp, "IMAGES")
743 if not os.path.isdir(images_dir):
744 os.makedirs(images_dir)
Doug Zongker3c84f562014-07-31 11:06:30 -0700745
Tao Baobf70c312017-07-11 17:27:55 -0700746 # A map between partition names and their paths, which could be used when
747 # generating AVB vbmeta image.
748 partitions = dict()
749
Doug Zongkerfc44a512014-08-26 13:10:25 -0700750 def banner(s):
Tao Bao89fbb0f2017-01-10 10:47:58 -0800751 print("\n\n++++ " + s + " ++++\n\n")
Doug Zongker3c84f562014-07-31 11:06:30 -0700752
Tao Bao262bf3f2017-07-11 17:27:55 -0700753 banner("boot")
754 # common.GetBootableImage() returns the image directly if present.
755 boot_image = common.GetBootableImage(
756 "IMAGES/boot.img", "boot.img", OPTIONS.input_tmp, "BOOT")
757 # boot.img may be unavailable in some targets (e.g. aosp_arm64).
758 if boot_image:
Tao Baobf70c312017-07-11 17:27:55 -0700759 partitions['boot'] = os.path.join(OPTIONS.input_tmp, "IMAGES", "boot.img")
760 if not os.path.exists(partitions['boot']):
Tao Bao262bf3f2017-07-11 17:27:55 -0700761 boot_image.WriteToDir(OPTIONS.input_tmp)
Dan Willemsen2ee00d52017-03-05 19:51:56 -0800762 if output_zip:
763 boot_image.AddToZip(output_zip)
Doug Zongker3c84f562014-07-31 11:06:30 -0700764
Michael Runge2e0d8fc2014-11-13 21:41:08 -0800765 recovery_image = None
Tao Baodb45efa2015-10-27 19:25:18 -0700766 if has_recovery:
767 banner("recovery")
Tao Bao262bf3f2017-07-11 17:27:55 -0700768 recovery_image = common.GetBootableImage(
769 "IMAGES/recovery.img", "recovery.img", OPTIONS.input_tmp, "RECOVERY")
770 assert recovery_image, "Failed to create recovery.img."
Tao Baobf70c312017-07-11 17:27:55 -0700771 partitions['recovery'] = os.path.join(
Tao Bao262bf3f2017-07-11 17:27:55 -0700772 OPTIONS.input_tmp, "IMAGES", "recovery.img")
Tao Baobf70c312017-07-11 17:27:55 -0700773 if not os.path.exists(partitions['recovery']):
Tao Bao262bf3f2017-07-11 17:27:55 -0700774 recovery_image.WriteToDir(OPTIONS.input_tmp)
775 if output_zip:
776 recovery_image.AddToZip(output_zip)
Doug Zongker3c84f562014-07-31 11:06:30 -0700777
Tao Baod42e97e2016-11-30 12:11:57 -0800778 banner("recovery (two-step image)")
779 # The special recovery.img for two-step package use.
780 recovery_two_step_image = common.GetBootableImage(
781 "IMAGES/recovery-two-step.img", "recovery-two-step.img",
782 OPTIONS.input_tmp, "RECOVERY", two_step_image=True)
Tao Bao262bf3f2017-07-11 17:27:55 -0700783 assert recovery_two_step_image, "Failed to create recovery-two-step.img."
784 recovery_two_step_image_path = os.path.join(
785 OPTIONS.input_tmp, "IMAGES", "recovery-two-step.img")
786 if not os.path.exists(recovery_two_step_image_path):
787 recovery_two_step_image.WriteToDir(OPTIONS.input_tmp)
Dan Willemsen2ee00d52017-03-05 19:51:56 -0800788 if output_zip:
789 recovery_two_step_image.AddToZip(output_zip)
Tao Baod42e97e2016-11-30 12:11:57 -0800790
Doug Zongkerfc44a512014-08-26 13:10:25 -0700791 banner("system")
Tao Baobea20ac2018-01-17 17:57:49 -0800792 partitions['system'] = AddSystem(
Tao Baoc633ed02017-05-30 21:46:33 -0700793 output_zip, recovery_img=recovery_image, boot_img=boot_image)
Tao Baobf70c312017-07-11 17:27:55 -0700794
Doug Zongkerfc44a512014-08-26 13:10:25 -0700795 if has_vendor:
796 banner("vendor")
Tao Baobea20ac2018-01-17 17:57:49 -0800797 partitions['vendor'] = AddVendor(output_zip)
Tao Baobf70c312017-07-11 17:27:55 -0700798
Jaekyun Seokb7735d82017-11-27 17:04:47 +0900799 if has_product:
800 banner("product")
801 partitions['product'] = AddProduct(output_zip)
802
Yifan Hongebc041a2018-07-26 16:02:52 -0700803 if has_product_services:
Dario Freni924af7d2018-08-17 00:56:14 +0100804 banner("product_services")
805 partitions['product_services'] = AddProductServices(output_zip)
Dario Freni5f681e12018-05-29 13:09:01 +0100806
Bowgo Tsaid624fa62017-11-14 23:42:30 +0800807 if has_odm:
808 banner("odm")
809 partitions['odm'] = AddOdm(output_zip)
810
Alex Light4e358ab2016-06-16 14:47:10 -0700811 if has_system_other:
812 banner("system_other")
813 AddSystemOther(output_zip)
Tao Baobf70c312017-07-11 17:27:55 -0700814
Tianjie Xub48589a2016-08-03 19:21:52 -0700815 if not OPTIONS.is_signing:
816 banner("userdata")
817 AddUserdata(output_zip)
818 banner("cache")
819 AddCache(output_zip)
Tao Baoc633ed02017-05-30 21:46:33 -0700820
821 if OPTIONS.info_dict.get("board_bpt_enable") == "true":
David Zeuthen25328622016-04-08 15:08:03 -0400822 banner("partition-table")
823 AddPartitionTable(output_zip)
Tao Baoc633ed02017-05-30 21:46:33 -0700824
Tao Baoc633ed02017-05-30 21:46:33 -0700825 if OPTIONS.info_dict.get("has_dtbo") == "true":
826 banner("dtbo")
Tao Baobf70c312017-07-11 17:27:55 -0700827 partitions['dtbo'] = AddDtbo(output_zip)
Tao Baoc633ed02017-05-30 21:46:33 -0700828
Bowgo Tsai3e599ea2017-05-26 18:30:04 +0800829 if OPTIONS.info_dict.get("avb_enable") == "true":
Tao Bao744c4c72018-08-20 21:09:07 -0700830 # vbmeta_partitions includes the partitions that should be included into
831 # top-level vbmeta.img, which are the ones that are not included in any
832 # chained VBMeta image plus the chained VBMeta images themselves.
833 vbmeta_partitions = common.AVB_PARTITIONS[:]
834
835 vbmeta_mainline = OPTIONS.info_dict.get("avb_vbmeta_mainline", "").strip()
836 if vbmeta_mainline:
837 banner("vbmeta_mainline")
838 AddVBMeta(
839 output_zip, partitions, "vbmeta_mainline", vbmeta_mainline.split())
840 vbmeta_partitions = [
841 item for item in vbmeta_partitions
842 if item not in vbmeta_mainline.split()]
843 vbmeta_partitions.append("vbmeta_mainline")
844
845 vbmeta_vendor = OPTIONS.info_dict.get("avb_vbmeta_vendor", "").strip()
846 if vbmeta_vendor:
847 banner("vbmeta_vendor")
848 AddVBMeta(
849 output_zip, partitions, "vbmeta_vendor", vbmeta_vendor.split())
850 vbmeta_partitions = [
851 item for item in vbmeta_partitions
852 if item not in vbmeta_vendor.split()]
853 vbmeta_partitions.append("vbmeta_vendor")
854
David Zeuthen2ce63ed2016-09-15 13:43:54 -0400855 banner("vbmeta")
Tao Bao744c4c72018-08-20 21:09:07 -0700856 AddVBMeta(output_zip, partitions, "vbmeta", vbmeta_partitions)
Doug Zongker3c84f562014-07-31 11:06:30 -0700857
David Anderson1ef03e22018-08-30 13:11:47 -0700858 if OPTIONS.info_dict.get("super_size"):
859 banner("super_empty")
860 AddSuperEmpty(output_zip)
861
Tianjie Xuaaca4212016-06-28 14:34:03 -0700862 banner("radio")
Tao Baobea20ac2018-01-17 17:57:49 -0800863 ab_partitions_txt = os.path.join(OPTIONS.input_tmp, "META",
864 "ab_partitions.txt")
865 if os.path.exists(ab_partitions_txt):
866 with open(ab_partitions_txt, 'r') as f:
867 ab_partitions = f.readlines()
Tianjie Xucfa86222016-03-07 16:31:19 -0800868
Tao Bao5277d102018-04-17 23:47:21 -0700869 # For devices using A/B update, make sure we have all the needed images
870 # ready under IMAGES/ or RADIO/.
871 CheckAbOtaImages(output_zip, ab_partitions)
Tianjie Xuaaca4212016-06-28 14:34:03 -0700872
Tianjie Xu861f4132018-09-12 11:49:33 -0700873 # Generate care_map.pb for ab_partitions, then write this file to
874 # target_files package.
Tianjie Xu4c05f4a2018-09-14 16:24:41 -0700875 AddCareMapForAbOta(output_zip, ab_partitions, partitions)
Tianjie Xucfa86222016-03-07 16:31:19 -0800876
Tao Bao95a95c32017-06-16 15:30:23 -0700877 # Radio images that need to be packed into IMAGES/, and product-img.zip.
Tao Baobea20ac2018-01-17 17:57:49 -0800878 pack_radioimages_txt = os.path.join(
Tao Bao95a95c32017-06-16 15:30:23 -0700879 OPTIONS.input_tmp, "META", "pack_radioimages.txt")
Tao Baobea20ac2018-01-17 17:57:49 -0800880 if os.path.exists(pack_radioimages_txt):
881 with open(pack_radioimages_txt, 'r') as f:
882 AddPackRadioImages(output_zip, f.readlines())
Tao Bao95a95c32017-06-16 15:30:23 -0700883
Dan Willemsen2ee00d52017-03-05 19:51:56 -0800884 if output_zip:
885 common.ZipClose(output_zip)
Tianjie Xu9ac4cb02017-06-09 16:58:03 -0700886 if OPTIONS.replace_updated_files_list:
887 ReplaceUpdatedFiles(output_zip.filename,
888 OPTIONS.replace_updated_files_list)
Tianjie Xu38af07f2017-05-25 17:38:53 -0700889
Doug Zongker3c84f562014-07-31 11:06:30 -0700890
Doug Zongker3c84f562014-07-31 11:06:30 -0700891def main(argv):
Baligh Uddin59f4ff12015-09-16 21:20:30 -0700892 def option_handler(o, a):
Michael Runge2e0d8fc2014-11-13 21:41:08 -0800893 if o in ("-a", "--add_missing"):
894 OPTIONS.add_missing = True
895 elif o in ("-r", "--rebuild_recovery",):
896 OPTIONS.rebuild_recovery = True
Baligh Uddin59f4ff12015-09-16 21:20:30 -0700897 elif o == "--replace_verity_private_key":
898 OPTIONS.replace_verity_private_key = (True, a)
899 elif o == "--replace_verity_public_key":
900 OPTIONS.replace_verity_public_key = (True, a)
Tianjie Xub48589a2016-08-03 19:21:52 -0700901 elif o == "--is_signing":
902 OPTIONS.is_signing = True
Michael Runge2e0d8fc2014-11-13 21:41:08 -0800903 else:
904 return False
905 return True
906
Dan Albert8b72aef2015-03-23 19:13:21 -0700907 args = common.ParseOptions(
908 argv, __doc__, extra_opts="ar",
Baligh Uddin59f4ff12015-09-16 21:20:30 -0700909 extra_long_opts=["add_missing", "rebuild_recovery",
910 "replace_verity_public_key=",
911 "replace_verity_private_key=",
Tao Bao45810422016-10-17 16:20:12 -0700912 "is_signing"],
Dan Albert8b72aef2015-03-23 19:13:21 -0700913 extra_option_handler=option_handler)
Michael Runge2e0d8fc2014-11-13 21:41:08 -0800914
Doug Zongker3c84f562014-07-31 11:06:30 -0700915
916 if len(args) != 1:
917 common.Usage(__doc__)
918 sys.exit(1)
919
920 AddImagesToTargetFiles(args[0])
Tao Bao89fbb0f2017-01-10 10:47:58 -0800921 print("done.")
Doug Zongker3c84f562014-07-31 11:06:30 -0700922
923if __name__ == '__main__':
924 try:
925 common.CloseInheritedPipes()
926 main(sys.argv[1:])
Dan Albert8b72aef2015-03-23 19:13:21 -0700927 except common.ExternalError as e:
Tao Bao89fbb0f2017-01-10 10:47:58 -0800928 print("\n ERROR: %s\n" % (e,))
Doug Zongker3c84f562014-07-31 11:06:30 -0700929 sys.exit(1)
Doug Zongkerfc44a512014-08-26 13:10:25 -0700930 finally:
931 common.Cleanup()