blob: c80d4bd9faa7562a6c2e4c73f321a6b61caab15b [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
Doug Zongker3c84f562014-07-31 11:06:30 -070048import sys
49
50if sys.hexversion < 0x02070000:
Tao Bao89fbb0f2017-01-10 10:47:58 -080051 print("Python 2.7 or newer is required.", file=sys.stderr)
Doug Zongker3c84f562014-07-31 11:06:30 -070052 sys.exit(1)
53
Tao Bao822f5842015-09-30 16:01:14 -070054import datetime
Doug Zongker3c84f562014-07-31 11:06:30 -070055import errno
56import os
David Zeuthend995f4b2016-01-29 16:59:17 -050057import shlex
Ying Wang2a048392015-06-25 13:56:53 -070058import shutil
David Zeuthend995f4b2016-01-29 16:59:17 -050059import subprocess
Doug Zongker3c84f562014-07-31 11:06:30 -070060import tempfile
61import zipfile
62
Doug Zongker3c84f562014-07-31 11:06:30 -070063import build_image
64import common
Tianjie Xucfa86222016-03-07 16:31:19 -080065import sparse_img
Doug Zongker3c84f562014-07-31 11:06:30 -070066
67OPTIONS = common.OPTIONS
68
Michael Runge2e0d8fc2014-11-13 21:41:08 -080069OPTIONS.add_missing = False
70OPTIONS.rebuild_recovery = False
Baligh Uddin59f4ff12015-09-16 21:20:30 -070071OPTIONS.replace_verity_public_key = False
72OPTIONS.replace_verity_private_key = False
Tianjie Xub48589a2016-08-03 19:21:52 -070073OPTIONS.is_signing = False
Doug Zongker3c84f562014-07-31 11:06:30 -070074
Tianjie Xucfa86222016-03-07 16:31:19 -080075def GetCareMap(which, imgname):
76 """Generate care_map of system (or vendor) partition"""
77
78 assert which in ("system", "vendor")
79 _, blk_device = common.GetTypeAndDevice("/" + which, OPTIONS.info_dict)
80
81 simg = sparse_img.SparseImage(imgname)
82 care_map_list = []
83 care_map_list.append(blk_device)
84 care_map_list.append(simg.care_map.to_string_raw())
85 return care_map_list
86
87
Michael Runge2e0d8fc2014-11-13 21:41:08 -080088def AddSystem(output_zip, prefix="IMAGES/", recovery_img=None, boot_img=None):
Doug Zongker3c84f562014-07-31 11:06:30 -070089 """Turn the contents of SYSTEM into a system image and store it in
David Zeuthend995f4b2016-01-29 16:59:17 -050090 output_zip. Returns the name of the system image file."""
Michael Runge2e0d8fc2014-11-13 21:41:08 -080091
92 prebuilt_path = os.path.join(OPTIONS.input_tmp, prefix, "system.img")
93 if os.path.exists(prebuilt_path):
Tao Bao89fbb0f2017-01-10 10:47:58 -080094 print("system.img already exists in %s, no need to rebuild..." % (prefix,))
David Zeuthend995f4b2016-01-29 16:59:17 -050095 return prebuilt_path
Michael Runge2e0d8fc2014-11-13 21:41:08 -080096
97 def output_sink(fn, data):
Dan Albert8b72aef2015-03-23 19:13:21 -070098 ofile = open(os.path.join(OPTIONS.input_tmp, "SYSTEM", fn), "w")
99 ofile.write(data)
100 ofile.close()
Michael Runge2e0d8fc2014-11-13 21:41:08 -0800101
102 if OPTIONS.rebuild_recovery:
Tao Bao89fbb0f2017-01-10 10:47:58 -0800103 print("Building new recovery patch")
Dan Albert8b72aef2015-03-23 19:13:21 -0700104 common.MakeRecoveryPatch(OPTIONS.input_tmp, output_sink, recovery_img,
105 boot_img, info_dict=OPTIONS.info_dict)
Michael Runge2e0d8fc2014-11-13 21:41:08 -0800106
Doug Zongkerfc44a512014-08-26 13:10:25 -0700107 block_list = common.MakeTempFile(prefix="system-blocklist-", suffix=".map")
108 imgname = BuildSystem(OPTIONS.input_tmp, OPTIONS.info_dict,
109 block_list=block_list)
David Zeuthend995f4b2016-01-29 16:59:17 -0500110
Dan Albert8e0178d2015-01-27 15:53:15 -0800111 common.ZipWrite(output_zip, imgname, prefix + "system.img")
112 common.ZipWrite(output_zip, block_list, prefix + "system.map")
David Zeuthend995f4b2016-01-29 16:59:17 -0500113 return imgname
Doug Zongkerfc44a512014-08-26 13:10:25 -0700114
115
116def BuildSystem(input_dir, info_dict, block_list=None):
117 """Build the (sparse) system image and return the name of a temp
118 file containing it."""
119 return CreateImage(input_dir, info_dict, "system", block_list=block_list)
120
121
Alex Light4e358ab2016-06-16 14:47:10 -0700122def AddSystemOther(output_zip, prefix="IMAGES/"):
123 """Turn the contents of SYSTEM_OTHER into a system_other image
124 and store it in output_zip."""
125
126 prebuilt_path = os.path.join(OPTIONS.input_tmp, prefix, "system_other.img")
127 if os.path.exists(prebuilt_path):
Tao Bao89fbb0f2017-01-10 10:47:58 -0800128 print("system_other.img already exists in %s, no need to rebuild..." % (
129 prefix,))
Alex Light4e358ab2016-06-16 14:47:10 -0700130 return
131
132 imgname = BuildSystemOther(OPTIONS.input_tmp, OPTIONS.info_dict)
133 common.ZipWrite(output_zip, imgname, prefix + "system_other.img")
134
135def BuildSystemOther(input_dir, info_dict):
136 """Build the (sparse) system_other image and return the name of a temp
137 file containing it."""
138 return CreateImage(input_dir, info_dict, "system_other", block_list=None)
139
140
Doug Zongkerfc44a512014-08-26 13:10:25 -0700141def AddVendor(output_zip, prefix="IMAGES/"):
142 """Turn the contents of VENDOR into a vendor image and store in it
143 output_zip."""
Michael Runge2e0d8fc2014-11-13 21:41:08 -0800144
145 prebuilt_path = os.path.join(OPTIONS.input_tmp, prefix, "vendor.img")
146 if os.path.exists(prebuilt_path):
Tao Bao89fbb0f2017-01-10 10:47:58 -0800147 print("vendor.img already exists in %s, no need to rebuild..." % (prefix,))
Tianjie Xucfa86222016-03-07 16:31:19 -0800148 return prebuilt_path
Michael Runge2e0d8fc2014-11-13 21:41:08 -0800149
Doug Zongkerfc44a512014-08-26 13:10:25 -0700150 block_list = common.MakeTempFile(prefix="vendor-blocklist-", suffix=".map")
151 imgname = BuildVendor(OPTIONS.input_tmp, OPTIONS.info_dict,
Dan Albert8b72aef2015-03-23 19:13:21 -0700152 block_list=block_list)
Dan Albert8e0178d2015-01-27 15:53:15 -0800153 common.ZipWrite(output_zip, imgname, prefix + "vendor.img")
154 common.ZipWrite(output_zip, block_list, prefix + "vendor.map")
Tianjie Xucfa86222016-03-07 16:31:19 -0800155 return imgname
Doug Zongker3c84f562014-07-31 11:06:30 -0700156
157
Doug Zongkerfc44a512014-08-26 13:10:25 -0700158def BuildVendor(input_dir, info_dict, block_list=None):
159 """Build the (sparse) vendor image and return the name of a temp
160 file containing it."""
161 return CreateImage(input_dir, info_dict, "vendor", block_list=block_list)
162
163
164def CreateImage(input_dir, info_dict, what, block_list=None):
Tao Bao89fbb0f2017-01-10 10:47:58 -0800165 print("creating " + what + ".img...")
Doug Zongker3c84f562014-07-31 11:06:30 -0700166
Doug Zongkerfc44a512014-08-26 13:10:25 -0700167 img = common.MakeTempFile(prefix=what + "-", suffix=".img")
Doug Zongker3c84f562014-07-31 11:06:30 -0700168
169 # The name of the directory it is making an image out of matters to
170 # mkyaffs2image. It wants "system" but we have a directory named
171 # "SYSTEM", so create a symlink.
172 try:
173 os.symlink(os.path.join(input_dir, what.upper()),
174 os.path.join(input_dir, what))
Dan Albert8b72aef2015-03-23 19:13:21 -0700175 except OSError as e:
176 # bogus error on my mac version?
177 # File "./build/tools/releasetools/img_from_target_files"
178 # os.path.join(OPTIONS.input_tmp, "system"))
179 # OSError: [Errno 17] File exists
180 if e.errno == errno.EEXIST:
Doug Zongker3c84f562014-07-31 11:06:30 -0700181 pass
182
183 image_props = build_image.ImagePropFromGlobalDict(info_dict, what)
184 fstab = info_dict["fstab"]
Tianjie Xucfa86222016-03-07 16:31:19 -0800185 mount_point = "/" + what
186 if fstab and mount_point in fstab:
187 image_props["fs_type"] = fstab[mount_point].fs_type
Doug Zongker3c84f562014-07-31 11:06:30 -0700188
Tao Bao822f5842015-09-30 16:01:14 -0700189 # Use a fixed timestamp (01/01/2009) when packaging the image.
190 # Bug: 24377993
191 epoch = datetime.datetime.fromtimestamp(0)
192 timestamp = (datetime.datetime(2009, 1, 1) - epoch).total_seconds()
193 image_props["timestamp"] = int(timestamp)
194
Doug Zongker3c84f562014-07-31 11:06:30 -0700195 if what == "system":
196 fs_config_prefix = ""
197 else:
198 fs_config_prefix = what + "_"
199
200 fs_config = os.path.join(
201 input_dir, "META/" + fs_config_prefix + "filesystem_config.txt")
Dan Albert8b72aef2015-03-23 19:13:21 -0700202 if not os.path.exists(fs_config):
203 fs_config = None
Doug Zongker3c84f562014-07-31 11:06:30 -0700204
Ying Wanga2292c92015-03-24 19:07:40 -0700205 # Override values loaded from info_dict.
206 if fs_config:
207 image_props["fs_config"] = fs_config
Ying Wanga2292c92015-03-24 19:07:40 -0700208 if block_list:
209 image_props["block_list"] = block_list
Ying Wanga2292c92015-03-24 19:07:40 -0700210
Doug Zongker3c84f562014-07-31 11:06:30 -0700211 succ = build_image.BuildImage(os.path.join(input_dir, what),
Ying Wanga2292c92015-03-24 19:07:40 -0700212 image_props, img)
Doug Zongker3c84f562014-07-31 11:06:30 -0700213 assert succ, "build " + what + ".img image failed"
214
Doug Zongkerfc44a512014-08-26 13:10:25 -0700215 return img
Doug Zongker3c84f562014-07-31 11:06:30 -0700216
217
218def AddUserdata(output_zip, prefix="IMAGES/"):
Ying Wang2a048392015-06-25 13:56:53 -0700219 """Create a userdata image and store it in output_zip.
220
221 In most case we just create and store an empty userdata.img;
222 But the invoker can also request to create userdata.img with real
223 data from the target files, by setting "userdata_img_with_data=true"
224 in OPTIONS.info_dict.
225 """
Doug Zongker3c84f562014-07-31 11:06:30 -0700226
Michael Runge2e0d8fc2014-11-13 21:41:08 -0800227 prebuilt_path = os.path.join(OPTIONS.input_tmp, prefix, "userdata.img")
228 if os.path.exists(prebuilt_path):
Tao Bao89fbb0f2017-01-10 10:47:58 -0800229 print("userdata.img already exists in %s, no need to rebuild..." % (
230 prefix,))
Michael Runge2e0d8fc2014-11-13 21:41:08 -0800231 return
232
Elliott Hughes305b0882016-06-15 17:04:54 -0700233 # Skip userdata.img if no size.
Tao Bao2c15d9e2015-07-09 11:51:16 -0700234 image_props = build_image.ImagePropFromGlobalDict(OPTIONS.info_dict, "data")
Elliott Hughes305b0882016-06-15 17:04:54 -0700235 if not image_props.get("partition_size"):
Doug Zongker3c84f562014-07-31 11:06:30 -0700236 return
237
Tao Bao89fbb0f2017-01-10 10:47:58 -0800238 print("creating userdata.img...")
Doug Zongker3c84f562014-07-31 11:06:30 -0700239
Tao Bao822f5842015-09-30 16:01:14 -0700240 # Use a fixed timestamp (01/01/2009) when packaging the image.
241 # Bug: 24377993
242 epoch = datetime.datetime.fromtimestamp(0)
243 timestamp = (datetime.datetime(2009, 1, 1) - epoch).total_seconds()
244 image_props["timestamp"] = int(timestamp)
245
Doug Zongker3c84f562014-07-31 11:06:30 -0700246 # The name of the directory it is making an image out of matters to
247 # mkyaffs2image. So we create a temp dir, and within it we create an
Ying Wang2a048392015-06-25 13:56:53 -0700248 # empty dir named "data", or a symlink to the DATA dir,
249 # and build the image from that.
Doug Zongker3c84f562014-07-31 11:06:30 -0700250 temp_dir = tempfile.mkdtemp()
251 user_dir = os.path.join(temp_dir, "data")
Ying Wang2a048392015-06-25 13:56:53 -0700252 empty = (OPTIONS.info_dict.get("userdata_img_with_data") != "true")
253 if empty:
254 # Create an empty dir.
255 os.mkdir(user_dir)
256 else:
257 # Symlink to the DATA dir.
258 os.symlink(os.path.join(OPTIONS.input_tmp, "DATA"),
259 user_dir)
260
Doug Zongker3c84f562014-07-31 11:06:30 -0700261 img = tempfile.NamedTemporaryFile()
262
263 fstab = OPTIONS.info_dict["fstab"]
264 if fstab:
Dan Albert8b72aef2015-03-23 19:13:21 -0700265 image_props["fs_type"] = fstab["/data"].fs_type
Doug Zongker3c84f562014-07-31 11:06:30 -0700266 succ = build_image.BuildImage(user_dir, image_props, img.name)
267 assert succ, "build userdata.img image failed"
268
269 common.CheckSize(img.name, "userdata.img", OPTIONS.info_dict)
Tao Bao2ed665a2015-04-01 11:21:55 -0700270 common.ZipWrite(output_zip, img.name, prefix + "userdata.img")
Doug Zongker3c84f562014-07-31 11:06:30 -0700271 img.close()
Ying Wang2a048392015-06-25 13:56:53 -0700272 shutil.rmtree(temp_dir)
Doug Zongker3c84f562014-07-31 11:06:30 -0700273
274
David Zeuthen2ce63ed2016-09-15 13:43:54 -0400275def AddVBMeta(output_zip, boot_img_path, system_img_path, prefix="IMAGES/"):
276 """Create a VBMeta image and store it in output_zip."""
277 _, img_file_name = tempfile.mkstemp()
278 avbtool = os.getenv('AVBTOOL') or "avbtool"
279 cmd = [avbtool, "make_vbmeta_image",
280 "--output", img_file_name,
281 "--include_descriptors_from_image", boot_img_path,
282 "--include_descriptors_from_image", system_img_path,
283 "--generate_dm_verity_cmdline_from_hashtree", system_img_path]
284 common.AppendAVBSigningArgs(cmd)
285 args = OPTIONS.info_dict.get("board_avb_make_vbmeta_image_args", None)
286 if args and args.strip():
287 cmd.extend(shlex.split(args))
288 p = common.Run(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
289 p.communicate()
290 assert p.returncode == 0, "avbtool make_vbmeta_image failed"
291 common.ZipWrite(output_zip, img_file_name, prefix + "vbmeta.img")
292
293
David Zeuthen25328622016-04-08 15:08:03 -0400294def AddPartitionTable(output_zip, prefix="IMAGES/"):
295 """Create a partition table image and store it in output_zip."""
296
297 _, img_file_name = tempfile.mkstemp()
298 _, bpt_file_name = tempfile.mkstemp()
299
300 # use BPTTOOL from environ, or "bpttool" if empty or not set.
301 bpttool = os.getenv("BPTTOOL") or "bpttool"
302 cmd = [bpttool, "make_table", "--output_json", bpt_file_name,
303 "--output_gpt", img_file_name]
304 input_files_str = OPTIONS.info_dict["board_bpt_input_files"]
305 input_files = input_files_str.split(" ")
306 for i in input_files:
307 cmd.extend(["--input", i])
308 disk_size = OPTIONS.info_dict.get("board_bpt_disk_size")
309 if disk_size:
310 cmd.extend(["--disk_size", disk_size])
311 args = OPTIONS.info_dict.get("board_bpt_make_table_args")
312 if args:
313 cmd.extend(shlex.split(args))
314
315 p = common.Run(cmd, stdout=subprocess.PIPE)
316 p.communicate()
317 assert p.returncode == 0, "bpttool make_table failed"
318
319 common.ZipWrite(output_zip, img_file_name, prefix + "partition-table.img")
320 common.ZipWrite(output_zip, bpt_file_name, prefix + "partition-table.bpt")
321
322
Doug Zongker3c84f562014-07-31 11:06:30 -0700323def AddCache(output_zip, prefix="IMAGES/"):
324 """Create an empty cache image and store it in output_zip."""
325
Michael Runge2e0d8fc2014-11-13 21:41:08 -0800326 prebuilt_path = os.path.join(OPTIONS.input_tmp, prefix, "cache.img")
327 if os.path.exists(prebuilt_path):
Tao Bao89fbb0f2017-01-10 10:47:58 -0800328 print("cache.img already exists in %s, no need to rebuild..." % (prefix,))
Michael Runge2e0d8fc2014-11-13 21:41:08 -0800329 return
330
Tao Bao2c15d9e2015-07-09 11:51:16 -0700331 image_props = build_image.ImagePropFromGlobalDict(OPTIONS.info_dict, "cache")
Doug Zongker3c84f562014-07-31 11:06:30 -0700332 # The build system has to explicitly request for cache.img.
333 if "fs_type" not in image_props:
334 return
335
Tao Bao89fbb0f2017-01-10 10:47:58 -0800336 print("creating cache.img...")
Doug Zongker3c84f562014-07-31 11:06:30 -0700337
Tao Bao822f5842015-09-30 16:01:14 -0700338 # Use a fixed timestamp (01/01/2009) when packaging the image.
339 # Bug: 24377993
340 epoch = datetime.datetime.fromtimestamp(0)
341 timestamp = (datetime.datetime(2009, 1, 1) - epoch).total_seconds()
342 image_props["timestamp"] = int(timestamp)
343
Doug Zongker3c84f562014-07-31 11:06:30 -0700344 # The name of the directory it is making an image out of matters to
345 # mkyaffs2image. So we create a temp dir, and within it we create an
346 # empty dir named "cache", and build the image from that.
347 temp_dir = tempfile.mkdtemp()
348 user_dir = os.path.join(temp_dir, "cache")
349 os.mkdir(user_dir)
350 img = tempfile.NamedTemporaryFile()
351
352 fstab = OPTIONS.info_dict["fstab"]
353 if fstab:
Dan Albert8b72aef2015-03-23 19:13:21 -0700354 image_props["fs_type"] = fstab["/cache"].fs_type
Doug Zongker3c84f562014-07-31 11:06:30 -0700355 succ = build_image.BuildImage(user_dir, image_props, img.name)
356 assert succ, "build cache.img image failed"
357
358 common.CheckSize(img.name, "cache.img", OPTIONS.info_dict)
Tao Bao2ed665a2015-04-01 11:21:55 -0700359 common.ZipWrite(output_zip, img.name, prefix + "cache.img")
Doug Zongker3c84f562014-07-31 11:06:30 -0700360 img.close()
361 os.rmdir(user_dir)
362 os.rmdir(temp_dir)
363
364
365def AddImagesToTargetFiles(filename):
366 OPTIONS.input_tmp, input_zip = common.UnzipTemp(filename)
Doug Zongkerfc44a512014-08-26 13:10:25 -0700367
Michael Runge2e0d8fc2014-11-13 21:41:08 -0800368 if not OPTIONS.add_missing:
369 for n in input_zip.namelist():
370 if n.startswith("IMAGES/"):
Tao Bao89fbb0f2017-01-10 10:47:58 -0800371 print("target_files appears to already contain images.")
Michael Runge2e0d8fc2014-11-13 21:41:08 -0800372 sys.exit(1)
Doug Zongkerfc44a512014-08-26 13:10:25 -0700373
Doug Zongker3c84f562014-07-31 11:06:30 -0700374 try:
Doug Zongkerfc44a512014-08-26 13:10:25 -0700375 input_zip.getinfo("VENDOR/")
376 has_vendor = True
377 except KeyError:
378 has_vendor = False
Doug Zongker3c84f562014-07-31 11:06:30 -0700379
Alex Light4e358ab2016-06-16 14:47:10 -0700380 has_system_other = "SYSTEM_OTHER/" in input_zip.namelist()
381
Tao Bao2c15d9e2015-07-09 11:51:16 -0700382 OPTIONS.info_dict = common.LoadInfoDict(input_zip, OPTIONS.input_tmp)
Doug Zongker3c84f562014-07-31 11:06:30 -0700383
Tao Bao2ed665a2015-04-01 11:21:55 -0700384 common.ZipClose(input_zip)
Doug Zongkerfc44a512014-08-26 13:10:25 -0700385 output_zip = zipfile.ZipFile(filename, "a",
Tao Bao9c84e502016-08-22 10:31:05 -0700386 compression=zipfile.ZIP_DEFLATED,
387 allowZip64=True)
Doug Zongker3c84f562014-07-31 11:06:30 -0700388
Tao Baodb45efa2015-10-27 19:25:18 -0700389 has_recovery = (OPTIONS.info_dict.get("no_recovery") != "true")
David Zeuthend995f4b2016-01-29 16:59:17 -0500390 system_root_image = (OPTIONS.info_dict.get("system_root_image", None) == "true")
Tao Baodb45efa2015-10-27 19:25:18 -0700391
Doug Zongkerfc44a512014-08-26 13:10:25 -0700392 def banner(s):
Tao Bao89fbb0f2017-01-10 10:47:58 -0800393 print("\n\n++++ " + s + " ++++\n\n")
Doug Zongker3c84f562014-07-31 11:06:30 -0700394
Michael Runge2e0d8fc2014-11-13 21:41:08 -0800395 prebuilt_path = os.path.join(OPTIONS.input_tmp, "IMAGES", "boot.img")
396 boot_image = None
397 if os.path.exists(prebuilt_path):
David Zeuthend995f4b2016-01-29 16:59:17 -0500398 banner("boot")
Tao Bao89fbb0f2017-01-10 10:47:58 -0800399 print("boot.img already exists in IMAGES/, no need to rebuild...")
Michael Runge2e0d8fc2014-11-13 21:41:08 -0800400 if OPTIONS.rebuild_recovery:
401 boot_image = common.GetBootableImage(
402 "IMAGES/boot.img", "boot.img", OPTIONS.input_tmp, "BOOT")
403 else:
David Zeuthen2ce63ed2016-09-15 13:43:54 -0400404 banner("boot")
405 boot_image = common.GetBootableImage(
Michael Runge2e0d8fc2014-11-13 21:41:08 -0800406 "IMAGES/boot.img", "boot.img", OPTIONS.input_tmp, "BOOT")
David Zeuthen2ce63ed2016-09-15 13:43:54 -0400407 if boot_image:
408 boot_image.AddToZip(output_zip)
Doug Zongker3c84f562014-07-31 11:06:30 -0700409
Michael Runge2e0d8fc2014-11-13 21:41:08 -0800410 recovery_image = None
Tao Baodb45efa2015-10-27 19:25:18 -0700411 if has_recovery:
412 banner("recovery")
413 prebuilt_path = os.path.join(OPTIONS.input_tmp, "IMAGES", "recovery.img")
414 if os.path.exists(prebuilt_path):
Tao Bao89fbb0f2017-01-10 10:47:58 -0800415 print("recovery.img already exists in IMAGES/, no need to rebuild...")
Tao Baodb45efa2015-10-27 19:25:18 -0700416 if OPTIONS.rebuild_recovery:
417 recovery_image = common.GetBootableImage(
418 "IMAGES/recovery.img", "recovery.img", OPTIONS.input_tmp,
419 "RECOVERY")
420 else:
Michael Runge2e0d8fc2014-11-13 21:41:08 -0800421 recovery_image = common.GetBootableImage(
422 "IMAGES/recovery.img", "recovery.img", OPTIONS.input_tmp, "RECOVERY")
Tao Baodb45efa2015-10-27 19:25:18 -0700423 if recovery_image:
424 recovery_image.AddToZip(output_zip)
Doug Zongker3c84f562014-07-31 11:06:30 -0700425
Tao Baod42e97e2016-11-30 12:11:57 -0800426 banner("recovery (two-step image)")
427 # The special recovery.img for two-step package use.
428 recovery_two_step_image = common.GetBootableImage(
429 "IMAGES/recovery-two-step.img", "recovery-two-step.img",
430 OPTIONS.input_tmp, "RECOVERY", two_step_image=True)
431 if recovery_two_step_image:
432 recovery_two_step_image.AddToZip(output_zip)
433
Doug Zongkerfc44a512014-08-26 13:10:25 -0700434 banner("system")
David Zeuthend995f4b2016-01-29 16:59:17 -0500435 system_img_path = AddSystem(
436 output_zip, recovery_img=recovery_image, boot_img=boot_image)
Tianjie Xu737afb92016-07-11 11:42:53 -0700437 vendor_img_path = None
Doug Zongkerfc44a512014-08-26 13:10:25 -0700438 if has_vendor:
439 banner("vendor")
Tianjie Xu737afb92016-07-11 11:42:53 -0700440 vendor_img_path = AddVendor(output_zip)
Alex Light4e358ab2016-06-16 14:47:10 -0700441 if has_system_other:
442 banner("system_other")
443 AddSystemOther(output_zip)
Tianjie Xub48589a2016-08-03 19:21:52 -0700444 if not OPTIONS.is_signing:
445 banner("userdata")
446 AddUserdata(output_zip)
447 banner("cache")
448 AddCache(output_zip)
David Zeuthen25328622016-04-08 15:08:03 -0400449 if OPTIONS.info_dict.get("board_bpt_enable", None) == "true":
450 banner("partition-table")
451 AddPartitionTable(output_zip)
David Zeuthen2ce63ed2016-09-15 13:43:54 -0400452 if OPTIONS.info_dict.get("board_avb_enable", None) == "true":
453 banner("vbmeta")
454 boot_contents = boot_image.WriteToTemp()
455 AddVBMeta(output_zip, boot_contents.name, system_img_path)
Doug Zongker3c84f562014-07-31 11:06:30 -0700456
Wei Wang2e735ca2016-05-10 22:48:13 -0700457 # For devices using A/B update, copy over images from RADIO/ and/or
458 # VENDOR_IMAGES/ to IMAGES/ and make sure we have all the needed
459 # images ready under IMAGES/. All images should have '.img' as extension.
Tianjie Xuaaca4212016-06-28 14:34:03 -0700460 banner("radio")
Tao Baoa0421cd2015-11-16 16:32:27 -0800461 ab_partitions = os.path.join(OPTIONS.input_tmp, "META", "ab_partitions.txt")
462 if os.path.exists(ab_partitions):
463 with open(ab_partitions, 'r') as f:
464 lines = f.readlines()
Tianjie Xucfa86222016-03-07 16:31:19 -0800465 # For devices using A/B update, generate care_map for system and vendor
466 # partitions (if present), then write this file to target_files package.
467 care_map_list = []
Tao Baoa0421cd2015-11-16 16:32:27 -0800468 for line in lines:
Tianjie Xucfa86222016-03-07 16:31:19 -0800469 if line.strip() == "system" and OPTIONS.info_dict.get(
470 "system_verity_block_device", None) is not None:
Tianjie Xu737afb92016-07-11 11:42:53 -0700471 assert os.path.exists(system_img_path)
472 care_map_list += GetCareMap("system", system_img_path)
Tianjie Xucfa86222016-03-07 16:31:19 -0800473 if line.strip() == "vendor" and OPTIONS.info_dict.get(
474 "vendor_verity_block_device", None) is not None:
Tianjie Xu737afb92016-07-11 11:42:53 -0700475 assert os.path.exists(vendor_img_path)
476 care_map_list += GetCareMap("vendor", vendor_img_path)
Tianjie Xucfa86222016-03-07 16:31:19 -0800477
Tao Baoa0421cd2015-11-16 16:32:27 -0800478 img_name = line.strip() + ".img"
Tianjie Xuaaca4212016-06-28 14:34:03 -0700479 prebuilt_path = os.path.join(OPTIONS.input_tmp, "IMAGES", img_name)
480 if os.path.exists(prebuilt_path):
Tao Bao89fbb0f2017-01-10 10:47:58 -0800481 print("%s already exists, no need to overwrite..." % (img_name,))
Tianjie Xuaaca4212016-06-28 14:34:03 -0700482 continue
483
Tao Baoa0421cd2015-11-16 16:32:27 -0800484 img_radio_path = os.path.join(OPTIONS.input_tmp, "RADIO", img_name)
Wei Wang2e735ca2016-05-10 22:48:13 -0700485 img_vendor_dir = os.path.join(
486 OPTIONS.input_tmp, "VENDOR_IMAGES")
Tao Baoa0421cd2015-11-16 16:32:27 -0800487 if os.path.exists(img_radio_path):
488 common.ZipWrite(output_zip, img_radio_path,
489 os.path.join("IMAGES", img_name))
Wei Wang2e735ca2016-05-10 22:48:13 -0700490 else:
491 for root, _, files in os.walk(img_vendor_dir):
492 if img_name in files:
493 common.ZipWrite(output_zip, os.path.join(root, img_name),
494 os.path.join("IMAGES", img_name))
495 break
Tao Baoa0421cd2015-11-16 16:32:27 -0800496
497 # Zip spec says: All slashes MUST be forward slashes.
498 img_path = 'IMAGES/' + img_name
499 assert img_path in output_zip.namelist(), "cannot find " + img_name
500
Tianjie Xucfa86222016-03-07 16:31:19 -0800501 if care_map_list:
502 file_path = "META/care_map.txt"
503 common.ZipWriteStr(output_zip, file_path, '\n'.join(care_map_list))
504
Tao Bao2ed665a2015-04-01 11:21:55 -0700505 common.ZipClose(output_zip)
Doug Zongker3c84f562014-07-31 11:06:30 -0700506
Doug Zongker3c84f562014-07-31 11:06:30 -0700507def main(argv):
Baligh Uddin59f4ff12015-09-16 21:20:30 -0700508 def option_handler(o, a):
Michael Runge2e0d8fc2014-11-13 21:41:08 -0800509 if o in ("-a", "--add_missing"):
510 OPTIONS.add_missing = True
511 elif o in ("-r", "--rebuild_recovery",):
512 OPTIONS.rebuild_recovery = True
Baligh Uddin59f4ff12015-09-16 21:20:30 -0700513 elif o == "--replace_verity_private_key":
514 OPTIONS.replace_verity_private_key = (True, a)
515 elif o == "--replace_verity_public_key":
516 OPTIONS.replace_verity_public_key = (True, a)
Tianjie Xub48589a2016-08-03 19:21:52 -0700517 elif o == "--is_signing":
518 OPTIONS.is_signing = True
Michael Runge2e0d8fc2014-11-13 21:41:08 -0800519 else:
520 return False
521 return True
522
Dan Albert8b72aef2015-03-23 19:13:21 -0700523 args = common.ParseOptions(
524 argv, __doc__, extra_opts="ar",
Baligh Uddin59f4ff12015-09-16 21:20:30 -0700525 extra_long_opts=["add_missing", "rebuild_recovery",
526 "replace_verity_public_key=",
527 "replace_verity_private_key=",
Tao Bao45810422016-10-17 16:20:12 -0700528 "is_signing"],
Dan Albert8b72aef2015-03-23 19:13:21 -0700529 extra_option_handler=option_handler)
Michael Runge2e0d8fc2014-11-13 21:41:08 -0800530
Doug Zongker3c84f562014-07-31 11:06:30 -0700531
532 if len(args) != 1:
533 common.Usage(__doc__)
534 sys.exit(1)
535
536 AddImagesToTargetFiles(args[0])
Tao Bao89fbb0f2017-01-10 10:47:58 -0800537 print("done.")
Doug Zongker3c84f562014-07-31 11:06:30 -0700538
539if __name__ == '__main__':
540 try:
541 common.CloseInheritedPipes()
542 main(sys.argv[1:])
Dan Albert8b72aef2015-03-23 19:13:21 -0700543 except common.ExternalError as e:
Tao Bao89fbb0f2017-01-10 10:47:58 -0800544 print("\n ERROR: %s\n" % (e,))
Doug Zongker3c84f562014-07-31 11:06:30 -0700545 sys.exit(1)
Doug Zongkerfc44a512014-08-26 13:10:25 -0700546 finally:
547 common.Cleanup()