blob: d7de85b90338eeb69317faf6d97c74dcf31e4985 [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
Tao Bao4978fa92019-06-04 16:26:45 -070031 meaningful when system image needs to be rebuilt and there're separate
32 boot / recovery images.
Tianjie Xub48589a2016-08-03 19:21:52 -070033
34 --replace_verity_private_key
35 Replace the private key used for verity signing. (same as the option
36 in sign_target_files_apks)
37
38 --replace_verity_public_key
39 Replace the certificate (public key) used for verity verification. (same
40 as the option in sign_target_files_apks)
41
42 --is_signing
43 Skip building & adding the images for "userdata" and "cache" if we
44 are signing the target files.
Doug Zongker3c84f562014-07-31 11:06:30 -070045"""
46
Tao Bao89fbb0f2017-01-10 10:47:58 -080047from __future__ import print_function
48
Tao Bao822f5842015-09-30 16:01:14 -070049import datetime
Tao Bao32fcdab2018-10-12 10:30:39 -070050import logging
Doug Zongker3c84f562014-07-31 11:06:30 -070051import os
David Zeuthend995f4b2016-01-29 16:59:17 -050052import shlex
Ying Wang2a048392015-06-25 13:56:53 -070053import shutil
Rupert Shuttleworth72942742020-12-08 06:18:35 +000054import stat
Tao Bao6b9fef52017-12-01 16:13:22 -080055import sys
Tao Baod86e3112017-09-22 15:45:33 -070056import uuid
Doug Zongker3c84f562014-07-31 11:06:30 -070057import zipfile
58
Doug Zongker3c84f562014-07-31 11:06:30 -070059import build_image
Yifan Hong055e6cf2018-11-29 13:51:48 -080060import build_super_image
Doug Zongker3c84f562014-07-31 11:06:30 -070061import common
Hongguang Chenf23364d2020-04-27 18:36:36 -070062import verity_utils
Kelvin Zhang5f0fcee2021-01-19 15:30:46 -050063import ota_metadata_pb2
64
Daniel Normanb4b07ab2021-02-17 13:22:21 -080065from apex_utils import GetSystemApexInfoFromTargetFiles
Kelvin Zhangc184fa12021-03-22 15:38:38 -040066from common import AddCareMapForAbOta
Doug Zongker3c84f562014-07-31 11:06:30 -070067
Tao Bao6b9fef52017-12-01 16:13:22 -080068if sys.hexversion < 0x02070000:
69 print("Python 2.7 or newer is required.", file=sys.stderr)
70 sys.exit(1)
71
Tao Bao32fcdab2018-10-12 10:30:39 -070072logger = logging.getLogger(__name__)
Doug Zongker3c84f562014-07-31 11:06:30 -070073
Tao Bao32fcdab2018-10-12 10:30:39 -070074OPTIONS = common.OPTIONS
Michael Runge2e0d8fc2014-11-13 21:41:08 -080075OPTIONS.add_missing = False
76OPTIONS.rebuild_recovery = False
Tianjie Xu9ac4cb02017-06-09 16:58:03 -070077OPTIONS.replace_updated_files_list = []
Baligh Uddin59f4ff12015-09-16 21:20:30 -070078OPTIONS.replace_verity_public_key = False
79OPTIONS.replace_verity_private_key = False
Tianjie Xub48589a2016-08-03 19:21:52 -070080OPTIONS.is_signing = False
Doug Zongker3c84f562014-07-31 11:06:30 -070081
Bryan Henrye6d547d2018-07-31 18:32:00 -070082# Use a fixed timestamp (01/01/2009 00:00:00 UTC) for files when packaging
83# images. (b/24377993, b/80600931)
Tao Baoe30a6a62018-08-27 10:57:19 -070084FIXED_FILE_TIMESTAMP = int((
85 datetime.datetime(2009, 1, 1, 0, 0, 0, 0, None) -
86 datetime.datetime.utcfromtimestamp(0)).total_seconds())
Tao Baoa2ff4c92018-01-17 12:14:43 -080087
Bowgo Tsaid624fa62017-11-14 23:42:30 +080088
Dan Willemsen2ee00d52017-03-05 19:51:56 -080089class OutputFile(object):
Tao Bao93e7ebe2019-01-13 23:23:01 -080090 """A helper class to write a generated file to the given dir or zip.
Dan Willemsen2ee00d52017-03-05 19:51:56 -080091
Tao Bao93e7ebe2019-01-13 23:23:01 -080092 When generating images, we want the outputs to go into the given zip file, or
93 the given dir.
94
95 Attributes:
96 name: The name of the output file, regardless of the final destination.
97 """
98
Kelvin Zhang5f0fcee2021-01-19 15:30:46 -050099 def __init__(self, output_zip, input_dir, *args):
Tao Bao93e7ebe2019-01-13 23:23:01 -0800100 # We write the intermediate output file under the given input_dir, even if
101 # the final destination is a zip archive.
Kelvin Zhang5f0fcee2021-01-19 15:30:46 -0500102 self.name = os.path.join(input_dir, *args)
Tao Bao93e7ebe2019-01-13 23:23:01 -0800103 self._output_zip = output_zip
Dan Willemsen2ee00d52017-03-05 19:51:56 -0800104 if self._output_zip:
Kelvin Zhang5f0fcee2021-01-19 15:30:46 -0500105 self._zip_name = os.path.join(*args)
Dan Willemsen2ee00d52017-03-05 19:51:56 -0800106
Dan Willemsen2ee00d52017-03-05 19:51:56 -0800107 def Write(self):
108 if self._output_zip:
109 common.ZipWrite(self._output_zip, self.name, self._zip_name)
110
Tao Baoe30a6a62018-08-27 10:57:19 -0700111
Tao Bao886d8832018-02-27 11:46:19 -0800112def AddSystem(output_zip, recovery_img=None, boot_img=None):
Doug Zongker3c84f562014-07-31 11:06:30 -0700113 """Turn the contents of SYSTEM into a system image and store it in
David Zeuthend995f4b2016-01-29 16:59:17 -0500114 output_zip. Returns the name of the system image file."""
Michael Runge2e0d8fc2014-11-13 21:41:08 -0800115
Tao Bao886d8832018-02-27 11:46:19 -0800116 img = OutputFile(output_zip, OPTIONS.input_tmp, "IMAGES", "system.img")
Tao Bao93e7ebe2019-01-13 23:23:01 -0800117 if os.path.exists(img.name):
Tao Bao32fcdab2018-10-12 10:30:39 -0700118 logger.info("system.img already exists; no need to rebuild...")
Tao Bao93e7ebe2019-01-13 23:23:01 -0800119 return img.name
Michael Runge2e0d8fc2014-11-13 21:41:08 -0800120
121 def output_sink(fn, data):
Tao Baoa3705452019-06-24 15:33:41 -0700122 output_file = os.path.join(OPTIONS.input_tmp, "SYSTEM", fn)
123 with open(output_file, "wb") as ofile:
124 ofile.write(data)
Michael Runge2e0d8fc2014-11-13 21:41:08 -0800125
Daniel Normana4911da2019-03-15 14:36:21 -0700126 if output_zip:
127 arc_name = "SYSTEM/" + fn
128 if arc_name in output_zip.namelist():
129 OPTIONS.replace_updated_files_list.append(arc_name)
130 else:
Tao Baoa3705452019-06-24 15:33:41 -0700131 common.ZipWrite(output_zip, output_file, arc_name)
Tianjie Xu38af07f2017-05-25 17:38:53 -0700132
Bill Peckhame868aec2019-09-17 17:06:47 -0700133 board_uses_vendorimage = OPTIONS.info_dict.get(
134 "board_uses_vendorimage") == "true"
135
136 if (OPTIONS.rebuild_recovery and not board_uses_vendorimage and
Kelvin Zhangc184fa12021-03-22 15:38:38 -0400137 recovery_img is not None and boot_img is not None):
Bill Peckhame868aec2019-09-17 17:06:47 -0700138 logger.info("Building new recovery patch on system at system/vendor")
Dan Albert8b72aef2015-03-23 19:13:21 -0700139 common.MakeRecoveryPatch(OPTIONS.input_tmp, output_sink, recovery_img,
140 boot_img, info_dict=OPTIONS.info_dict)
Michael Runge2e0d8fc2014-11-13 21:41:08 -0800141
Kelvin Zhangc184fa12021-03-22 15:38:38 -0400142 block_list = OutputFile(output_zip, OPTIONS.input_tmp,
143 "IMAGES", "system.map")
Dan Willemsen2ee00d52017-03-05 19:51:56 -0800144 CreateImage(OPTIONS.input_tmp, OPTIONS.info_dict, "system", img,
145 block_list=block_list)
Dan Willemsen2ee00d52017-03-05 19:51:56 -0800146 return img.name
Doug Zongkerfc44a512014-08-26 13:10:25 -0700147
148
Tao Bao886d8832018-02-27 11:46:19 -0800149def AddSystemOther(output_zip):
Alex Light4e358ab2016-06-16 14:47:10 -0700150 """Turn the contents of SYSTEM_OTHER into a system_other image
151 and store it in output_zip."""
152
Tao Bao886d8832018-02-27 11:46:19 -0800153 img = OutputFile(output_zip, OPTIONS.input_tmp, "IMAGES", "system_other.img")
Tao Bao93e7ebe2019-01-13 23:23:01 -0800154 if os.path.exists(img.name):
Tao Bao32fcdab2018-10-12 10:30:39 -0700155 logger.info("system_other.img already exists; no need to rebuild...")
Alex Light4e358ab2016-06-16 14:47:10 -0700156 return
157
Dan Willemsen2ee00d52017-03-05 19:51:56 -0800158 CreateImage(OPTIONS.input_tmp, OPTIONS.info_dict, "system_other", img)
Alex Light4e358ab2016-06-16 14:47:10 -0700159
160
Bill Peckhame868aec2019-09-17 17:06:47 -0700161def AddVendor(output_zip, recovery_img=None, boot_img=None):
Doug Zongkerfc44a512014-08-26 13:10:25 -0700162 """Turn the contents of VENDOR into a vendor image and store in it
163 output_zip."""
Michael Runge2e0d8fc2014-11-13 21:41:08 -0800164
Tao Bao886d8832018-02-27 11:46:19 -0800165 img = OutputFile(output_zip, OPTIONS.input_tmp, "IMAGES", "vendor.img")
Tao Bao93e7ebe2019-01-13 23:23:01 -0800166 if os.path.exists(img.name):
Tao Bao32fcdab2018-10-12 10:30:39 -0700167 logger.info("vendor.img already exists; no need to rebuild...")
Tao Bao93e7ebe2019-01-13 23:23:01 -0800168 return img.name
Michael Runge2e0d8fc2014-11-13 21:41:08 -0800169
Bill Peckhame868aec2019-09-17 17:06:47 -0700170 def output_sink(fn, data):
171 ofile = open(os.path.join(OPTIONS.input_tmp, "VENDOR", fn), "w")
172 ofile.write(data)
173 ofile.close()
174
175 if output_zip:
176 arc_name = "VENDOR/" + fn
177 if arc_name in output_zip.namelist():
178 OPTIONS.replace_updated_files_list.append(arc_name)
179 else:
180 common.ZipWrite(output_zip, ofile.name, arc_name)
181
182 board_uses_vendorimage = OPTIONS.info_dict.get(
183 "board_uses_vendorimage") == "true"
184
185 if (OPTIONS.rebuild_recovery and board_uses_vendorimage and
Kelvin Zhangc184fa12021-03-22 15:38:38 -0400186 recovery_img is not None and boot_img is not None):
Bill Peckhame868aec2019-09-17 17:06:47 -0700187 logger.info("Building new recovery patch on vendor")
188 common.MakeRecoveryPatch(OPTIONS.input_tmp, output_sink, recovery_img,
189 boot_img, info_dict=OPTIONS.info_dict)
190
Kelvin Zhangc184fa12021-03-22 15:38:38 -0400191 block_list = OutputFile(output_zip, OPTIONS.input_tmp,
192 "IMAGES", "vendor.map")
Dan Willemsen2ee00d52017-03-05 19:51:56 -0800193 CreateImage(OPTIONS.input_tmp, OPTIONS.info_dict, "vendor", img,
194 block_list=block_list)
195 return img.name
Doug Zongker3c84f562014-07-31 11:06:30 -0700196
Yueyao Zhu889ee5e2017-05-12 17:50:46 -0700197
Tao Bao886d8832018-02-27 11:46:19 -0800198def AddProduct(output_zip):
199 """Turn the contents of PRODUCT into a product image and store it in
200 output_zip."""
Jaekyun Seokb7735d82017-11-27 17:04:47 +0900201
Tao Bao886d8832018-02-27 11:46:19 -0800202 img = OutputFile(output_zip, OPTIONS.input_tmp, "IMAGES", "product.img")
Tao Bao93e7ebe2019-01-13 23:23:01 -0800203 if os.path.exists(img.name):
Tao Bao32fcdab2018-10-12 10:30:39 -0700204 logger.info("product.img already exists; no need to rebuild...")
Tao Bao93e7ebe2019-01-13 23:23:01 -0800205 return img.name
Jaekyun Seokb7735d82017-11-27 17:04:47 +0900206
Tao Bao886d8832018-02-27 11:46:19 -0800207 block_list = OutputFile(
208 output_zip, OPTIONS.input_tmp, "IMAGES", "product.map")
209 CreateImage(
210 OPTIONS.input_tmp, OPTIONS.info_dict, "product", img,
211 block_list=block_list)
Jaekyun Seokb7735d82017-11-27 17:04:47 +0900212 return img.name
213
214
Justin Yun6151e3f2019-06-25 15:58:13 +0900215def AddSystemExt(output_zip):
216 """Turn the contents of SYSTEM_EXT into a system_ext image and store it in
217 output_zip."""
Dario Freni5f681e12018-05-29 13:09:01 +0100218
219 img = OutputFile(output_zip, OPTIONS.input_tmp, "IMAGES",
Justin Yun6151e3f2019-06-25 15:58:13 +0900220 "system_ext.img")
Tao Bao93e7ebe2019-01-13 23:23:01 -0800221 if os.path.exists(img.name):
Justin Yun6151e3f2019-06-25 15:58:13 +0900222 logger.info("system_ext.img already exists; no need to rebuild...")
Tao Bao93e7ebe2019-01-13 23:23:01 -0800223 return img.name
Dario Freni5f681e12018-05-29 13:09:01 +0100224
225 block_list = OutputFile(
Justin Yun6151e3f2019-06-25 15:58:13 +0900226 output_zip, OPTIONS.input_tmp, "IMAGES", "system_ext.map")
Dario Freni5f681e12018-05-29 13:09:01 +0100227 CreateImage(
Justin Yun6151e3f2019-06-25 15:58:13 +0900228 OPTIONS.input_tmp, OPTIONS.info_dict, "system_ext", img,
Dario Freni5f681e12018-05-29 13:09:01 +0100229 block_list=block_list)
230 return img.name
231
232
Bowgo Tsaid624fa62017-11-14 23:42:30 +0800233def AddOdm(output_zip):
234 """Turn the contents of ODM into an odm image and store it in output_zip."""
235
236 img = OutputFile(output_zip, OPTIONS.input_tmp, "IMAGES", "odm.img")
Tao Bao93e7ebe2019-01-13 23:23:01 -0800237 if os.path.exists(img.name):
Tao Bao32fcdab2018-10-12 10:30:39 -0700238 logger.info("odm.img already exists; no need to rebuild...")
Tao Bao93e7ebe2019-01-13 23:23:01 -0800239 return img.name
Bowgo Tsaid624fa62017-11-14 23:42:30 +0800240
241 block_list = OutputFile(
242 output_zip, OPTIONS.input_tmp, "IMAGES", "odm.map")
243 CreateImage(
244 OPTIONS.input_tmp, OPTIONS.info_dict, "odm", img,
245 block_list=block_list)
246 return img.name
247
248
Yifan Hongcfb917a2020-05-07 14:58:20 -0700249def AddVendorDlkm(output_zip):
250 """Turn the contents of VENDOR_DLKM into an vendor_dlkm image and store it in output_zip."""
251
252 img = OutputFile(output_zip, OPTIONS.input_tmp, "IMAGES", "vendor_dlkm.img")
253 if os.path.exists(img.name):
254 logger.info("vendor_dlkm.img already exists; no need to rebuild...")
255 return img.name
256
257 block_list = OutputFile(
258 output_zip, OPTIONS.input_tmp, "IMAGES", "vendor_dlkm.map")
259 CreateImage(
260 OPTIONS.input_tmp, OPTIONS.info_dict, "vendor_dlkm", img,
261 block_list=block_list)
262 return img.name
263
Kelvin Zhangc184fa12021-03-22 15:38:38 -0400264
Yifan Hongf496f1b2020-07-15 16:52:59 -0700265def AddOdmDlkm(output_zip):
266 """Turn the contents of OdmDlkm into an odm_dlkm image and store it in output_zip."""
267
268 img = OutputFile(output_zip, OPTIONS.input_tmp, "IMAGES", "odm_dlkm.img")
269 if os.path.exists(img.name):
270 logger.info("odm_dlkm.img already exists; no need to rebuild...")
271 return img.name
272
273 block_list = OutputFile(
274 output_zip, OPTIONS.input_tmp, "IMAGES", "odm_dlkm.map")
275 CreateImage(
276 OPTIONS.input_tmp, OPTIONS.info_dict, "odm_dlkm", img,
277 block_list=block_list)
278 return img.name
279
Yifan Hongcfb917a2020-05-07 14:58:20 -0700280
Tao Bao886d8832018-02-27 11:46:19 -0800281def AddDtbo(output_zip):
Tao Baoc633ed02017-05-30 21:46:33 -0700282 """Adds the DTBO image.
283
Tao Bao886d8832018-02-27 11:46:19 -0800284 Uses the image under IMAGES/ if it already exists. Otherwise looks for the
Tao Baoc633ed02017-05-30 21:46:33 -0700285 image under PREBUILT_IMAGES/, signs it as needed, and returns the image name.
286 """
Tao Bao886d8832018-02-27 11:46:19 -0800287 img = OutputFile(output_zip, OPTIONS.input_tmp, "IMAGES", "dtbo.img")
Tao Bao93e7ebe2019-01-13 23:23:01 -0800288 if os.path.exists(img.name):
Tao Bao32fcdab2018-10-12 10:30:39 -0700289 logger.info("dtbo.img already exists; no need to rebuild...")
Tao Bao93e7ebe2019-01-13 23:23:01 -0800290 return img.name
Tao Baoc633ed02017-05-30 21:46:33 -0700291
292 dtbo_prebuilt_path = os.path.join(
293 OPTIONS.input_tmp, "PREBUILT_IMAGES", "dtbo.img")
294 assert os.path.exists(dtbo_prebuilt_path)
295 shutil.copy(dtbo_prebuilt_path, img.name)
296
297 # AVB-sign the image as needed.
Bowgo Tsai3e599ea2017-05-26 18:30:04 +0800298 if OPTIONS.info_dict.get("avb_enable") == "true":
Rupert Shuttleworth72942742020-12-08 06:18:35 +0000299 # Signing requires +w
300 os.chmod(img.name, os.stat(img.name).st_mode | stat.S_IWUSR)
301
Tao Baof88e0ce2019-03-18 14:01:38 -0700302 avbtool = OPTIONS.info_dict["avb_avbtool"]
Tao Bao3ebfdde2017-05-23 23:06:55 -0700303 part_size = OPTIONS.info_dict["dtbo_size"]
Tao Baoc633ed02017-05-30 21:46:33 -0700304 # The AVB hash footer will be replaced if already present.
305 cmd = [avbtool, "add_hash_footer", "--image", img.name,
306 "--partition_size", str(part_size), "--partition_name", "dtbo"]
Bowgo Tsai3e599ea2017-05-26 18:30:04 +0800307 common.AppendAVBSigningArgs(cmd, "dtbo")
308 args = OPTIONS.info_dict.get("avb_dtbo_add_hash_footer_args")
Tao Baoc633ed02017-05-30 21:46:33 -0700309 if args and args.strip():
310 cmd.extend(shlex.split(args))
Tao Bao2764aee2018-11-21 11:02:48 -0800311 common.RunAndCheckOutput(cmd)
Tao Baoc633ed02017-05-30 21:46:33 -0700312
313 img.Write()
314 return img.name
315
Kelvin Zhangc184fa12021-03-22 15:38:38 -0400316
Andrew Sculle077cf72021-02-18 10:27:29 +0000317def AddPvmfw(output_zip):
318 """Adds the pvmfw image.
319
320 Uses the image under IMAGES/ if it already exists. Otherwise looks for the
321 image under PREBUILT_IMAGES/, signs it as needed, and returns the image name.
322 """
323 img = OutputFile(output_zip, OPTIONS.input_tmp, "IMAGES", "pvmfw.img")
324 if os.path.exists(img.name):
325 logger.info("pvmfw.img already exists; no need to rebuild...")
326 return img.name
327
328 pvmfw_prebuilt_path = os.path.join(
329 OPTIONS.input_tmp, "PREBUILT_IMAGES", "pvmfw.img")
330 assert os.path.exists(pvmfw_prebuilt_path)
331 shutil.copy(pvmfw_prebuilt_path, img.name)
332
333 # AVB-sign the image as needed.
334 if OPTIONS.info_dict.get("avb_enable") == "true":
335 # Signing requires +w
336 os.chmod(img.name, os.stat(img.name).st_mode | stat.S_IWUSR)
337
338 avbtool = OPTIONS.info_dict["avb_avbtool"]
339 part_size = OPTIONS.info_dict["pvmfw_size"]
340 # The AVB hash footer will be replaced if already present.
341 cmd = [avbtool, "add_hash_footer", "--image", img.name,
342 "--partition_size", str(part_size), "--partition_name", "pvmfw"]
343 common.AppendAVBSigningArgs(cmd, "pvmfw")
344 args = OPTIONS.info_dict.get("avb_pvmfw_add_hash_footer_args")
345 if args and args.strip():
346 cmd.extend(shlex.split(args))
347 common.RunAndCheckOutput(cmd)
348
349 img.Write()
350 return img.name
351
Kelvin Zhangc184fa12021-03-22 15:38:38 -0400352
Hongguang Chenf23364d2020-04-27 18:36:36 -0700353def AddCustomImages(output_zip, partition_name):
354 """Adds and signs custom images in IMAGES/.
355
356 Args:
357 output_zip: The output zip file (needs to be already open), or None to
358 write images to OPTIONS.input_tmp/.
359
360 Uses the image under IMAGES/ if it already exists. Otherwise looks for the
361 image under PREBUILT_IMAGES/, signs it as needed, and returns the image name.
362
363 Raises:
364 AssertionError: If image can't be found.
365 """
366
367 partition_size = OPTIONS.info_dict.get(
368 "avb_{}_partition_size".format(partition_name))
369 key_path = OPTIONS.info_dict.get("avb_{}_key_path".format(partition_name))
370 algorithm = OPTIONS.info_dict.get("avb_{}_algorithm".format(partition_name))
371 extra_args = OPTIONS.info_dict.get(
372 "avb_{}_add_hashtree_footer_args".format(partition_name))
373 partition_size = OPTIONS.info_dict.get(
374 "avb_{}_partition_size".format(partition_name))
375
376 builder = verity_utils.CreateCustomImageBuilder(
377 OPTIONS.info_dict, partition_name, partition_size,
378 key_path, algorithm, extra_args)
379
380 for img_name in OPTIONS.info_dict.get(
Kelvin Zhangc184fa12021-03-22 15:38:38 -0400381 "avb_{}_image_list".format(partition_name)).split():
382 custom_image = OutputFile(
383 output_zip, OPTIONS.input_tmp, "IMAGES", img_name)
Hongguang Chenf23364d2020-04-27 18:36:36 -0700384 if os.path.exists(custom_image.name):
385 continue
386
387 custom_image_prebuilt_path = os.path.join(
388 OPTIONS.input_tmp, "PREBUILT_IMAGES", img_name)
389 assert os.path.exists(custom_image_prebuilt_path), \
Kelvin Zhangc184fa12021-03-22 15:38:38 -0400390 "Failed to find %s at %s" % (img_name, custom_image_prebuilt_path)
Hongguang Chenf23364d2020-04-27 18:36:36 -0700391
392 shutil.copy(custom_image_prebuilt_path, custom_image.name)
393
394 if builder is not None:
395 builder.Build(custom_image.name)
396
397 custom_image.Write()
398
399 default = os.path.join(OPTIONS.input_tmp, "IMAGES", partition_name + ".img")
400 assert os.path.exists(default), \
401 "There should be one %s.img" % (partition_name)
402 return default
403
Doug Zongker3c84f562014-07-31 11:06:30 -0700404
Dan Willemsen2ee00d52017-03-05 19:51:56 -0800405def CreateImage(input_dir, info_dict, what, output_file, block_list=None):
Tao Baoa3705452019-06-24 15:33:41 -0700406 logger.info("creating %s.img...", what)
Doug Zongker3c84f562014-07-31 11:06:30 -0700407
Doug Zongker3c84f562014-07-31 11:06:30 -0700408 image_props = build_image.ImagePropFromGlobalDict(info_dict, what)
Bryan Henrye6d547d2018-07-31 18:32:00 -0700409 image_props["timestamp"] = FIXED_FILE_TIMESTAMP
Tao Bao822f5842015-09-30 16:01:14 -0700410
Doug Zongker3c84f562014-07-31 11:06:30 -0700411 if what == "system":
412 fs_config_prefix = ""
413 else:
414 fs_config_prefix = what + "_"
415
416 fs_config = os.path.join(
417 input_dir, "META/" + fs_config_prefix + "filesystem_config.txt")
Dan Albert8b72aef2015-03-23 19:13:21 -0700418 if not os.path.exists(fs_config):
419 fs_config = None
Doug Zongker3c84f562014-07-31 11:06:30 -0700420
Ying Wanga2292c92015-03-24 19:07:40 -0700421 # Override values loaded from info_dict.
422 if fs_config:
423 image_props["fs_config"] = fs_config
Ying Wanga2292c92015-03-24 19:07:40 -0700424 if block_list:
Dan Willemsen2ee00d52017-03-05 19:51:56 -0800425 image_props["block_list"] = block_list.name
Ying Wanga2292c92015-03-24 19:07:40 -0700426
Tao Baod86e3112017-09-22 15:45:33 -0700427 # Use repeatable ext4 FS UUID and hash_seed UUID (based on partition name and
428 # build fingerprint).
Tao Bao3ed35d32019-10-07 20:48:48 -0700429 build_info = common.BuildInfo(info_dict)
Yifan Hongc08cbf02020-09-15 19:07:39 +0000430 uuid_seed = what + "-" + build_info.GetPartitionFingerprint(what)
Tao Baod86e3112017-09-22 15:45:33 -0700431 image_props["uuid"] = str(uuid.uuid5(uuid.NAMESPACE_URL, uuid_seed))
432 hash_seed = "hash_seed-" + uuid_seed
433 image_props["hash_seed"] = str(uuid.uuid5(uuid.NAMESPACE_URL, hash_seed))
434
Tao Baoc6bd70a2018-09-27 16:58:00 -0700435 build_image.BuildImage(
436 os.path.join(input_dir, what.upper()), image_props, output_file.name)
Doug Zongker3c84f562014-07-31 11:06:30 -0700437
Dan Willemsen2ee00d52017-03-05 19:51:56 -0800438 output_file.Write()
439 if block_list:
440 block_list.Write()
441
Shashikant Baviskar16a73892019-02-07 10:57:21 +0900442 # Set the '_image_size' for given image size.
Tianjie Xuf1a13182017-01-19 17:39:30 -0800443 is_verity_partition = "verity_block_device" in image_props
Tianjie Xu6b2e1552017-06-01 11:32:32 -0700444 verity_supported = (image_props.get("verity") == "true" or
Bowgo Tsai3e599ea2017-05-26 18:30:04 +0800445 image_props.get("avb_enable") == "true")
Tianjie Xu6b2e1552017-06-01 11:32:32 -0700446 is_avb_enable = image_props.get("avb_hashtree_enable") == "true"
447 if verity_supported and (is_verity_partition or is_avb_enable):
Tao Bao35f4ebc2018-09-27 15:31:11 -0700448 image_size = image_props.get("image_size")
449 if image_size:
Shashikant Baviskar16a73892019-02-07 10:57:21 +0900450 image_size_key = what + "_image_size"
451 info_dict[image_size_key] = int(image_size)
Tianjie Xuf1a13182017-01-19 17:39:30 -0800452
Yifan Hongc767f7c2018-11-08 15:41:24 -0800453 use_dynamic_size = (
Tao Bao2764aee2018-11-21 11:02:48 -0800454 info_dict.get("use_dynamic_partition_size") == "true" and
455 what in shlex.split(info_dict.get("dynamic_partition_list", "").strip()))
Yifan Hongc767f7c2018-11-08 15:41:24 -0800456 if use_dynamic_size:
457 info_dict.update(build_image.GlobalDictFromImageProp(image_props, what))
458
Doug Zongker3c84f562014-07-31 11:06:30 -0700459
Tao Bao886d8832018-02-27 11:46:19 -0800460def AddUserdata(output_zip):
Ying Wang2a048392015-06-25 13:56:53 -0700461 """Create a userdata image and store it in output_zip.
462
463 In most case we just create and store an empty userdata.img;
464 But the invoker can also request to create userdata.img with real
465 data from the target files, by setting "userdata_img_with_data=true"
466 in OPTIONS.info_dict.
467 """
Doug Zongker3c84f562014-07-31 11:06:30 -0700468
Tao Bao886d8832018-02-27 11:46:19 -0800469 img = OutputFile(output_zip, OPTIONS.input_tmp, "IMAGES", "userdata.img")
Tao Bao93e7ebe2019-01-13 23:23:01 -0800470 if os.path.exists(img.name):
Tao Bao32fcdab2018-10-12 10:30:39 -0700471 logger.info("userdata.img already exists; no need to rebuild...")
Michael Runge2e0d8fc2014-11-13 21:41:08 -0800472 return
473
Elliott Hughes305b0882016-06-15 17:04:54 -0700474 # Skip userdata.img if no size.
Tao Bao2c15d9e2015-07-09 11:51:16 -0700475 image_props = build_image.ImagePropFromGlobalDict(OPTIONS.info_dict, "data")
Elliott Hughes305b0882016-06-15 17:04:54 -0700476 if not image_props.get("partition_size"):
Doug Zongker3c84f562014-07-31 11:06:30 -0700477 return
478
Tao Bao32fcdab2018-10-12 10:30:39 -0700479 logger.info("creating userdata.img...")
Doug Zongker3c84f562014-07-31 11:06:30 -0700480
Bryan Henrye6d547d2018-07-31 18:32:00 -0700481 image_props["timestamp"] = FIXED_FILE_TIMESTAMP
Tao Bao822f5842015-09-30 16:01:14 -0700482
Tao Baofa863c82017-05-23 23:49:03 -0700483 if OPTIONS.info_dict.get("userdata_img_with_data") == "true":
484 user_dir = os.path.join(OPTIONS.input_tmp, "DATA")
Ying Wang2a048392015-06-25 13:56:53 -0700485 else:
Tao Bao1c830bf2017-12-25 10:43:47 -0800486 user_dir = common.MakeTempDir()
Ying Wang2a048392015-06-25 13:56:53 -0700487
Tao Baoc6bd70a2018-09-27 16:58:00 -0700488 build_image.BuildImage(user_dir, image_props, img.name)
Doug Zongker3c84f562014-07-31 11:06:30 -0700489
490 common.CheckSize(img.name, "userdata.img", OPTIONS.info_dict)
Dan Willemsen2ee00d52017-03-05 19:51:56 -0800491 img.Write()
Doug Zongker3c84f562014-07-31 11:06:30 -0700492
493
Tao Bao744c4c72018-08-20 21:09:07 -0700494def AddVBMeta(output_zip, partitions, name, needed_partitions):
495 """Creates a VBMeta image and stores it in output_zip.
496
497 It generates the requested VBMeta image. The requested image could be for
498 top-level or chained VBMeta image, which is determined based on the name.
Tao Baobf70c312017-07-11 17:27:55 -0700499
500 Args:
501 output_zip: The output zip file, which needs to be already open.
502 partitions: A dict that's keyed by partition names with image paths as
Hongguang Chenf23364d2020-04-27 18:36:36 -0700503 values. Only valid partition names are accepted, as partitions listed
504 in common.AVB_PARTITIONS and custom partitions listed in
505 OPTIONS.info_dict.get("avb_custom_images_partition_list")
David Anderson7709ab22018-10-15 14:41:34 -0700506 name: Name of the VBMeta partition, e.g. 'vbmeta', 'vbmeta_system'.
Tao Bao744c4c72018-08-20 21:09:07 -0700507 needed_partitions: Partitions whose descriptors should be included into the
508 generated VBMeta image.
509
Tao Bao71064202018-10-22 15:08:02 -0700510 Returns:
511 Path to the created image.
512
Tao Bao744c4c72018-08-20 21:09:07 -0700513 Raises:
514 AssertionError: On invalid input args.
Tao Baobf70c312017-07-11 17:27:55 -0700515 """
Tao Bao744c4c72018-08-20 21:09:07 -0700516 assert needed_partitions, "Needed partitions must be specified"
517
518 img = OutputFile(
519 output_zip, OPTIONS.input_tmp, "IMAGES", "{}.img".format(name))
Tao Bao93e7ebe2019-01-13 23:23:01 -0800520 if os.path.exists(img.name):
Tao Bao32fcdab2018-10-12 10:30:39 -0700521 logger.info("%s.img already exists; not rebuilding...", name)
Tao Bao93e7ebe2019-01-13 23:23:01 -0800522 return img.name
Tao Bao262bf3f2017-07-11 17:27:55 -0700523
Daniel Norman276f0622019-07-26 14:13:51 -0700524 common.BuildVBMeta(img.name, partitions, name, needed_partitions)
Dan Willemsen2ee00d52017-03-05 19:51:56 -0800525 img.Write()
Tao Bao71064202018-10-22 15:08:02 -0700526 return img.name
David Zeuthen2ce63ed2016-09-15 13:43:54 -0400527
528
Tao Bao886d8832018-02-27 11:46:19 -0800529def AddPartitionTable(output_zip):
David Zeuthen25328622016-04-08 15:08:03 -0400530 """Create a partition table image and store it in output_zip."""
531
Tao Bao886d8832018-02-27 11:46:19 -0800532 img = OutputFile(
533 output_zip, OPTIONS.input_tmp, "IMAGES", "partition-table.img")
534 bpt = OutputFile(
Bryan Henryf130a232018-04-26 11:59:33 -0700535 output_zip, OPTIONS.input_tmp, "META", "partition-table.bpt")
David Zeuthen25328622016-04-08 15:08:03 -0400536
537 # use BPTTOOL from environ, or "bpttool" if empty or not set.
538 bpttool = os.getenv("BPTTOOL") or "bpttool"
Dan Willemsen2ee00d52017-03-05 19:51:56 -0800539 cmd = [bpttool, "make_table", "--output_json", bpt.name,
540 "--output_gpt", img.name]
David Zeuthen25328622016-04-08 15:08:03 -0400541 input_files_str = OPTIONS.info_dict["board_bpt_input_files"]
542 input_files = input_files_str.split(" ")
543 for i in input_files:
544 cmd.extend(["--input", i])
545 disk_size = OPTIONS.info_dict.get("board_bpt_disk_size")
546 if disk_size:
547 cmd.extend(["--disk_size", disk_size])
548 args = OPTIONS.info_dict.get("board_bpt_make_table_args")
549 if args:
550 cmd.extend(shlex.split(args))
Tao Bao2764aee2018-11-21 11:02:48 -0800551 common.RunAndCheckOutput(cmd)
David Zeuthen25328622016-04-08 15:08:03 -0400552
Dan Willemsen2ee00d52017-03-05 19:51:56 -0800553 img.Write()
554 bpt.Write()
David Zeuthen25328622016-04-08 15:08:03 -0400555
556
Tao Bao886d8832018-02-27 11:46:19 -0800557def AddCache(output_zip):
Doug Zongker3c84f562014-07-31 11:06:30 -0700558 """Create an empty cache image and store it in output_zip."""
559
Tao Bao886d8832018-02-27 11:46:19 -0800560 img = OutputFile(output_zip, OPTIONS.input_tmp, "IMAGES", "cache.img")
Tao Bao93e7ebe2019-01-13 23:23:01 -0800561 if os.path.exists(img.name):
Tao Bao32fcdab2018-10-12 10:30:39 -0700562 logger.info("cache.img already exists; no need to rebuild...")
Michael Runge2e0d8fc2014-11-13 21:41:08 -0800563 return
564
Tao Bao2c15d9e2015-07-09 11:51:16 -0700565 image_props = build_image.ImagePropFromGlobalDict(OPTIONS.info_dict, "cache")
Doug Zongker3c84f562014-07-31 11:06:30 -0700566 # The build system has to explicitly request for cache.img.
567 if "fs_type" not in image_props:
568 return
569
Tao Bao32fcdab2018-10-12 10:30:39 -0700570 logger.info("creating cache.img...")
Doug Zongker3c84f562014-07-31 11:06:30 -0700571
Bryan Henrye6d547d2018-07-31 18:32:00 -0700572 image_props["timestamp"] = FIXED_FILE_TIMESTAMP
Tao Bao822f5842015-09-30 16:01:14 -0700573
Tao Bao1c830bf2017-12-25 10:43:47 -0800574 user_dir = common.MakeTempDir()
Tao Baoc6bd70a2018-09-27 16:58:00 -0700575 build_image.BuildImage(user_dir, image_props, img.name)
Doug Zongker3c84f562014-07-31 11:06:30 -0700576
577 common.CheckSize(img.name, "cache.img", OPTIONS.info_dict)
Dan Willemsen2ee00d52017-03-05 19:51:56 -0800578 img.Write()
Doug Zongker3c84f562014-07-31 11:06:30 -0700579
580
Tao Bao5277d102018-04-17 23:47:21 -0700581def CheckAbOtaImages(output_zip, ab_partitions):
582 """Checks that all the listed A/B partitions have their images available.
Tao Baobea20ac2018-01-17 17:57:49 -0800583
Tao Bao5277d102018-04-17 23:47:21 -0700584 The images need to be available under IMAGES/ or RADIO/, with the former takes
585 a priority.
Tao Baobea20ac2018-01-17 17:57:49 -0800586
587 Args:
588 output_zip: The output zip file (needs to be already open), or None to
Tao Bao5277d102018-04-17 23:47:21 -0700589 find images in OPTIONS.input_tmp/.
Tao Baobea20ac2018-01-17 17:57:49 -0800590 ab_partitions: The list of A/B partitions.
591
592 Raises:
593 AssertionError: If it can't find an image.
594 """
595 for partition in ab_partitions:
596 img_name = partition.strip() + ".img"
Tao Baobea20ac2018-01-17 17:57:49 -0800597
Tao Baoa2ff4c92018-01-17 12:14:43 -0800598 # Assert that the image is present under IMAGES/ now.
Tao Baobea20ac2018-01-17 17:57:49 -0800599 if output_zip:
600 # Zip spec says: All slashes MUST be forward slashes.
Tao Bao5277d102018-04-17 23:47:21 -0700601 images_path = "IMAGES/" + img_name
602 radio_path = "RADIO/" + img_name
603 available = (images_path in output_zip.namelist() or
604 radio_path in output_zip.namelist())
Tao Baobea20ac2018-01-17 17:57:49 -0800605 else:
Tao Bao5277d102018-04-17 23:47:21 -0700606 images_path = os.path.join(OPTIONS.input_tmp, "IMAGES", img_name)
607 radio_path = os.path.join(OPTIONS.input_tmp, "RADIO", img_name)
608 available = os.path.exists(images_path) or os.path.exists(radio_path)
609
610 assert available, "Failed to find " + img_name
Tao Baobea20ac2018-01-17 17:57:49 -0800611
612
Tao Baobea20ac2018-01-17 17:57:49 -0800613def AddPackRadioImages(output_zip, images):
614 """Copies images listed in META/pack_radioimages.txt from RADIO/ to IMAGES/.
615
616 Args:
617 output_zip: The output zip file (needs to be already open), or None to
618 write images to OPTIONS.input_tmp/.
619 images: A list of image names.
620
621 Raises:
622 AssertionError: If a listed image can't be found.
623 """
624 for image in images:
625 img_name = image.strip()
626 _, ext = os.path.splitext(img_name)
627 if not ext:
628 img_name += ".img"
Tao Baoa2ff4c92018-01-17 12:14:43 -0800629
Tao Baobea20ac2018-01-17 17:57:49 -0800630 prebuilt_path = os.path.join(OPTIONS.input_tmp, "IMAGES", img_name)
631 if os.path.exists(prebuilt_path):
Tao Bao32fcdab2018-10-12 10:30:39 -0700632 logger.info("%s already exists, no need to overwrite...", img_name)
Tao Baobea20ac2018-01-17 17:57:49 -0800633 continue
634
635 img_radio_path = os.path.join(OPTIONS.input_tmp, "RADIO", img_name)
636 assert os.path.exists(img_radio_path), \
637 "Failed to find %s at %s" % (img_name, img_radio_path)
Tao Baoa2ff4c92018-01-17 12:14:43 -0800638
Tao Baobea20ac2018-01-17 17:57:49 -0800639 if output_zip:
Tao Baoa2ff4c92018-01-17 12:14:43 -0800640 common.ZipWrite(output_zip, img_radio_path, "IMAGES/" + img_name)
Tao Baobea20ac2018-01-17 17:57:49 -0800641 else:
642 shutil.copy(img_radio_path, prebuilt_path)
643
644
David Anderson1ef03e22018-08-30 13:11:47 -0700645def AddSuperEmpty(output_zip):
646 """Create a super_empty.img and store it in output_zip."""
647
648 img = OutputFile(output_zip, OPTIONS.input_tmp, "IMAGES", "super_empty.img")
Yifan Hong055e6cf2018-11-29 13:51:48 -0800649 build_super_image.BuildSuperImage(OPTIONS.info_dict, img.name)
David Anderson1ef03e22018-08-30 13:11:47 -0700650 img.Write()
651
652
Yifan Hongc767f7c2018-11-08 15:41:24 -0800653def AddSuperSplit(output_zip):
654 """Create split super_*.img and store it in output_zip."""
655
Yifan Hong055e6cf2018-11-29 13:51:48 -0800656 outdir = os.path.join(OPTIONS.input_tmp, "OTA")
Yifan Honge98427a2018-12-07 10:08:27 -0800657 built = build_super_image.BuildSuperImage(OPTIONS.input_tmp, outdir)
Yifan Hongc767f7c2018-11-08 15:41:24 -0800658
Yifan Honge98427a2018-12-07 10:08:27 -0800659 if built:
660 for dev in OPTIONS.info_dict['super_block_devices'].strip().split():
661 img = OutputFile(output_zip, OPTIONS.input_tmp, "OTA",
662 "super_" + dev + ".img")
663 img.Write()
Yifan Hongc767f7c2018-11-08 15:41:24 -0800664
665
Tianjie Xu9ac4cb02017-06-09 16:58:03 -0700666def ReplaceUpdatedFiles(zip_filename, files_list):
Tao Bao89d7ab22017-12-14 17:05:33 -0800667 """Updates all the ZIP entries listed in files_list.
Tianjie Xu38af07f2017-05-25 17:38:53 -0700668
Tianjie Xu4c05f4a2018-09-14 16:24:41 -0700669 For now the list includes META/care_map.pb, and the related files under
Tianjie Xu9ac4cb02017-06-09 16:58:03 -0700670 SYSTEM/ after rebuilding recovery.
671 """
Tao Bao89d7ab22017-12-14 17:05:33 -0800672 common.ZipDelete(zip_filename, files_list)
Tianjie Xu38af07f2017-05-25 17:38:53 -0700673 output_zip = zipfile.ZipFile(zip_filename, "a",
674 compression=zipfile.ZIP_DEFLATED,
675 allowZip64=True)
Tianjie Xu9ac4cb02017-06-09 16:58:03 -0700676 for item in files_list:
Tianjie Xu38af07f2017-05-25 17:38:53 -0700677 file_path = os.path.join(OPTIONS.input_tmp, item)
678 assert os.path.exists(file_path)
679 common.ZipWrite(output_zip, file_path, arcname=item)
680 common.ZipClose(output_zip)
681
682
Chris Gross435b8fe2020-09-15 09:53:44 -0700683def HasPartition(partition_name):
684 """Determines if the target files archive should build a given partition."""
685
686 return ((os.path.isdir(
687 os.path.join(OPTIONS.input_tmp, partition_name.upper())) and
Kelvin Zhangc184fa12021-03-22 15:38:38 -0400688 OPTIONS.info_dict.get(
689 "building_{}_image".format(partition_name)) == "true") or
690 os.path.exists(
691 os.path.join(OPTIONS.input_tmp, "IMAGES",
692 "{}.img".format(partition_name))))
693
Chris Gross435b8fe2020-09-15 09:53:44 -0700694
Kelvin Zhang5f0fcee2021-01-19 15:30:46 -0500695def AddApexInfo(output_zip):
Daniel Normanb4b07ab2021-02-17 13:22:21 -0800696 apex_infos = GetSystemApexInfoFromTargetFiles(OPTIONS.input_tmp)
Kelvin Zhang5f0fcee2021-01-19 15:30:46 -0500697 apex_metadata_proto = ota_metadata_pb2.ApexMetadata()
698 apex_metadata_proto.apex_info.extend(apex_infos)
699 apex_info_bytes = apex_metadata_proto.SerializeToString()
700
701 output_file = os.path.join(OPTIONS.input_tmp, "META", "apex_info.pb")
702 with open(output_file, "wb") as ofile:
703 ofile.write(apex_info_bytes)
704 if output_zip:
705 arc_name = "META/apex_info.pb"
706 if arc_name in output_zip.namelist():
707 OPTIONS.replace_updated_files_list.append(arc_name)
708 else:
709 common.ZipWrite(output_zip, output_file, arc_name)
710
Chris Gross435b8fe2020-09-15 09:53:44 -0700711
Doug Zongker3c84f562014-07-31 11:06:30 -0700712def AddImagesToTargetFiles(filename):
Tao Baoae396d92017-11-20 11:56:43 -0800713 """Creates and adds images (boot/recovery/system/...) to a target_files.zip.
714
715 It works with either a zip file (zip mode), or a directory that contains the
716 files to be packed into a target_files.zip (dir mode). The latter is used when
717 being called from build/make/core/Makefile.
718
719 The images will be created under IMAGES/ in the input target_files.zip.
720
721 Args:
Tao Baodba59ee2018-01-09 13:21:02 -0800722 filename: the target_files.zip, or the zip root directory.
Tao Baoae396d92017-11-20 11:56:43 -0800723 """
Dan Willemsen2ee00d52017-03-05 19:51:56 -0800724 if os.path.isdir(filename):
725 OPTIONS.input_tmp = os.path.abspath(filename)
Dan Willemsen2ee00d52017-03-05 19:51:56 -0800726 else:
Tao Baodba59ee2018-01-09 13:21:02 -0800727 OPTIONS.input_tmp = common.UnzipTemp(filename)
Doug Zongkerfc44a512014-08-26 13:10:25 -0700728
Michael Runge2e0d8fc2014-11-13 21:41:08 -0800729 if not OPTIONS.add_missing:
Dan Willemsen2ee00d52017-03-05 19:51:56 -0800730 if os.path.isdir(os.path.join(OPTIONS.input_tmp, "IMAGES")):
Tao Bao32fcdab2018-10-12 10:30:39 -0700731 logger.warning("target_files appears to already contain images.")
Dan Willemsen2ee00d52017-03-05 19:51:56 -0800732 sys.exit(1)
Doug Zongkerfc44a512014-08-26 13:10:25 -0700733
Tao Bao410ad8b2018-08-24 12:08:38 -0700734 OPTIONS.info_dict = common.LoadInfoDict(OPTIONS.input_tmp, repacking=True)
Tao Baodba59ee2018-01-09 13:21:02 -0800735
736 has_recovery = OPTIONS.info_dict.get("no_recovery") != "true"
Chris Grossa784ef12019-04-22 11:09:57 -0700737 has_boot = OPTIONS.info_dict.get("no_boot") != "true"
Steve Mucklee1b10862019-07-10 10:49:37 -0700738 has_vendor_boot = OPTIONS.info_dict.get("vendor_boot") == "true"
Tao Baodba59ee2018-01-09 13:21:02 -0800739
Chris Gross435b8fe2020-09-15 09:53:44 -0700740 # {vendor,odm,product,system_ext,vendor_dlkm,odm_dlkm, system, system_other}.img
741 # can be built from source, or dropped into target_files.zip as a prebuilt blob.
742 has_vendor = HasPartition("vendor")
743 has_odm = HasPartition("odm")
744 has_vendor_dlkm = HasPartition("vendor_dlkm")
745 has_odm_dlkm = HasPartition("odm_dlkm")
746 has_product = HasPartition("product")
747 has_system_ext = HasPartition("system_ext")
748 has_system = HasPartition("system")
749 has_system_other = HasPartition("system_other")
Chris Gross203191b2020-05-30 02:39:12 +0000750 has_userdata = OPTIONS.info_dict.get("building_userdata_image") == "true"
751 has_cache = OPTIONS.info_dict.get("building_cache_image") == "true"
Doug Zongker3c84f562014-07-31 11:06:30 -0700752
Tao Baodba59ee2018-01-09 13:21:02 -0800753 # Set up the output destination. It writes to the given directory for dir
754 # mode; otherwise appends to the given ZIP.
755 if os.path.isdir(filename):
756 output_zip = None
757 else:
Dan Willemsen2ee00d52017-03-05 19:51:56 -0800758 output_zip = zipfile.ZipFile(filename, "a",
759 compression=zipfile.ZIP_DEFLATED,
760 allowZip64=True)
Tao Baoae396d92017-11-20 11:56:43 -0800761
762 # Always make input_tmp/IMAGES available, since we may stage boot / recovery
763 # images there even under zip mode. The directory will be cleaned up as part
764 # of OPTIONS.input_tmp.
765 images_dir = os.path.join(OPTIONS.input_tmp, "IMAGES")
766 if not os.path.isdir(images_dir):
767 os.makedirs(images_dir)
Doug Zongker3c84f562014-07-31 11:06:30 -0700768
Tao Baobf70c312017-07-11 17:27:55 -0700769 # A map between partition names and their paths, which could be used when
770 # generating AVB vbmeta image.
Tao Bao3ed35d32019-10-07 20:48:48 -0700771 partitions = {}
Tao Baobf70c312017-07-11 17:27:55 -0700772
Doug Zongkerfc44a512014-08-26 13:10:25 -0700773 def banner(s):
Tao Baoa3705452019-06-24 15:33:41 -0700774 logger.info("\n\n++++ %s ++++\n\n", s)
Doug Zongker3c84f562014-07-31 11:06:30 -0700775
Chris Grossa784ef12019-04-22 11:09:57 -0700776 boot_image = None
777 if has_boot:
778 banner("boot")
Steve Muckle9793cf62020-04-08 18:27:00 -0700779 boot_images = OPTIONS.info_dict.get("boot_images")
780 if boot_images is None:
781 boot_images = "boot.img"
Kelvin Zhangc184fa12021-03-22 15:38:38 -0400782 for index, b in enumerate(boot_images.split()):
Steve Muckle9793cf62020-04-08 18:27:00 -0700783 # common.GetBootableImage() returns the image directly if present.
784 boot_image = common.GetBootableImage(
785 "IMAGES/" + b, b, OPTIONS.input_tmp, "BOOT")
786 # boot.img may be unavailable in some targets (e.g. aosp_arm64).
787 if boot_image:
788 boot_image_path = os.path.join(OPTIONS.input_tmp, "IMAGES", b)
Roopesh Nataraja3e15f6e2020-06-08 19:54:13 -0700789 # Although multiple boot images can be generated, include the image
790 # descriptor of only the first boot image in vbmeta
791 if index == 0:
Steve Muckle9793cf62020-04-08 18:27:00 -0700792 partitions['boot'] = boot_image_path
793 if not os.path.exists(boot_image_path):
794 boot_image.WriteToDir(OPTIONS.input_tmp)
795 if output_zip:
796 boot_image.AddToZip(output_zip)
Doug Zongker3c84f562014-07-31 11:06:30 -0700797
Steve Mucklee1b10862019-07-10 10:49:37 -0700798 if has_vendor_boot:
799 banner("vendor_boot")
800 vendor_boot_image = common.GetVendorBootImage(
801 "IMAGES/vendor_boot.img", "vendor_boot.img", OPTIONS.input_tmp,
802 "VENDOR_BOOT")
803 if vendor_boot_image:
804 partitions['vendor_boot'] = os.path.join(OPTIONS.input_tmp, "IMAGES",
805 "vendor_boot.img")
806 if not os.path.exists(partitions['vendor_boot']):
807 vendor_boot_image.WriteToDir(OPTIONS.input_tmp)
808 if output_zip:
809 vendor_boot_image.AddToZip(output_zip)
810
Michael Runge2e0d8fc2014-11-13 21:41:08 -0800811 recovery_image = None
Tao Baodb45efa2015-10-27 19:25:18 -0700812 if has_recovery:
813 banner("recovery")
Tao Bao262bf3f2017-07-11 17:27:55 -0700814 recovery_image = common.GetBootableImage(
815 "IMAGES/recovery.img", "recovery.img", OPTIONS.input_tmp, "RECOVERY")
816 assert recovery_image, "Failed to create recovery.img."
Tao Baobf70c312017-07-11 17:27:55 -0700817 partitions['recovery'] = os.path.join(
Tao Bao262bf3f2017-07-11 17:27:55 -0700818 OPTIONS.input_tmp, "IMAGES", "recovery.img")
Tao Baobf70c312017-07-11 17:27:55 -0700819 if not os.path.exists(partitions['recovery']):
Tao Bao262bf3f2017-07-11 17:27:55 -0700820 recovery_image.WriteToDir(OPTIONS.input_tmp)
821 if output_zip:
822 recovery_image.AddToZip(output_zip)
Doug Zongker3c84f562014-07-31 11:06:30 -0700823
Tao Baod42e97e2016-11-30 12:11:57 -0800824 banner("recovery (two-step image)")
825 # The special recovery.img for two-step package use.
826 recovery_two_step_image = common.GetBootableImage(
Tao Bao04808502019-07-25 23:11:41 -0700827 "OTA/recovery-two-step.img", "recovery-two-step.img",
Tao Baod42e97e2016-11-30 12:11:57 -0800828 OPTIONS.input_tmp, "RECOVERY", two_step_image=True)
Tao Bao262bf3f2017-07-11 17:27:55 -0700829 assert recovery_two_step_image, "Failed to create recovery-two-step.img."
830 recovery_two_step_image_path = os.path.join(
Tao Bao04808502019-07-25 23:11:41 -0700831 OPTIONS.input_tmp, "OTA", "recovery-two-step.img")
Tao Bao262bf3f2017-07-11 17:27:55 -0700832 if not os.path.exists(recovery_two_step_image_path):
833 recovery_two_step_image.WriteToDir(OPTIONS.input_tmp)
Dan Willemsen2ee00d52017-03-05 19:51:56 -0800834 if output_zip:
835 recovery_two_step_image.AddToZip(output_zip)
Tao Baod42e97e2016-11-30 12:11:57 -0800836
Bill Peckhamcc57de32019-01-29 11:01:46 -0800837 if has_system:
838 banner("system")
839 partitions['system'] = AddSystem(
840 output_zip, recovery_img=recovery_image, boot_img=boot_image)
Tao Baobf70c312017-07-11 17:27:55 -0700841
Doug Zongkerfc44a512014-08-26 13:10:25 -0700842 if has_vendor:
843 banner("vendor")
Bill Peckhame868aec2019-09-17 17:06:47 -0700844 partitions['vendor'] = AddVendor(
845 output_zip, recovery_img=recovery_image, boot_img=boot_image)
Tao Baobf70c312017-07-11 17:27:55 -0700846
Jaekyun Seokb7735d82017-11-27 17:04:47 +0900847 if has_product:
848 banner("product")
849 partitions['product'] = AddProduct(output_zip)
850
Justin Yun6151e3f2019-06-25 15:58:13 +0900851 if has_system_ext:
852 banner("system_ext")
853 partitions['system_ext'] = AddSystemExt(output_zip)
Dario Freni5f681e12018-05-29 13:09:01 +0100854
Bowgo Tsaid624fa62017-11-14 23:42:30 +0800855 if has_odm:
856 banner("odm")
857 partitions['odm'] = AddOdm(output_zip)
858
Yifan Hongcfb917a2020-05-07 14:58:20 -0700859 if has_vendor_dlkm:
860 banner("vendor_dlkm")
861 partitions['vendor_dlkm'] = AddVendorDlkm(output_zip)
862
Yifan Hongf496f1b2020-07-15 16:52:59 -0700863 if has_odm_dlkm:
864 banner("odm_dlkm")
865 partitions['odm_dlkm'] = AddOdmDlkm(output_zip)
866
Alex Light4e358ab2016-06-16 14:47:10 -0700867 if has_system_other:
868 banner("system_other")
869 AddSystemOther(output_zip)
Tao Baobf70c312017-07-11 17:27:55 -0700870
Kelvin Zhang5f0fcee2021-01-19 15:30:46 -0500871 AddApexInfo(output_zip)
872
Tianjie Xub48589a2016-08-03 19:21:52 -0700873 if not OPTIONS.is_signing:
874 banner("userdata")
875 AddUserdata(output_zip)
876 banner("cache")
877 AddCache(output_zip)
Tao Baoc633ed02017-05-30 21:46:33 -0700878
879 if OPTIONS.info_dict.get("board_bpt_enable") == "true":
David Zeuthen25328622016-04-08 15:08:03 -0400880 banner("partition-table")
881 AddPartitionTable(output_zip)
Tao Baoc633ed02017-05-30 21:46:33 -0700882
Tao Baoc633ed02017-05-30 21:46:33 -0700883 if OPTIONS.info_dict.get("has_dtbo") == "true":
884 banner("dtbo")
Tao Baobf70c312017-07-11 17:27:55 -0700885 partitions['dtbo'] = AddDtbo(output_zip)
Tao Baoc633ed02017-05-30 21:46:33 -0700886
Andrew Sculle077cf72021-02-18 10:27:29 +0000887 if OPTIONS.info_dict.get("has_pvmfw") == "true":
888 banner("pvmfw")
889 partitions['pvmfw'] = AddPvmfw(output_zip)
890
Hongguang Chenf23364d2020-04-27 18:36:36 -0700891 # Custom images.
892 custom_partitions = OPTIONS.info_dict.get(
893 "avb_custom_images_partition_list", "").strip().split()
894 for partition_name in custom_partitions:
895 partition_name = partition_name.strip()
896 banner("custom images for " + partition_name)
897 partitions[partition_name] = AddCustomImages(output_zip, partition_name)
898
Bowgo Tsai3e599ea2017-05-26 18:30:04 +0800899 if OPTIONS.info_dict.get("avb_enable") == "true":
Tao Bao744c4c72018-08-20 21:09:07 -0700900 # vbmeta_partitions includes the partitions that should be included into
901 # top-level vbmeta.img, which are the ones that are not included in any
902 # chained VBMeta image plus the chained VBMeta images themselves.
Hongguang Chenf23364d2020-04-27 18:36:36 -0700903 # Currently custom_partitions are all chained to VBMeta image.
904 vbmeta_partitions = common.AVB_PARTITIONS[:] + tuple(custom_partitions)
Tao Bao744c4c72018-08-20 21:09:07 -0700905
David Anderson7709ab22018-10-15 14:41:34 -0700906 vbmeta_system = OPTIONS.info_dict.get("avb_vbmeta_system", "").strip()
907 if vbmeta_system:
908 banner("vbmeta_system")
Tao Bao71064202018-10-22 15:08:02 -0700909 partitions["vbmeta_system"] = AddVBMeta(
David Anderson7709ab22018-10-15 14:41:34 -0700910 output_zip, partitions, "vbmeta_system", vbmeta_system.split())
Tao Bao744c4c72018-08-20 21:09:07 -0700911 vbmeta_partitions = [
912 item for item in vbmeta_partitions
David Anderson7709ab22018-10-15 14:41:34 -0700913 if item not in vbmeta_system.split()]
914 vbmeta_partitions.append("vbmeta_system")
Tao Bao744c4c72018-08-20 21:09:07 -0700915
916 vbmeta_vendor = OPTIONS.info_dict.get("avb_vbmeta_vendor", "").strip()
917 if vbmeta_vendor:
918 banner("vbmeta_vendor")
Tao Bao71064202018-10-22 15:08:02 -0700919 partitions["vbmeta_vendor"] = AddVBMeta(
Tao Bao744c4c72018-08-20 21:09:07 -0700920 output_zip, partitions, "vbmeta_vendor", vbmeta_vendor.split())
921 vbmeta_partitions = [
922 item for item in vbmeta_partitions
923 if item not in vbmeta_vendor.split()]
924 vbmeta_partitions.append("vbmeta_vendor")
925
Bowgo Tsai82182252020-11-13 11:28:17 +0800926 if OPTIONS.info_dict.get("avb_building_vbmeta_image") == "true":
927 banner("vbmeta")
928 AddVBMeta(output_zip, partitions, "vbmeta", vbmeta_partitions)
Doug Zongker3c84f562014-07-31 11:06:30 -0700929
Tao Bao48a2feb2019-06-28 11:00:05 -0700930 if OPTIONS.info_dict.get("use_dynamic_partitions") == "true":
Yo Chiange86bab42021-03-25 10:12:28 +0000931 if OPTIONS.info_dict.get("build_super_empty_partition") == "true":
932 banner("super_empty")
933 AddSuperEmpty(output_zip)
David Anderson1ef03e22018-08-30 13:11:47 -0700934
Tao Bao48a2feb2019-06-28 11:00:05 -0700935 if OPTIONS.info_dict.get("build_super_partition") == "true":
Tao Bao519d1822018-12-27 12:47:23 -0800936 if OPTIONS.info_dict.get(
Kelvin Zhangc184fa12021-03-22 15:38:38 -0400937 "build_retrofit_dynamic_partitions_ota_package") == "true":
Yifan Hongc767f7c2018-11-08 15:41:24 -0800938 banner("super split images")
939 AddSuperSplit(output_zip)
Yifan Hongc767f7c2018-11-08 15:41:24 -0800940
Tianjie Xuaaca4212016-06-28 14:34:03 -0700941 banner("radio")
Tao Baobea20ac2018-01-17 17:57:49 -0800942 ab_partitions_txt = os.path.join(OPTIONS.input_tmp, "META",
943 "ab_partitions.txt")
944 if os.path.exists(ab_partitions_txt):
Tao Baoa3705452019-06-24 15:33:41 -0700945 with open(ab_partitions_txt) as f:
Tao Baobea20ac2018-01-17 17:57:49 -0800946 ab_partitions = f.readlines()
Tianjie Xucfa86222016-03-07 16:31:19 -0800947
Tao Bao5277d102018-04-17 23:47:21 -0700948 # For devices using A/B update, make sure we have all the needed images
949 # ready under IMAGES/ or RADIO/.
950 CheckAbOtaImages(output_zip, ab_partitions)
Tianjie Xuaaca4212016-06-28 14:34:03 -0700951
Tianjie Xu861f4132018-09-12 11:49:33 -0700952 # Generate care_map.pb for ab_partitions, then write this file to
953 # target_files package.
Tianjie Xu4c05f4a2018-09-14 16:24:41 -0700954 AddCareMapForAbOta(output_zip, ab_partitions, partitions)
Tianjie Xucfa86222016-03-07 16:31:19 -0800955
Tao Bao95a95c32017-06-16 15:30:23 -0700956 # Radio images that need to be packed into IMAGES/, and product-img.zip.
Tao Baobea20ac2018-01-17 17:57:49 -0800957 pack_radioimages_txt = os.path.join(
Tao Bao95a95c32017-06-16 15:30:23 -0700958 OPTIONS.input_tmp, "META", "pack_radioimages.txt")
Tao Baobea20ac2018-01-17 17:57:49 -0800959 if os.path.exists(pack_radioimages_txt):
Tao Baoa3705452019-06-24 15:33:41 -0700960 with open(pack_radioimages_txt) as f:
Tao Baobea20ac2018-01-17 17:57:49 -0800961 AddPackRadioImages(output_zip, f.readlines())
Tao Bao95a95c32017-06-16 15:30:23 -0700962
Dan Willemsen2ee00d52017-03-05 19:51:56 -0800963 if output_zip:
964 common.ZipClose(output_zip)
Tianjie Xu9ac4cb02017-06-09 16:58:03 -0700965 if OPTIONS.replace_updated_files_list:
966 ReplaceUpdatedFiles(output_zip.filename,
967 OPTIONS.replace_updated_files_list)
Tianjie Xu38af07f2017-05-25 17:38:53 -0700968
Doug Zongker3c84f562014-07-31 11:06:30 -0700969
Doug Zongker3c84f562014-07-31 11:06:30 -0700970def main(argv):
Baligh Uddin59f4ff12015-09-16 21:20:30 -0700971 def option_handler(o, a):
Michael Runge2e0d8fc2014-11-13 21:41:08 -0800972 if o in ("-a", "--add_missing"):
973 OPTIONS.add_missing = True
974 elif o in ("-r", "--rebuild_recovery",):
975 OPTIONS.rebuild_recovery = True
Baligh Uddin59f4ff12015-09-16 21:20:30 -0700976 elif o == "--replace_verity_private_key":
977 OPTIONS.replace_verity_private_key = (True, a)
978 elif o == "--replace_verity_public_key":
979 OPTIONS.replace_verity_public_key = (True, a)
Tianjie Xub48589a2016-08-03 19:21:52 -0700980 elif o == "--is_signing":
981 OPTIONS.is_signing = True
Michael Runge2e0d8fc2014-11-13 21:41:08 -0800982 else:
983 return False
984 return True
985
Dan Albert8b72aef2015-03-23 19:13:21 -0700986 args = common.ParseOptions(
987 argv, __doc__, extra_opts="ar",
Baligh Uddin59f4ff12015-09-16 21:20:30 -0700988 extra_long_opts=["add_missing", "rebuild_recovery",
989 "replace_verity_public_key=",
990 "replace_verity_private_key=",
Tao Bao45810422016-10-17 16:20:12 -0700991 "is_signing"],
Dan Albert8b72aef2015-03-23 19:13:21 -0700992 extra_option_handler=option_handler)
Michael Runge2e0d8fc2014-11-13 21:41:08 -0800993
Doug Zongker3c84f562014-07-31 11:06:30 -0700994 if len(args) != 1:
995 common.Usage(__doc__)
996 sys.exit(1)
997
Tao Bao32fcdab2018-10-12 10:30:39 -0700998 common.InitLogging()
999
Doug Zongker3c84f562014-07-31 11:06:30 -07001000 AddImagesToTargetFiles(args[0])
Tao Bao32fcdab2018-10-12 10:30:39 -07001001 logger.info("done.")
Doug Zongker3c84f562014-07-31 11:06:30 -07001002
Kelvin Zhangc184fa12021-03-22 15:38:38 -04001003
Doug Zongker3c84f562014-07-31 11:06:30 -07001004if __name__ == '__main__':
1005 try:
1006 common.CloseInheritedPipes()
1007 main(sys.argv[1:])
Tao Bao32fcdab2018-10-12 10:30:39 -07001008 except common.ExternalError:
1009 logger.exception("\n ERROR:\n")
Doug Zongker3c84f562014-07-31 11:06:30 -07001010 sys.exit(1)
Doug Zongkerfc44a512014-08-26 13:10:25 -07001011 finally:
1012 common.Cleanup()