blob: b9aef7c188a263290cfe037ca09b66c26b3f4aad [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 Xuf1a13182017-01-19 17:39:30 -080065import rangelib
Tianjie Xucfa86222016-03-07 16:31:19 -080066import sparse_img
Doug Zongker3c84f562014-07-31 11:06:30 -070067
68OPTIONS = common.OPTIONS
69
Michael Runge2e0d8fc2014-11-13 21:41:08 -080070OPTIONS.add_missing = False
71OPTIONS.rebuild_recovery = False
Baligh Uddin59f4ff12015-09-16 21:20:30 -070072OPTIONS.replace_verity_public_key = False
73OPTIONS.replace_verity_private_key = False
Tianjie Xub48589a2016-08-03 19:21:52 -070074OPTIONS.is_signing = False
Doug Zongker3c84f562014-07-31 11:06:30 -070075
Tianjie Xucfa86222016-03-07 16:31:19 -080076def GetCareMap(which, imgname):
77 """Generate care_map of system (or vendor) partition"""
78
79 assert which in ("system", "vendor")
80 _, blk_device = common.GetTypeAndDevice("/" + which, OPTIONS.info_dict)
81
82 simg = sparse_img.SparseImage(imgname)
83 care_map_list = []
84 care_map_list.append(blk_device)
85 care_map_list.append(simg.care_map.to_string_raw())
Tianjie Xuf1a13182017-01-19 17:39:30 -080086
87 care_map_ranges = simg.care_map
88 key = which + "_adjusted_partition_size"
89 adjusted_blocks = OPTIONS.info_dict.get(key)
90 if adjusted_blocks:
91 assert adjusted_blocks > 0, "blocks should be positive for " + which
92 care_map_ranges = care_map_ranges.intersect(rangelib.RangeSet(
93 "0-%d" % (adjusted_blocks,)))
94
95 care_map_list.append(care_map_ranges.to_string_raw())
Tianjie Xucfa86222016-03-07 16:31:19 -080096 return care_map_list
97
98
Michael Runge2e0d8fc2014-11-13 21:41:08 -080099def AddSystem(output_zip, prefix="IMAGES/", recovery_img=None, boot_img=None):
Doug Zongker3c84f562014-07-31 11:06:30 -0700100 """Turn the contents of SYSTEM into a system image and store it in
David Zeuthend995f4b2016-01-29 16:59:17 -0500101 output_zip. Returns the name of the system image file."""
Michael Runge2e0d8fc2014-11-13 21:41:08 -0800102
103 prebuilt_path = os.path.join(OPTIONS.input_tmp, prefix, "system.img")
104 if os.path.exists(prebuilt_path):
Tao Bao89fbb0f2017-01-10 10:47:58 -0800105 print("system.img already exists in %s, no need to rebuild..." % (prefix,))
David Zeuthend995f4b2016-01-29 16:59:17 -0500106 return prebuilt_path
Michael Runge2e0d8fc2014-11-13 21:41:08 -0800107
108 def output_sink(fn, data):
Dan Albert8b72aef2015-03-23 19:13:21 -0700109 ofile = open(os.path.join(OPTIONS.input_tmp, "SYSTEM", fn), "w")
110 ofile.write(data)
111 ofile.close()
Michael Runge2e0d8fc2014-11-13 21:41:08 -0800112
113 if OPTIONS.rebuild_recovery:
Tao Bao89fbb0f2017-01-10 10:47:58 -0800114 print("Building new recovery patch")
Dan Albert8b72aef2015-03-23 19:13:21 -0700115 common.MakeRecoveryPatch(OPTIONS.input_tmp, output_sink, recovery_img,
116 boot_img, info_dict=OPTIONS.info_dict)
Michael Runge2e0d8fc2014-11-13 21:41:08 -0800117
Doug Zongkerfc44a512014-08-26 13:10:25 -0700118 block_list = common.MakeTempFile(prefix="system-blocklist-", suffix=".map")
119 imgname = BuildSystem(OPTIONS.input_tmp, OPTIONS.info_dict,
120 block_list=block_list)
David Zeuthend995f4b2016-01-29 16:59:17 -0500121
Dan Albert8e0178d2015-01-27 15:53:15 -0800122 common.ZipWrite(output_zip, imgname, prefix + "system.img")
123 common.ZipWrite(output_zip, block_list, prefix + "system.map")
David Zeuthend995f4b2016-01-29 16:59:17 -0500124 return imgname
Doug Zongkerfc44a512014-08-26 13:10:25 -0700125
126
127def BuildSystem(input_dir, info_dict, block_list=None):
128 """Build the (sparse) system image and return the name of a temp
129 file containing it."""
130 return CreateImage(input_dir, info_dict, "system", block_list=block_list)
131
132
Alex Light4e358ab2016-06-16 14:47:10 -0700133def AddSystemOther(output_zip, prefix="IMAGES/"):
134 """Turn the contents of SYSTEM_OTHER into a system_other image
135 and store it in output_zip."""
136
137 prebuilt_path = os.path.join(OPTIONS.input_tmp, prefix, "system_other.img")
138 if os.path.exists(prebuilt_path):
Tao Bao89fbb0f2017-01-10 10:47:58 -0800139 print("system_other.img already exists in %s, no need to rebuild..." % (
140 prefix,))
Alex Light4e358ab2016-06-16 14:47:10 -0700141 return
142
143 imgname = BuildSystemOther(OPTIONS.input_tmp, OPTIONS.info_dict)
144 common.ZipWrite(output_zip, imgname, prefix + "system_other.img")
145
146def BuildSystemOther(input_dir, info_dict):
147 """Build the (sparse) system_other image and return the name of a temp
148 file containing it."""
149 return CreateImage(input_dir, info_dict, "system_other", block_list=None)
150
151
Doug Zongkerfc44a512014-08-26 13:10:25 -0700152def AddVendor(output_zip, prefix="IMAGES/"):
153 """Turn the contents of VENDOR into a vendor image and store in it
154 output_zip."""
Michael Runge2e0d8fc2014-11-13 21:41:08 -0800155
156 prebuilt_path = os.path.join(OPTIONS.input_tmp, prefix, "vendor.img")
157 if os.path.exists(prebuilt_path):
Tao Bao89fbb0f2017-01-10 10:47:58 -0800158 print("vendor.img already exists in %s, no need to rebuild..." % (prefix,))
Tianjie Xucfa86222016-03-07 16:31:19 -0800159 return prebuilt_path
Michael Runge2e0d8fc2014-11-13 21:41:08 -0800160
Doug Zongkerfc44a512014-08-26 13:10:25 -0700161 block_list = common.MakeTempFile(prefix="vendor-blocklist-", suffix=".map")
162 imgname = BuildVendor(OPTIONS.input_tmp, OPTIONS.info_dict,
Dan Albert8b72aef2015-03-23 19:13:21 -0700163 block_list=block_list)
Dan Albert8e0178d2015-01-27 15:53:15 -0800164 common.ZipWrite(output_zip, imgname, prefix + "vendor.img")
165 common.ZipWrite(output_zip, block_list, prefix + "vendor.map")
Tianjie Xucfa86222016-03-07 16:31:19 -0800166 return imgname
Doug Zongker3c84f562014-07-31 11:06:30 -0700167
168
Doug Zongkerfc44a512014-08-26 13:10:25 -0700169def BuildVendor(input_dir, info_dict, block_list=None):
170 """Build the (sparse) vendor image and return the name of a temp
171 file containing it."""
172 return CreateImage(input_dir, info_dict, "vendor", block_list=block_list)
173
174
175def CreateImage(input_dir, info_dict, what, block_list=None):
Tao Bao89fbb0f2017-01-10 10:47:58 -0800176 print("creating " + what + ".img...")
Doug Zongker3c84f562014-07-31 11:06:30 -0700177
Doug Zongkerfc44a512014-08-26 13:10:25 -0700178 img = common.MakeTempFile(prefix=what + "-", suffix=".img")
Doug Zongker3c84f562014-07-31 11:06:30 -0700179
180 # The name of the directory it is making an image out of matters to
181 # mkyaffs2image. It wants "system" but we have a directory named
182 # "SYSTEM", so create a symlink.
183 try:
184 os.symlink(os.path.join(input_dir, what.upper()),
185 os.path.join(input_dir, what))
Dan Albert8b72aef2015-03-23 19:13:21 -0700186 except OSError as e:
187 # bogus error on my mac version?
188 # File "./build/tools/releasetools/img_from_target_files"
189 # os.path.join(OPTIONS.input_tmp, "system"))
190 # OSError: [Errno 17] File exists
191 if e.errno == errno.EEXIST:
Doug Zongker3c84f562014-07-31 11:06:30 -0700192 pass
193
194 image_props = build_image.ImagePropFromGlobalDict(info_dict, what)
195 fstab = info_dict["fstab"]
Tianjie Xucfa86222016-03-07 16:31:19 -0800196 mount_point = "/" + what
197 if fstab and mount_point in fstab:
198 image_props["fs_type"] = fstab[mount_point].fs_type
Doug Zongker3c84f562014-07-31 11:06:30 -0700199
Tao Bao822f5842015-09-30 16:01:14 -0700200 # Use a fixed timestamp (01/01/2009) when packaging the image.
201 # Bug: 24377993
202 epoch = datetime.datetime.fromtimestamp(0)
203 timestamp = (datetime.datetime(2009, 1, 1) - epoch).total_seconds()
204 image_props["timestamp"] = int(timestamp)
205
Doug Zongker3c84f562014-07-31 11:06:30 -0700206 if what == "system":
207 fs_config_prefix = ""
208 else:
209 fs_config_prefix = what + "_"
210
211 fs_config = os.path.join(
212 input_dir, "META/" + fs_config_prefix + "filesystem_config.txt")
Dan Albert8b72aef2015-03-23 19:13:21 -0700213 if not os.path.exists(fs_config):
214 fs_config = None
Doug Zongker3c84f562014-07-31 11:06:30 -0700215
Ying Wanga2292c92015-03-24 19:07:40 -0700216 # Override values loaded from info_dict.
217 if fs_config:
218 image_props["fs_config"] = fs_config
Ying Wanga2292c92015-03-24 19:07:40 -0700219 if block_list:
220 image_props["block_list"] = block_list
Ying Wanga2292c92015-03-24 19:07:40 -0700221
Doug Zongker3c84f562014-07-31 11:06:30 -0700222 succ = build_image.BuildImage(os.path.join(input_dir, what),
Ying Wanga2292c92015-03-24 19:07:40 -0700223 image_props, img)
Doug Zongker3c84f562014-07-31 11:06:30 -0700224 assert succ, "build " + what + ".img image failed"
225
Tianjie Xuf1a13182017-01-19 17:39:30 -0800226 is_verity_partition = "verity_block_device" in image_props
227 verity_supported = image_props.get("verity") == "true"
228 if is_verity_partition and verity_supported:
229 adjusted_blocks_value = image_props.get("partition_size")
230 if adjusted_blocks_value:
231 adjusted_blocks_key = what + "_adjusted_partition_size"
232 info_dict[adjusted_blocks_key] = int(adjusted_blocks_value)/4096 - 1
233
Doug Zongkerfc44a512014-08-26 13:10:25 -0700234 return img
Doug Zongker3c84f562014-07-31 11:06:30 -0700235
236
237def AddUserdata(output_zip, prefix="IMAGES/"):
Ying Wang2a048392015-06-25 13:56:53 -0700238 """Create a userdata image and store it in output_zip.
239
240 In most case we just create and store an empty userdata.img;
241 But the invoker can also request to create userdata.img with real
242 data from the target files, by setting "userdata_img_with_data=true"
243 in OPTIONS.info_dict.
244 """
Doug Zongker3c84f562014-07-31 11:06:30 -0700245
Michael Runge2e0d8fc2014-11-13 21:41:08 -0800246 prebuilt_path = os.path.join(OPTIONS.input_tmp, prefix, "userdata.img")
247 if os.path.exists(prebuilt_path):
Tao Bao89fbb0f2017-01-10 10:47:58 -0800248 print("userdata.img already exists in %s, no need to rebuild..." % (
249 prefix,))
Michael Runge2e0d8fc2014-11-13 21:41:08 -0800250 return
251
Elliott Hughes305b0882016-06-15 17:04:54 -0700252 # Skip userdata.img if no size.
Tao Bao2c15d9e2015-07-09 11:51:16 -0700253 image_props = build_image.ImagePropFromGlobalDict(OPTIONS.info_dict, "data")
Elliott Hughes305b0882016-06-15 17:04:54 -0700254 if not image_props.get("partition_size"):
Doug Zongker3c84f562014-07-31 11:06:30 -0700255 return
256
Tao Bao89fbb0f2017-01-10 10:47:58 -0800257 print("creating userdata.img...")
Doug Zongker3c84f562014-07-31 11:06:30 -0700258
Tao Bao822f5842015-09-30 16:01:14 -0700259 # Use a fixed timestamp (01/01/2009) when packaging the image.
260 # Bug: 24377993
261 epoch = datetime.datetime.fromtimestamp(0)
262 timestamp = (datetime.datetime(2009, 1, 1) - epoch).total_seconds()
263 image_props["timestamp"] = int(timestamp)
264
Doug Zongker3c84f562014-07-31 11:06:30 -0700265 # The name of the directory it is making an image out of matters to
266 # mkyaffs2image. So we create a temp dir, and within it we create an
Ying Wang2a048392015-06-25 13:56:53 -0700267 # empty dir named "data", or a symlink to the DATA dir,
268 # and build the image from that.
Doug Zongker3c84f562014-07-31 11:06:30 -0700269 temp_dir = tempfile.mkdtemp()
270 user_dir = os.path.join(temp_dir, "data")
Ying Wang2a048392015-06-25 13:56:53 -0700271 empty = (OPTIONS.info_dict.get("userdata_img_with_data") != "true")
272 if empty:
273 # Create an empty dir.
274 os.mkdir(user_dir)
275 else:
276 # Symlink to the DATA dir.
277 os.symlink(os.path.join(OPTIONS.input_tmp, "DATA"),
278 user_dir)
279
Doug Zongker3c84f562014-07-31 11:06:30 -0700280 img = tempfile.NamedTemporaryFile()
281
282 fstab = OPTIONS.info_dict["fstab"]
283 if fstab:
Dan Albert8b72aef2015-03-23 19:13:21 -0700284 image_props["fs_type"] = fstab["/data"].fs_type
Doug Zongker3c84f562014-07-31 11:06:30 -0700285 succ = build_image.BuildImage(user_dir, image_props, img.name)
286 assert succ, "build userdata.img image failed"
287
288 common.CheckSize(img.name, "userdata.img", OPTIONS.info_dict)
Tao Bao2ed665a2015-04-01 11:21:55 -0700289 common.ZipWrite(output_zip, img.name, prefix + "userdata.img")
Doug Zongker3c84f562014-07-31 11:06:30 -0700290 img.close()
Ying Wang2a048392015-06-25 13:56:53 -0700291 shutil.rmtree(temp_dir)
Doug Zongker3c84f562014-07-31 11:06:30 -0700292
293
David Zeuthen2ce63ed2016-09-15 13:43:54 -0400294def AddVBMeta(output_zip, boot_img_path, system_img_path, prefix="IMAGES/"):
295 """Create a VBMeta image and store it in output_zip."""
296 _, img_file_name = tempfile.mkstemp()
297 avbtool = os.getenv('AVBTOOL') or "avbtool"
298 cmd = [avbtool, "make_vbmeta_image",
299 "--output", img_file_name,
300 "--include_descriptors_from_image", boot_img_path,
301 "--include_descriptors_from_image", system_img_path,
302 "--generate_dm_verity_cmdline_from_hashtree", system_img_path]
303 common.AppendAVBSigningArgs(cmd)
304 args = OPTIONS.info_dict.get("board_avb_make_vbmeta_image_args", None)
305 if args and args.strip():
306 cmd.extend(shlex.split(args))
307 p = common.Run(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
308 p.communicate()
309 assert p.returncode == 0, "avbtool make_vbmeta_image failed"
310 common.ZipWrite(output_zip, img_file_name, prefix + "vbmeta.img")
311
312
David Zeuthen25328622016-04-08 15:08:03 -0400313def AddPartitionTable(output_zip, prefix="IMAGES/"):
314 """Create a partition table image and store it in output_zip."""
315
316 _, img_file_name = tempfile.mkstemp()
317 _, bpt_file_name = tempfile.mkstemp()
318
319 # use BPTTOOL from environ, or "bpttool" if empty or not set.
320 bpttool = os.getenv("BPTTOOL") or "bpttool"
321 cmd = [bpttool, "make_table", "--output_json", bpt_file_name,
322 "--output_gpt", img_file_name]
323 input_files_str = OPTIONS.info_dict["board_bpt_input_files"]
324 input_files = input_files_str.split(" ")
325 for i in input_files:
326 cmd.extend(["--input", i])
327 disk_size = OPTIONS.info_dict.get("board_bpt_disk_size")
328 if disk_size:
329 cmd.extend(["--disk_size", disk_size])
330 args = OPTIONS.info_dict.get("board_bpt_make_table_args")
331 if args:
332 cmd.extend(shlex.split(args))
333
334 p = common.Run(cmd, stdout=subprocess.PIPE)
335 p.communicate()
336 assert p.returncode == 0, "bpttool make_table failed"
337
338 common.ZipWrite(output_zip, img_file_name, prefix + "partition-table.img")
339 common.ZipWrite(output_zip, bpt_file_name, prefix + "partition-table.bpt")
340
341
Doug Zongker3c84f562014-07-31 11:06:30 -0700342def AddCache(output_zip, prefix="IMAGES/"):
343 """Create an empty cache image and store it in output_zip."""
344
Michael Runge2e0d8fc2014-11-13 21:41:08 -0800345 prebuilt_path = os.path.join(OPTIONS.input_tmp, prefix, "cache.img")
346 if os.path.exists(prebuilt_path):
Tao Bao89fbb0f2017-01-10 10:47:58 -0800347 print("cache.img already exists in %s, no need to rebuild..." % (prefix,))
Michael Runge2e0d8fc2014-11-13 21:41:08 -0800348 return
349
Tao Bao2c15d9e2015-07-09 11:51:16 -0700350 image_props = build_image.ImagePropFromGlobalDict(OPTIONS.info_dict, "cache")
Doug Zongker3c84f562014-07-31 11:06:30 -0700351 # The build system has to explicitly request for cache.img.
352 if "fs_type" not in image_props:
353 return
354
Tao Bao89fbb0f2017-01-10 10:47:58 -0800355 print("creating cache.img...")
Doug Zongker3c84f562014-07-31 11:06:30 -0700356
Tao Bao822f5842015-09-30 16:01:14 -0700357 # Use a fixed timestamp (01/01/2009) when packaging the image.
358 # Bug: 24377993
359 epoch = datetime.datetime.fromtimestamp(0)
360 timestamp = (datetime.datetime(2009, 1, 1) - epoch).total_seconds()
361 image_props["timestamp"] = int(timestamp)
362
Doug Zongker3c84f562014-07-31 11:06:30 -0700363 # The name of the directory it is making an image out of matters to
364 # mkyaffs2image. So we create a temp dir, and within it we create an
365 # empty dir named "cache", and build the image from that.
366 temp_dir = tempfile.mkdtemp()
367 user_dir = os.path.join(temp_dir, "cache")
368 os.mkdir(user_dir)
369 img = tempfile.NamedTemporaryFile()
370
371 fstab = OPTIONS.info_dict["fstab"]
372 if fstab:
Dan Albert8b72aef2015-03-23 19:13:21 -0700373 image_props["fs_type"] = fstab["/cache"].fs_type
Doug Zongker3c84f562014-07-31 11:06:30 -0700374 succ = build_image.BuildImage(user_dir, image_props, img.name)
375 assert succ, "build cache.img image failed"
376
377 common.CheckSize(img.name, "cache.img", OPTIONS.info_dict)
Tao Bao2ed665a2015-04-01 11:21:55 -0700378 common.ZipWrite(output_zip, img.name, prefix + "cache.img")
Doug Zongker3c84f562014-07-31 11:06:30 -0700379 img.close()
380 os.rmdir(user_dir)
381 os.rmdir(temp_dir)
382
383
384def AddImagesToTargetFiles(filename):
385 OPTIONS.input_tmp, input_zip = common.UnzipTemp(filename)
Doug Zongkerfc44a512014-08-26 13:10:25 -0700386
Michael Runge2e0d8fc2014-11-13 21:41:08 -0800387 if not OPTIONS.add_missing:
388 for n in input_zip.namelist():
389 if n.startswith("IMAGES/"):
Tao Bao89fbb0f2017-01-10 10:47:58 -0800390 print("target_files appears to already contain images.")
Michael Runge2e0d8fc2014-11-13 21:41:08 -0800391 sys.exit(1)
Doug Zongkerfc44a512014-08-26 13:10:25 -0700392
Doug Zongker3c84f562014-07-31 11:06:30 -0700393 try:
Doug Zongkerfc44a512014-08-26 13:10:25 -0700394 input_zip.getinfo("VENDOR/")
395 has_vendor = True
396 except KeyError:
397 has_vendor = False
Doug Zongker3c84f562014-07-31 11:06:30 -0700398
Alex Light4e358ab2016-06-16 14:47:10 -0700399 has_system_other = "SYSTEM_OTHER/" in input_zip.namelist()
400
Tao Bao2c15d9e2015-07-09 11:51:16 -0700401 OPTIONS.info_dict = common.LoadInfoDict(input_zip, OPTIONS.input_tmp)
Doug Zongker3c84f562014-07-31 11:06:30 -0700402
Tao Bao2ed665a2015-04-01 11:21:55 -0700403 common.ZipClose(input_zip)
Doug Zongkerfc44a512014-08-26 13:10:25 -0700404 output_zip = zipfile.ZipFile(filename, "a",
Tao Bao9c84e502016-08-22 10:31:05 -0700405 compression=zipfile.ZIP_DEFLATED,
406 allowZip64=True)
Doug Zongker3c84f562014-07-31 11:06:30 -0700407
Tao Baodb45efa2015-10-27 19:25:18 -0700408 has_recovery = (OPTIONS.info_dict.get("no_recovery") != "true")
David Zeuthend995f4b2016-01-29 16:59:17 -0500409 system_root_image = (OPTIONS.info_dict.get("system_root_image", None) == "true")
Tao Baodb45efa2015-10-27 19:25:18 -0700410
Doug Zongkerfc44a512014-08-26 13:10:25 -0700411 def banner(s):
Tao Bao89fbb0f2017-01-10 10:47:58 -0800412 print("\n\n++++ " + s + " ++++\n\n")
Doug Zongker3c84f562014-07-31 11:06:30 -0700413
Michael Runge2e0d8fc2014-11-13 21:41:08 -0800414 prebuilt_path = os.path.join(OPTIONS.input_tmp, "IMAGES", "boot.img")
415 boot_image = None
416 if os.path.exists(prebuilt_path):
David Zeuthend995f4b2016-01-29 16:59:17 -0500417 banner("boot")
Tao Bao89fbb0f2017-01-10 10:47:58 -0800418 print("boot.img already exists in IMAGES/, no need to rebuild...")
Michael Runge2e0d8fc2014-11-13 21:41:08 -0800419 if OPTIONS.rebuild_recovery:
420 boot_image = common.GetBootableImage(
421 "IMAGES/boot.img", "boot.img", OPTIONS.input_tmp, "BOOT")
422 else:
David Zeuthen2ce63ed2016-09-15 13:43:54 -0400423 banner("boot")
424 boot_image = common.GetBootableImage(
Michael Runge2e0d8fc2014-11-13 21:41:08 -0800425 "IMAGES/boot.img", "boot.img", OPTIONS.input_tmp, "BOOT")
David Zeuthen2ce63ed2016-09-15 13:43:54 -0400426 if boot_image:
427 boot_image.AddToZip(output_zip)
Doug Zongker3c84f562014-07-31 11:06:30 -0700428
Michael Runge2e0d8fc2014-11-13 21:41:08 -0800429 recovery_image = None
Tao Baodb45efa2015-10-27 19:25:18 -0700430 if has_recovery:
431 banner("recovery")
432 prebuilt_path = os.path.join(OPTIONS.input_tmp, "IMAGES", "recovery.img")
433 if os.path.exists(prebuilt_path):
Tao Bao89fbb0f2017-01-10 10:47:58 -0800434 print("recovery.img already exists in IMAGES/, no need to rebuild...")
Tao Baodb45efa2015-10-27 19:25:18 -0700435 if OPTIONS.rebuild_recovery:
436 recovery_image = common.GetBootableImage(
437 "IMAGES/recovery.img", "recovery.img", OPTIONS.input_tmp,
438 "RECOVERY")
439 else:
Michael Runge2e0d8fc2014-11-13 21:41:08 -0800440 recovery_image = common.GetBootableImage(
441 "IMAGES/recovery.img", "recovery.img", OPTIONS.input_tmp, "RECOVERY")
Tao Baodb45efa2015-10-27 19:25:18 -0700442 if recovery_image:
443 recovery_image.AddToZip(output_zip)
Doug Zongker3c84f562014-07-31 11:06:30 -0700444
Tao Baod42e97e2016-11-30 12:11:57 -0800445 banner("recovery (two-step image)")
446 # The special recovery.img for two-step package use.
447 recovery_two_step_image = common.GetBootableImage(
448 "IMAGES/recovery-two-step.img", "recovery-two-step.img",
449 OPTIONS.input_tmp, "RECOVERY", two_step_image=True)
450 if recovery_two_step_image:
451 recovery_two_step_image.AddToZip(output_zip)
452
Doug Zongkerfc44a512014-08-26 13:10:25 -0700453 banner("system")
David Zeuthend995f4b2016-01-29 16:59:17 -0500454 system_img_path = AddSystem(
455 output_zip, recovery_img=recovery_image, boot_img=boot_image)
Tianjie Xu737afb92016-07-11 11:42:53 -0700456 vendor_img_path = None
Doug Zongkerfc44a512014-08-26 13:10:25 -0700457 if has_vendor:
458 banner("vendor")
Tianjie Xu737afb92016-07-11 11:42:53 -0700459 vendor_img_path = AddVendor(output_zip)
Alex Light4e358ab2016-06-16 14:47:10 -0700460 if has_system_other:
461 banner("system_other")
462 AddSystemOther(output_zip)
Tianjie Xub48589a2016-08-03 19:21:52 -0700463 if not OPTIONS.is_signing:
464 banner("userdata")
465 AddUserdata(output_zip)
466 banner("cache")
467 AddCache(output_zip)
David Zeuthen25328622016-04-08 15:08:03 -0400468 if OPTIONS.info_dict.get("board_bpt_enable", None) == "true":
469 banner("partition-table")
470 AddPartitionTable(output_zip)
David Zeuthen2ce63ed2016-09-15 13:43:54 -0400471 if OPTIONS.info_dict.get("board_avb_enable", None) == "true":
472 banner("vbmeta")
473 boot_contents = boot_image.WriteToTemp()
474 AddVBMeta(output_zip, boot_contents.name, system_img_path)
Doug Zongker3c84f562014-07-31 11:06:30 -0700475
Wei Wang2e735ca2016-05-10 22:48:13 -0700476 # For devices using A/B update, copy over images from RADIO/ and/or
477 # VENDOR_IMAGES/ to IMAGES/ and make sure we have all the needed
478 # images ready under IMAGES/. All images should have '.img' as extension.
Tianjie Xuaaca4212016-06-28 14:34:03 -0700479 banner("radio")
Tao Baoa0421cd2015-11-16 16:32:27 -0800480 ab_partitions = os.path.join(OPTIONS.input_tmp, "META", "ab_partitions.txt")
481 if os.path.exists(ab_partitions):
482 with open(ab_partitions, 'r') as f:
483 lines = f.readlines()
Tianjie Xucfa86222016-03-07 16:31:19 -0800484 # For devices using A/B update, generate care_map for system and vendor
485 # partitions (if present), then write this file to target_files package.
486 care_map_list = []
Tao Baoa0421cd2015-11-16 16:32:27 -0800487 for line in lines:
Tianjie Xucfa86222016-03-07 16:31:19 -0800488 if line.strip() == "system" and OPTIONS.info_dict.get(
489 "system_verity_block_device", None) is not None:
Tianjie Xu737afb92016-07-11 11:42:53 -0700490 assert os.path.exists(system_img_path)
491 care_map_list += GetCareMap("system", system_img_path)
Tianjie Xucfa86222016-03-07 16:31:19 -0800492 if line.strip() == "vendor" and OPTIONS.info_dict.get(
493 "vendor_verity_block_device", None) is not None:
Tianjie Xu737afb92016-07-11 11:42:53 -0700494 assert os.path.exists(vendor_img_path)
495 care_map_list += GetCareMap("vendor", vendor_img_path)
Tianjie Xucfa86222016-03-07 16:31:19 -0800496
Tao Baoa0421cd2015-11-16 16:32:27 -0800497 img_name = line.strip() + ".img"
Tianjie Xuaaca4212016-06-28 14:34:03 -0700498 prebuilt_path = os.path.join(OPTIONS.input_tmp, "IMAGES", img_name)
499 if os.path.exists(prebuilt_path):
Tao Bao89fbb0f2017-01-10 10:47:58 -0800500 print("%s already exists, no need to overwrite..." % (img_name,))
Tianjie Xuaaca4212016-06-28 14:34:03 -0700501 continue
502
Tao Baoa0421cd2015-11-16 16:32:27 -0800503 img_radio_path = os.path.join(OPTIONS.input_tmp, "RADIO", img_name)
Wei Wang2e735ca2016-05-10 22:48:13 -0700504 img_vendor_dir = os.path.join(
505 OPTIONS.input_tmp, "VENDOR_IMAGES")
Tao Baoa0421cd2015-11-16 16:32:27 -0800506 if os.path.exists(img_radio_path):
507 common.ZipWrite(output_zip, img_radio_path,
508 os.path.join("IMAGES", img_name))
Wei Wang2e735ca2016-05-10 22:48:13 -0700509 else:
510 for root, _, files in os.walk(img_vendor_dir):
511 if img_name in files:
512 common.ZipWrite(output_zip, os.path.join(root, img_name),
513 os.path.join("IMAGES", img_name))
514 break
Tao Baoa0421cd2015-11-16 16:32:27 -0800515
516 # Zip spec says: All slashes MUST be forward slashes.
517 img_path = 'IMAGES/' + img_name
518 assert img_path in output_zip.namelist(), "cannot find " + img_name
519
Tianjie Xucfa86222016-03-07 16:31:19 -0800520 if care_map_list:
521 file_path = "META/care_map.txt"
522 common.ZipWriteStr(output_zip, file_path, '\n'.join(care_map_list))
523
Tao Bao2ed665a2015-04-01 11:21:55 -0700524 common.ZipClose(output_zip)
Doug Zongker3c84f562014-07-31 11:06:30 -0700525
Doug Zongker3c84f562014-07-31 11:06:30 -0700526def main(argv):
Baligh Uddin59f4ff12015-09-16 21:20:30 -0700527 def option_handler(o, a):
Michael Runge2e0d8fc2014-11-13 21:41:08 -0800528 if o in ("-a", "--add_missing"):
529 OPTIONS.add_missing = True
530 elif o in ("-r", "--rebuild_recovery",):
531 OPTIONS.rebuild_recovery = True
Baligh Uddin59f4ff12015-09-16 21:20:30 -0700532 elif o == "--replace_verity_private_key":
533 OPTIONS.replace_verity_private_key = (True, a)
534 elif o == "--replace_verity_public_key":
535 OPTIONS.replace_verity_public_key = (True, a)
Tianjie Xub48589a2016-08-03 19:21:52 -0700536 elif o == "--is_signing":
537 OPTIONS.is_signing = True
Michael Runge2e0d8fc2014-11-13 21:41:08 -0800538 else:
539 return False
540 return True
541
Dan Albert8b72aef2015-03-23 19:13:21 -0700542 args = common.ParseOptions(
543 argv, __doc__, extra_opts="ar",
Baligh Uddin59f4ff12015-09-16 21:20:30 -0700544 extra_long_opts=["add_missing", "rebuild_recovery",
545 "replace_verity_public_key=",
546 "replace_verity_private_key=",
Tao Bao45810422016-10-17 16:20:12 -0700547 "is_signing"],
Dan Albert8b72aef2015-03-23 19:13:21 -0700548 extra_option_handler=option_handler)
Michael Runge2e0d8fc2014-11-13 21:41:08 -0800549
Doug Zongker3c84f562014-07-31 11:06:30 -0700550
551 if len(args) != 1:
552 common.Usage(__doc__)
553 sys.exit(1)
554
555 AddImagesToTargetFiles(args[0])
Tao Bao89fbb0f2017-01-10 10:47:58 -0800556 print("done.")
Doug Zongker3c84f562014-07-31 11:06:30 -0700557
558if __name__ == '__main__':
559 try:
560 common.CloseInheritedPipes()
561 main(sys.argv[1:])
Dan Albert8b72aef2015-03-23 19:13:21 -0700562 except common.ExternalError as e:
Tao Bao89fbb0f2017-01-10 10:47:58 -0800563 print("\n ERROR: %s\n" % (e,))
Doug Zongker3c84f562014-07-31 11:06:30 -0700564 sys.exit(1)
Doug Zongkerfc44a512014-08-26 13:10:25 -0700565 finally:
566 common.Cleanup()