blob: 28fd474c923740d6707d7fc5ee18bdba164737e2 [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)
Tianjie Xuf1a13182017-01-19 17:39:30 -080085
86 care_map_ranges = simg.care_map
87 key = which + "_adjusted_partition_size"
88 adjusted_blocks = OPTIONS.info_dict.get(key)
89 if adjusted_blocks:
90 assert adjusted_blocks > 0, "blocks should be positive for " + which
91 care_map_ranges = care_map_ranges.intersect(rangelib.RangeSet(
92 "0-%d" % (adjusted_blocks,)))
93
94 care_map_list.append(care_map_ranges.to_string_raw())
Tianjie Xucfa86222016-03-07 16:31:19 -080095 return care_map_list
96
97
Michael Runge2e0d8fc2014-11-13 21:41:08 -080098def AddSystem(output_zip, prefix="IMAGES/", recovery_img=None, boot_img=None):
Doug Zongker3c84f562014-07-31 11:06:30 -070099 """Turn the contents of SYSTEM into a system image and store it in
David Zeuthend995f4b2016-01-29 16:59:17 -0500100 output_zip. Returns the name of the system image file."""
Michael Runge2e0d8fc2014-11-13 21:41:08 -0800101
102 prebuilt_path = os.path.join(OPTIONS.input_tmp, prefix, "system.img")
103 if os.path.exists(prebuilt_path):
Tao Bao89fbb0f2017-01-10 10:47:58 -0800104 print("system.img already exists in %s, no need to rebuild..." % (prefix,))
David Zeuthend995f4b2016-01-29 16:59:17 -0500105 return prebuilt_path
Michael Runge2e0d8fc2014-11-13 21:41:08 -0800106
107 def output_sink(fn, data):
Dan Albert8b72aef2015-03-23 19:13:21 -0700108 ofile = open(os.path.join(OPTIONS.input_tmp, "SYSTEM", fn), "w")
109 ofile.write(data)
110 ofile.close()
Michael Runge2e0d8fc2014-11-13 21:41:08 -0800111
112 if OPTIONS.rebuild_recovery:
Tao Bao89fbb0f2017-01-10 10:47:58 -0800113 print("Building new recovery patch")
Dan Albert8b72aef2015-03-23 19:13:21 -0700114 common.MakeRecoveryPatch(OPTIONS.input_tmp, output_sink, recovery_img,
115 boot_img, info_dict=OPTIONS.info_dict)
Michael Runge2e0d8fc2014-11-13 21:41:08 -0800116
Doug Zongkerfc44a512014-08-26 13:10:25 -0700117 block_list = common.MakeTempFile(prefix="system-blocklist-", suffix=".map")
118 imgname = BuildSystem(OPTIONS.input_tmp, OPTIONS.info_dict,
119 block_list=block_list)
David Zeuthend995f4b2016-01-29 16:59:17 -0500120
Dan Albert8e0178d2015-01-27 15:53:15 -0800121 common.ZipWrite(output_zip, imgname, prefix + "system.img")
122 common.ZipWrite(output_zip, block_list, prefix + "system.map")
David Zeuthend995f4b2016-01-29 16:59:17 -0500123 return imgname
Doug Zongkerfc44a512014-08-26 13:10:25 -0700124
125
126def BuildSystem(input_dir, info_dict, block_list=None):
127 """Build the (sparse) system image and return the name of a temp
128 file containing it."""
129 return CreateImage(input_dir, info_dict, "system", block_list=block_list)
130
131
Alex Light4e358ab2016-06-16 14:47:10 -0700132def AddSystemOther(output_zip, prefix="IMAGES/"):
133 """Turn the contents of SYSTEM_OTHER into a system_other image
134 and store it in output_zip."""
135
136 prebuilt_path = os.path.join(OPTIONS.input_tmp, prefix, "system_other.img")
137 if os.path.exists(prebuilt_path):
Tao Bao89fbb0f2017-01-10 10:47:58 -0800138 print("system_other.img already exists in %s, no need to rebuild..." % (
139 prefix,))
Alex Light4e358ab2016-06-16 14:47:10 -0700140 return
141
142 imgname = BuildSystemOther(OPTIONS.input_tmp, OPTIONS.info_dict)
143 common.ZipWrite(output_zip, imgname, prefix + "system_other.img")
144
145def BuildSystemOther(input_dir, info_dict):
146 """Build the (sparse) system_other image and return the name of a temp
147 file containing it."""
148 return CreateImage(input_dir, info_dict, "system_other", block_list=None)
149
150
Doug Zongkerfc44a512014-08-26 13:10:25 -0700151def AddVendor(output_zip, prefix="IMAGES/"):
152 """Turn the contents of VENDOR into a vendor image and store in it
153 output_zip."""
Michael Runge2e0d8fc2014-11-13 21:41:08 -0800154
155 prebuilt_path = os.path.join(OPTIONS.input_tmp, prefix, "vendor.img")
156 if os.path.exists(prebuilt_path):
Tao Bao89fbb0f2017-01-10 10:47:58 -0800157 print("vendor.img already exists in %s, no need to rebuild..." % (prefix,))
Tianjie Xucfa86222016-03-07 16:31:19 -0800158 return prebuilt_path
Michael Runge2e0d8fc2014-11-13 21:41:08 -0800159
Doug Zongkerfc44a512014-08-26 13:10:25 -0700160 block_list = common.MakeTempFile(prefix="vendor-blocklist-", suffix=".map")
161 imgname = BuildVendor(OPTIONS.input_tmp, OPTIONS.info_dict,
Dan Albert8b72aef2015-03-23 19:13:21 -0700162 block_list=block_list)
Dan Albert8e0178d2015-01-27 15:53:15 -0800163 common.ZipWrite(output_zip, imgname, prefix + "vendor.img")
164 common.ZipWrite(output_zip, block_list, prefix + "vendor.map")
Tianjie Xucfa86222016-03-07 16:31:19 -0800165 return imgname
Doug Zongker3c84f562014-07-31 11:06:30 -0700166
167
Doug Zongkerfc44a512014-08-26 13:10:25 -0700168def BuildVendor(input_dir, info_dict, block_list=None):
169 """Build the (sparse) vendor image and return the name of a temp
170 file containing it."""
171 return CreateImage(input_dir, info_dict, "vendor", block_list=block_list)
172
173
174def CreateImage(input_dir, info_dict, what, block_list=None):
Tao Bao89fbb0f2017-01-10 10:47:58 -0800175 print("creating " + what + ".img...")
Doug Zongker3c84f562014-07-31 11:06:30 -0700176
Doug Zongkerfc44a512014-08-26 13:10:25 -0700177 img = common.MakeTempFile(prefix=what + "-", suffix=".img")
Doug Zongker3c84f562014-07-31 11:06:30 -0700178
179 # The name of the directory it is making an image out of matters to
180 # mkyaffs2image. It wants "system" but we have a directory named
181 # "SYSTEM", so create a symlink.
182 try:
183 os.symlink(os.path.join(input_dir, what.upper()),
184 os.path.join(input_dir, what))
Dan Albert8b72aef2015-03-23 19:13:21 -0700185 except OSError as e:
186 # bogus error on my mac version?
187 # File "./build/tools/releasetools/img_from_target_files"
188 # os.path.join(OPTIONS.input_tmp, "system"))
189 # OSError: [Errno 17] File exists
190 if e.errno == errno.EEXIST:
Doug Zongker3c84f562014-07-31 11:06:30 -0700191 pass
192
193 image_props = build_image.ImagePropFromGlobalDict(info_dict, what)
194 fstab = info_dict["fstab"]
Tianjie Xucfa86222016-03-07 16:31:19 -0800195 mount_point = "/" + what
196 if fstab and mount_point in fstab:
197 image_props["fs_type"] = fstab[mount_point].fs_type
Doug Zongker3c84f562014-07-31 11:06:30 -0700198
Tao Bao822f5842015-09-30 16:01:14 -0700199 # Use a fixed timestamp (01/01/2009) when packaging the image.
200 # Bug: 24377993
201 epoch = datetime.datetime.fromtimestamp(0)
202 timestamp = (datetime.datetime(2009, 1, 1) - epoch).total_seconds()
203 image_props["timestamp"] = int(timestamp)
204
Doug Zongker3c84f562014-07-31 11:06:30 -0700205 if what == "system":
206 fs_config_prefix = ""
207 else:
208 fs_config_prefix = what + "_"
209
210 fs_config = os.path.join(
211 input_dir, "META/" + fs_config_prefix + "filesystem_config.txt")
Dan Albert8b72aef2015-03-23 19:13:21 -0700212 if not os.path.exists(fs_config):
213 fs_config = None
Doug Zongker3c84f562014-07-31 11:06:30 -0700214
Ying Wanga2292c92015-03-24 19:07:40 -0700215 # Override values loaded from info_dict.
216 if fs_config:
217 image_props["fs_config"] = fs_config
Ying Wanga2292c92015-03-24 19:07:40 -0700218 if block_list:
219 image_props["block_list"] = block_list
Ying Wanga2292c92015-03-24 19:07:40 -0700220
Doug Zongker3c84f562014-07-31 11:06:30 -0700221 succ = build_image.BuildImage(os.path.join(input_dir, what),
Ying Wanga2292c92015-03-24 19:07:40 -0700222 image_props, img)
Doug Zongker3c84f562014-07-31 11:06:30 -0700223 assert succ, "build " + what + ".img image failed"
224
Tianjie Xuf1a13182017-01-19 17:39:30 -0800225 is_verity_partition = "verity_block_device" in image_props
226 verity_supported = image_props.get("verity") == "true"
227 if is_verity_partition and verity_supported:
228 adjusted_blocks_value = image_props.get("partition_size")
229 if adjusted_blocks_value:
230 adjusted_blocks_key = what + "_adjusted_partition_size"
231 info_dict[adjusted_blocks_key] = int(adjusted_blocks_value)/4096 - 1
232
Doug Zongkerfc44a512014-08-26 13:10:25 -0700233 return img
Doug Zongker3c84f562014-07-31 11:06:30 -0700234
235
236def AddUserdata(output_zip, prefix="IMAGES/"):
Ying Wang2a048392015-06-25 13:56:53 -0700237 """Create a userdata image and store it in output_zip.
238
239 In most case we just create and store an empty userdata.img;
240 But the invoker can also request to create userdata.img with real
241 data from the target files, by setting "userdata_img_with_data=true"
242 in OPTIONS.info_dict.
243 """
Doug Zongker3c84f562014-07-31 11:06:30 -0700244
Michael Runge2e0d8fc2014-11-13 21:41:08 -0800245 prebuilt_path = os.path.join(OPTIONS.input_tmp, prefix, "userdata.img")
246 if os.path.exists(prebuilt_path):
Tao Bao89fbb0f2017-01-10 10:47:58 -0800247 print("userdata.img already exists in %s, no need to rebuild..." % (
248 prefix,))
Michael Runge2e0d8fc2014-11-13 21:41:08 -0800249 return
250
Elliott Hughes305b0882016-06-15 17:04:54 -0700251 # Skip userdata.img if no size.
Tao Bao2c15d9e2015-07-09 11:51:16 -0700252 image_props = build_image.ImagePropFromGlobalDict(OPTIONS.info_dict, "data")
Elliott Hughes305b0882016-06-15 17:04:54 -0700253 if not image_props.get("partition_size"):
Doug Zongker3c84f562014-07-31 11:06:30 -0700254 return
255
Tao Bao89fbb0f2017-01-10 10:47:58 -0800256 print("creating userdata.img...")
Doug Zongker3c84f562014-07-31 11:06:30 -0700257
Tao Bao822f5842015-09-30 16:01:14 -0700258 # Use a fixed timestamp (01/01/2009) when packaging the image.
259 # Bug: 24377993
260 epoch = datetime.datetime.fromtimestamp(0)
261 timestamp = (datetime.datetime(2009, 1, 1) - epoch).total_seconds()
262 image_props["timestamp"] = int(timestamp)
263
Doug Zongker3c84f562014-07-31 11:06:30 -0700264 # The name of the directory it is making an image out of matters to
265 # mkyaffs2image. So we create a temp dir, and within it we create an
Ying Wang2a048392015-06-25 13:56:53 -0700266 # empty dir named "data", or a symlink to the DATA dir,
267 # and build the image from that.
Doug Zongker3c84f562014-07-31 11:06:30 -0700268 temp_dir = tempfile.mkdtemp()
269 user_dir = os.path.join(temp_dir, "data")
Ying Wang2a048392015-06-25 13:56:53 -0700270 empty = (OPTIONS.info_dict.get("userdata_img_with_data") != "true")
271 if empty:
272 # Create an empty dir.
273 os.mkdir(user_dir)
274 else:
275 # Symlink to the DATA dir.
276 os.symlink(os.path.join(OPTIONS.input_tmp, "DATA"),
277 user_dir)
278
Doug Zongker3c84f562014-07-31 11:06:30 -0700279 img = tempfile.NamedTemporaryFile()
280
281 fstab = OPTIONS.info_dict["fstab"]
282 if fstab:
Dan Albert8b72aef2015-03-23 19:13:21 -0700283 image_props["fs_type"] = fstab["/data"].fs_type
Doug Zongker3c84f562014-07-31 11:06:30 -0700284 succ = build_image.BuildImage(user_dir, image_props, img.name)
285 assert succ, "build userdata.img image failed"
286
287 common.CheckSize(img.name, "userdata.img", OPTIONS.info_dict)
Tao Bao2ed665a2015-04-01 11:21:55 -0700288 common.ZipWrite(output_zip, img.name, prefix + "userdata.img")
Doug Zongker3c84f562014-07-31 11:06:30 -0700289 img.close()
Ying Wang2a048392015-06-25 13:56:53 -0700290 shutil.rmtree(temp_dir)
Doug Zongker3c84f562014-07-31 11:06:30 -0700291
292
David Zeuthen2ce63ed2016-09-15 13:43:54 -0400293def AddVBMeta(output_zip, boot_img_path, system_img_path, prefix="IMAGES/"):
294 """Create a VBMeta image and store it in output_zip."""
295 _, img_file_name = tempfile.mkstemp()
296 avbtool = os.getenv('AVBTOOL') or "avbtool"
297 cmd = [avbtool, "make_vbmeta_image",
298 "--output", img_file_name,
299 "--include_descriptors_from_image", boot_img_path,
300 "--include_descriptors_from_image", system_img_path,
301 "--generate_dm_verity_cmdline_from_hashtree", system_img_path]
302 common.AppendAVBSigningArgs(cmd)
303 args = OPTIONS.info_dict.get("board_avb_make_vbmeta_image_args", None)
304 if args and args.strip():
305 cmd.extend(shlex.split(args))
306 p = common.Run(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
307 p.communicate()
308 assert p.returncode == 0, "avbtool make_vbmeta_image failed"
309 common.ZipWrite(output_zip, img_file_name, prefix + "vbmeta.img")
310
311
David Zeuthen25328622016-04-08 15:08:03 -0400312def AddPartitionTable(output_zip, prefix="IMAGES/"):
313 """Create a partition table image and store it in output_zip."""
314
315 _, img_file_name = tempfile.mkstemp()
316 _, bpt_file_name = tempfile.mkstemp()
317
318 # use BPTTOOL from environ, or "bpttool" if empty or not set.
319 bpttool = os.getenv("BPTTOOL") or "bpttool"
320 cmd = [bpttool, "make_table", "--output_json", bpt_file_name,
321 "--output_gpt", img_file_name]
322 input_files_str = OPTIONS.info_dict["board_bpt_input_files"]
323 input_files = input_files_str.split(" ")
324 for i in input_files:
325 cmd.extend(["--input", i])
326 disk_size = OPTIONS.info_dict.get("board_bpt_disk_size")
327 if disk_size:
328 cmd.extend(["--disk_size", disk_size])
329 args = OPTIONS.info_dict.get("board_bpt_make_table_args")
330 if args:
331 cmd.extend(shlex.split(args))
332
333 p = common.Run(cmd, stdout=subprocess.PIPE)
334 p.communicate()
335 assert p.returncode == 0, "bpttool make_table failed"
336
337 common.ZipWrite(output_zip, img_file_name, prefix + "partition-table.img")
338 common.ZipWrite(output_zip, bpt_file_name, prefix + "partition-table.bpt")
339
340
Doug Zongker3c84f562014-07-31 11:06:30 -0700341def AddCache(output_zip, prefix="IMAGES/"):
342 """Create an empty cache image and store it in output_zip."""
343
Michael Runge2e0d8fc2014-11-13 21:41:08 -0800344 prebuilt_path = os.path.join(OPTIONS.input_tmp, prefix, "cache.img")
345 if os.path.exists(prebuilt_path):
Tao Bao89fbb0f2017-01-10 10:47:58 -0800346 print("cache.img already exists in %s, no need to rebuild..." % (prefix,))
Michael Runge2e0d8fc2014-11-13 21:41:08 -0800347 return
348
Tao Bao2c15d9e2015-07-09 11:51:16 -0700349 image_props = build_image.ImagePropFromGlobalDict(OPTIONS.info_dict, "cache")
Doug Zongker3c84f562014-07-31 11:06:30 -0700350 # The build system has to explicitly request for cache.img.
351 if "fs_type" not in image_props:
352 return
353
Tao Bao89fbb0f2017-01-10 10:47:58 -0800354 print("creating cache.img...")
Doug Zongker3c84f562014-07-31 11:06:30 -0700355
Tao Bao822f5842015-09-30 16:01:14 -0700356 # Use a fixed timestamp (01/01/2009) when packaging the image.
357 # Bug: 24377993
358 epoch = datetime.datetime.fromtimestamp(0)
359 timestamp = (datetime.datetime(2009, 1, 1) - epoch).total_seconds()
360 image_props["timestamp"] = int(timestamp)
361
Doug Zongker3c84f562014-07-31 11:06:30 -0700362 # The name of the directory it is making an image out of matters to
363 # mkyaffs2image. So we create a temp dir, and within it we create an
364 # empty dir named "cache", and build the image from that.
365 temp_dir = tempfile.mkdtemp()
366 user_dir = os.path.join(temp_dir, "cache")
367 os.mkdir(user_dir)
368 img = tempfile.NamedTemporaryFile()
369
370 fstab = OPTIONS.info_dict["fstab"]
371 if fstab:
Dan Albert8b72aef2015-03-23 19:13:21 -0700372 image_props["fs_type"] = fstab["/cache"].fs_type
Doug Zongker3c84f562014-07-31 11:06:30 -0700373 succ = build_image.BuildImage(user_dir, image_props, img.name)
374 assert succ, "build cache.img image failed"
375
376 common.CheckSize(img.name, "cache.img", OPTIONS.info_dict)
Tao Bao2ed665a2015-04-01 11:21:55 -0700377 common.ZipWrite(output_zip, img.name, prefix + "cache.img")
Doug Zongker3c84f562014-07-31 11:06:30 -0700378 img.close()
379 os.rmdir(user_dir)
380 os.rmdir(temp_dir)
381
382
383def AddImagesToTargetFiles(filename):
384 OPTIONS.input_tmp, input_zip = common.UnzipTemp(filename)
Doug Zongkerfc44a512014-08-26 13:10:25 -0700385
Michael Runge2e0d8fc2014-11-13 21:41:08 -0800386 if not OPTIONS.add_missing:
387 for n in input_zip.namelist():
388 if n.startswith("IMAGES/"):
Tao Bao89fbb0f2017-01-10 10:47:58 -0800389 print("target_files appears to already contain images.")
Michael Runge2e0d8fc2014-11-13 21:41:08 -0800390 sys.exit(1)
Doug Zongkerfc44a512014-08-26 13:10:25 -0700391
Doug Zongker3c84f562014-07-31 11:06:30 -0700392 try:
Doug Zongkerfc44a512014-08-26 13:10:25 -0700393 input_zip.getinfo("VENDOR/")
394 has_vendor = True
395 except KeyError:
396 has_vendor = False
Doug Zongker3c84f562014-07-31 11:06:30 -0700397
Alex Light4e358ab2016-06-16 14:47:10 -0700398 has_system_other = "SYSTEM_OTHER/" in input_zip.namelist()
399
Tao Bao2c15d9e2015-07-09 11:51:16 -0700400 OPTIONS.info_dict = common.LoadInfoDict(input_zip, OPTIONS.input_tmp)
Doug Zongker3c84f562014-07-31 11:06:30 -0700401
Tao Bao2ed665a2015-04-01 11:21:55 -0700402 common.ZipClose(input_zip)
Doug Zongkerfc44a512014-08-26 13:10:25 -0700403 output_zip = zipfile.ZipFile(filename, "a",
Tao Bao9c84e502016-08-22 10:31:05 -0700404 compression=zipfile.ZIP_DEFLATED,
405 allowZip64=True)
Doug Zongker3c84f562014-07-31 11:06:30 -0700406
Tao Baodb45efa2015-10-27 19:25:18 -0700407 has_recovery = (OPTIONS.info_dict.get("no_recovery") != "true")
David Zeuthend995f4b2016-01-29 16:59:17 -0500408 system_root_image = (OPTIONS.info_dict.get("system_root_image", None) == "true")
Tao Baodb45efa2015-10-27 19:25:18 -0700409
Doug Zongkerfc44a512014-08-26 13:10:25 -0700410 def banner(s):
Tao Bao89fbb0f2017-01-10 10:47:58 -0800411 print("\n\n++++ " + s + " ++++\n\n")
Doug Zongker3c84f562014-07-31 11:06:30 -0700412
Michael Runge2e0d8fc2014-11-13 21:41:08 -0800413 prebuilt_path = os.path.join(OPTIONS.input_tmp, "IMAGES", "boot.img")
414 boot_image = None
415 if os.path.exists(prebuilt_path):
David Zeuthend995f4b2016-01-29 16:59:17 -0500416 banner("boot")
Tao Bao89fbb0f2017-01-10 10:47:58 -0800417 print("boot.img already exists in IMAGES/, no need to rebuild...")
Michael Runge2e0d8fc2014-11-13 21:41:08 -0800418 if OPTIONS.rebuild_recovery:
419 boot_image = common.GetBootableImage(
420 "IMAGES/boot.img", "boot.img", OPTIONS.input_tmp, "BOOT")
421 else:
David Zeuthen2ce63ed2016-09-15 13:43:54 -0400422 banner("boot")
423 boot_image = common.GetBootableImage(
Michael Runge2e0d8fc2014-11-13 21:41:08 -0800424 "IMAGES/boot.img", "boot.img", OPTIONS.input_tmp, "BOOT")
David Zeuthen2ce63ed2016-09-15 13:43:54 -0400425 if boot_image:
426 boot_image.AddToZip(output_zip)
Doug Zongker3c84f562014-07-31 11:06:30 -0700427
Michael Runge2e0d8fc2014-11-13 21:41:08 -0800428 recovery_image = None
Tao Baodb45efa2015-10-27 19:25:18 -0700429 if has_recovery:
430 banner("recovery")
431 prebuilt_path = os.path.join(OPTIONS.input_tmp, "IMAGES", "recovery.img")
432 if os.path.exists(prebuilt_path):
Tao Bao89fbb0f2017-01-10 10:47:58 -0800433 print("recovery.img already exists in IMAGES/, no need to rebuild...")
Tao Baodb45efa2015-10-27 19:25:18 -0700434 if OPTIONS.rebuild_recovery:
435 recovery_image = common.GetBootableImage(
436 "IMAGES/recovery.img", "recovery.img", OPTIONS.input_tmp,
437 "RECOVERY")
438 else:
Michael Runge2e0d8fc2014-11-13 21:41:08 -0800439 recovery_image = common.GetBootableImage(
440 "IMAGES/recovery.img", "recovery.img", OPTIONS.input_tmp, "RECOVERY")
Tao Baodb45efa2015-10-27 19:25:18 -0700441 if recovery_image:
442 recovery_image.AddToZip(output_zip)
Doug Zongker3c84f562014-07-31 11:06:30 -0700443
Tao Baod42e97e2016-11-30 12:11:57 -0800444 banner("recovery (two-step image)")
445 # The special recovery.img for two-step package use.
446 recovery_two_step_image = common.GetBootableImage(
447 "IMAGES/recovery-two-step.img", "recovery-two-step.img",
448 OPTIONS.input_tmp, "RECOVERY", two_step_image=True)
449 if recovery_two_step_image:
450 recovery_two_step_image.AddToZip(output_zip)
451
Doug Zongkerfc44a512014-08-26 13:10:25 -0700452 banner("system")
David Zeuthend995f4b2016-01-29 16:59:17 -0500453 system_img_path = AddSystem(
454 output_zip, recovery_img=recovery_image, boot_img=boot_image)
Tianjie Xu737afb92016-07-11 11:42:53 -0700455 vendor_img_path = None
Doug Zongkerfc44a512014-08-26 13:10:25 -0700456 if has_vendor:
457 banner("vendor")
Tianjie Xu737afb92016-07-11 11:42:53 -0700458 vendor_img_path = AddVendor(output_zip)
Alex Light4e358ab2016-06-16 14:47:10 -0700459 if has_system_other:
460 banner("system_other")
461 AddSystemOther(output_zip)
Tianjie Xub48589a2016-08-03 19:21:52 -0700462 if not OPTIONS.is_signing:
463 banner("userdata")
464 AddUserdata(output_zip)
465 banner("cache")
466 AddCache(output_zip)
David Zeuthen25328622016-04-08 15:08:03 -0400467 if OPTIONS.info_dict.get("board_bpt_enable", None) == "true":
468 banner("partition-table")
469 AddPartitionTable(output_zip)
David Zeuthen2ce63ed2016-09-15 13:43:54 -0400470 if OPTIONS.info_dict.get("board_avb_enable", None) == "true":
471 banner("vbmeta")
472 boot_contents = boot_image.WriteToTemp()
473 AddVBMeta(output_zip, boot_contents.name, system_img_path)
Doug Zongker3c84f562014-07-31 11:06:30 -0700474
Wei Wang2e735ca2016-05-10 22:48:13 -0700475 # For devices using A/B update, copy over images from RADIO/ and/or
476 # VENDOR_IMAGES/ to IMAGES/ and make sure we have all the needed
477 # images ready under IMAGES/. All images should have '.img' as extension.
Tianjie Xuaaca4212016-06-28 14:34:03 -0700478 banner("radio")
Tao Baoa0421cd2015-11-16 16:32:27 -0800479 ab_partitions = os.path.join(OPTIONS.input_tmp, "META", "ab_partitions.txt")
480 if os.path.exists(ab_partitions):
481 with open(ab_partitions, 'r') as f:
482 lines = f.readlines()
Tianjie Xucfa86222016-03-07 16:31:19 -0800483 # For devices using A/B update, generate care_map for system and vendor
484 # partitions (if present), then write this file to target_files package.
485 care_map_list = []
Tao Baoa0421cd2015-11-16 16:32:27 -0800486 for line in lines:
Tianjie Xucfa86222016-03-07 16:31:19 -0800487 if line.strip() == "system" and OPTIONS.info_dict.get(
488 "system_verity_block_device", None) is not None:
Tianjie Xu737afb92016-07-11 11:42:53 -0700489 assert os.path.exists(system_img_path)
490 care_map_list += GetCareMap("system", system_img_path)
Tianjie Xucfa86222016-03-07 16:31:19 -0800491 if line.strip() == "vendor" and OPTIONS.info_dict.get(
492 "vendor_verity_block_device", None) is not None:
Tianjie Xu737afb92016-07-11 11:42:53 -0700493 assert os.path.exists(vendor_img_path)
494 care_map_list += GetCareMap("vendor", vendor_img_path)
Tianjie Xucfa86222016-03-07 16:31:19 -0800495
Tao Baoa0421cd2015-11-16 16:32:27 -0800496 img_name = line.strip() + ".img"
Tianjie Xuaaca4212016-06-28 14:34:03 -0700497 prebuilt_path = os.path.join(OPTIONS.input_tmp, "IMAGES", img_name)
498 if os.path.exists(prebuilt_path):
Tao Bao89fbb0f2017-01-10 10:47:58 -0800499 print("%s already exists, no need to overwrite..." % (img_name,))
Tianjie Xuaaca4212016-06-28 14:34:03 -0700500 continue
501
Tao Baoa0421cd2015-11-16 16:32:27 -0800502 img_radio_path = os.path.join(OPTIONS.input_tmp, "RADIO", img_name)
Wei Wang2e735ca2016-05-10 22:48:13 -0700503 img_vendor_dir = os.path.join(
504 OPTIONS.input_tmp, "VENDOR_IMAGES")
Tao Baoa0421cd2015-11-16 16:32:27 -0800505 if os.path.exists(img_radio_path):
506 common.ZipWrite(output_zip, img_radio_path,
507 os.path.join("IMAGES", img_name))
Wei Wang2e735ca2016-05-10 22:48:13 -0700508 else:
509 for root, _, files in os.walk(img_vendor_dir):
510 if img_name in files:
511 common.ZipWrite(output_zip, os.path.join(root, img_name),
512 os.path.join("IMAGES", img_name))
513 break
Tao Baoa0421cd2015-11-16 16:32:27 -0800514
515 # Zip spec says: All slashes MUST be forward slashes.
516 img_path = 'IMAGES/' + img_name
517 assert img_path in output_zip.namelist(), "cannot find " + img_name
518
Tianjie Xucfa86222016-03-07 16:31:19 -0800519 if care_map_list:
520 file_path = "META/care_map.txt"
521 common.ZipWriteStr(output_zip, file_path, '\n'.join(care_map_list))
522
Tao Bao2ed665a2015-04-01 11:21:55 -0700523 common.ZipClose(output_zip)
Doug Zongker3c84f562014-07-31 11:06:30 -0700524
Doug Zongker3c84f562014-07-31 11:06:30 -0700525def main(argv):
Baligh Uddin59f4ff12015-09-16 21:20:30 -0700526 def option_handler(o, a):
Michael Runge2e0d8fc2014-11-13 21:41:08 -0800527 if o in ("-a", "--add_missing"):
528 OPTIONS.add_missing = True
529 elif o in ("-r", "--rebuild_recovery",):
530 OPTIONS.rebuild_recovery = True
Baligh Uddin59f4ff12015-09-16 21:20:30 -0700531 elif o == "--replace_verity_private_key":
532 OPTIONS.replace_verity_private_key = (True, a)
533 elif o == "--replace_verity_public_key":
534 OPTIONS.replace_verity_public_key = (True, a)
Tianjie Xub48589a2016-08-03 19:21:52 -0700535 elif o == "--is_signing":
536 OPTIONS.is_signing = True
Michael Runge2e0d8fc2014-11-13 21:41:08 -0800537 else:
538 return False
539 return True
540
Dan Albert8b72aef2015-03-23 19:13:21 -0700541 args = common.ParseOptions(
542 argv, __doc__, extra_opts="ar",
Baligh Uddin59f4ff12015-09-16 21:20:30 -0700543 extra_long_opts=["add_missing", "rebuild_recovery",
544 "replace_verity_public_key=",
545 "replace_verity_private_key=",
Tao Bao45810422016-10-17 16:20:12 -0700546 "is_signing"],
Dan Albert8b72aef2015-03-23 19:13:21 -0700547 extra_option_handler=option_handler)
Michael Runge2e0d8fc2014-11-13 21:41:08 -0800548
Doug Zongker3c84f562014-07-31 11:06:30 -0700549
550 if len(args) != 1:
551 common.Usage(__doc__)
552 sys.exit(1)
553
554 AddImagesToTargetFiles(args[0])
Tao Bao89fbb0f2017-01-10 10:47:58 -0800555 print("done.")
Doug Zongker3c84f562014-07-31 11:06:30 -0700556
557if __name__ == '__main__':
558 try:
559 common.CloseInheritedPipes()
560 main(sys.argv[1:])
Dan Albert8b72aef2015-03-23 19:13:21 -0700561 except common.ExternalError as e:
Tao Bao89fbb0f2017-01-10 10:47:58 -0800562 print("\n ERROR: %s\n" % (e,))
Doug Zongker3c84f562014-07-31 11:06:30 -0700563 sys.exit(1)
Doug Zongkerfc44a512014-08-26 13:10:25 -0700564 finally:
565 common.Cleanup()