blob: 86354e71efa70f1810cd812929a0371c681c5603 [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
Tianjie Xu38af07f2017-05-25 17:38:53 -070072OPTIONS.replace_recovery_patch_files_list = []
Baligh Uddin59f4ff12015-09-16 21:20:30 -070073OPTIONS.replace_verity_public_key = False
74OPTIONS.replace_verity_private_key = False
Tianjie Xub48589a2016-08-03 19:21:52 -070075OPTIONS.is_signing = False
Doug Zongker3c84f562014-07-31 11:06:30 -070076
Dan Willemsen2ee00d52017-03-05 19:51:56 -080077
78class OutputFile(object):
79 def __init__(self, output_zip, input_dir, prefix, name):
80 self._output_zip = output_zip
81 self.input_name = os.path.join(input_dir, prefix, name)
82
83 if self._output_zip:
84 self._zip_name = os.path.join(prefix, name)
85
86 root, suffix = os.path.splitext(name)
87 self.name = common.MakeTempFile(prefix=root + '-', suffix=suffix)
88 else:
89 self.name = self.input_name
90
91 def Write(self):
92 if self._output_zip:
93 common.ZipWrite(self._output_zip, self.name, self._zip_name)
94
95
Tianjie Xucfa86222016-03-07 16:31:19 -080096def GetCareMap(which, imgname):
97 """Generate care_map of system (or vendor) partition"""
98
99 assert which in ("system", "vendor")
Tianjie Xucfa86222016-03-07 16:31:19 -0800100
101 simg = sparse_img.SparseImage(imgname)
102 care_map_list = []
Tianjie Xu955629b2017-03-01 11:48:25 -0800103 care_map_list.append(which)
Tianjie Xuf1a13182017-01-19 17:39:30 -0800104
105 care_map_ranges = simg.care_map
106 key = which + "_adjusted_partition_size"
107 adjusted_blocks = OPTIONS.info_dict.get(key)
108 if adjusted_blocks:
109 assert adjusted_blocks > 0, "blocks should be positive for " + which
110 care_map_ranges = care_map_ranges.intersect(rangelib.RangeSet(
111 "0-%d" % (adjusted_blocks,)))
112
113 care_map_list.append(care_map_ranges.to_string_raw())
Tianjie Xucfa86222016-03-07 16:31:19 -0800114 return care_map_list
115
116
Michael Runge2e0d8fc2014-11-13 21:41:08 -0800117def AddSystem(output_zip, prefix="IMAGES/", recovery_img=None, boot_img=None):
Doug Zongker3c84f562014-07-31 11:06:30 -0700118 """Turn the contents of SYSTEM into a system image and store it in
David Zeuthend995f4b2016-01-29 16:59:17 -0500119 output_zip. Returns the name of the system image file."""
Michael Runge2e0d8fc2014-11-13 21:41:08 -0800120
Dan Willemsen2ee00d52017-03-05 19:51:56 -0800121 img = OutputFile(output_zip, OPTIONS.input_tmp, prefix, "system.img")
122 if os.path.exists(img.input_name):
Tao Bao89fbb0f2017-01-10 10:47:58 -0800123 print("system.img already exists in %s, no need to rebuild..." % (prefix,))
Dan Willemsen2ee00d52017-03-05 19:51:56 -0800124 return img.input_name
Michael Runge2e0d8fc2014-11-13 21:41:08 -0800125
126 def output_sink(fn, data):
Dan Albert8b72aef2015-03-23 19:13:21 -0700127 ofile = open(os.path.join(OPTIONS.input_tmp, "SYSTEM", fn), "w")
128 ofile.write(data)
129 ofile.close()
Michael Runge2e0d8fc2014-11-13 21:41:08 -0800130
Tianjie Xu38af07f2017-05-25 17:38:53 -0700131 arc_name = "SYSTEM/" + fn
132 if arc_name in output_zip.namelist():
133 OPTIONS.replace_recovery_patch_files_list.append(arc_name)
134 else:
135 common.ZipWrite(output_zip, ofile.name, arc_name)
136
Michael Runge2e0d8fc2014-11-13 21:41:08 -0800137 if OPTIONS.rebuild_recovery:
Tao Bao89fbb0f2017-01-10 10:47:58 -0800138 print("Building new recovery patch")
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
Dan Willemsen2ee00d52017-03-05 19:51:56 -0800142 block_list = OutputFile(output_zip, OPTIONS.input_tmp, prefix, "system.map")
143 CreateImage(OPTIONS.input_tmp, OPTIONS.info_dict, "system", img,
144 block_list=block_list)
David Zeuthend995f4b2016-01-29 16:59:17 -0500145
Dan Willemsen2ee00d52017-03-05 19:51:56 -0800146 return img.name
Doug Zongkerfc44a512014-08-26 13:10:25 -0700147
148
Alex Light4e358ab2016-06-16 14:47:10 -0700149def AddSystemOther(output_zip, prefix="IMAGES/"):
150 """Turn the contents of SYSTEM_OTHER into a system_other image
151 and store it in output_zip."""
152
Dan Willemsen2ee00d52017-03-05 19:51:56 -0800153 img = OutputFile(output_zip, OPTIONS.input_tmp, prefix, "system_other.img")
154 if os.path.exists(img.input_name):
Tao Bao89fbb0f2017-01-10 10:47:58 -0800155 print("system_other.img already exists in %s, no need to rebuild..." % (
156 prefix,))
Alex Light4e358ab2016-06-16 14:47:10 -0700157 return
158
Dan Willemsen2ee00d52017-03-05 19:51:56 -0800159 CreateImage(OPTIONS.input_tmp, OPTIONS.info_dict, "system_other", img)
Alex Light4e358ab2016-06-16 14:47:10 -0700160
161
Doug Zongkerfc44a512014-08-26 13:10:25 -0700162def AddVendor(output_zip, prefix="IMAGES/"):
163 """Turn the contents of VENDOR into a vendor image and store in it
164 output_zip."""
Michael Runge2e0d8fc2014-11-13 21:41:08 -0800165
Dan Willemsen2ee00d52017-03-05 19:51:56 -0800166 img = OutputFile(output_zip, OPTIONS.input_tmp, prefix, "vendor.img")
167 if os.path.exists(img.input_name):
Tao Bao89fbb0f2017-01-10 10:47:58 -0800168 print("vendor.img already exists in %s, no need to rebuild..." % (prefix,))
Dan Willemsen2ee00d52017-03-05 19:51:56 -0800169 return img.input_name
Michael Runge2e0d8fc2014-11-13 21:41:08 -0800170
Dan Willemsen2ee00d52017-03-05 19:51:56 -0800171 block_list = OutputFile(output_zip, OPTIONS.input_tmp, prefix, "vendor.map")
172 CreateImage(OPTIONS.input_tmp, OPTIONS.info_dict, "vendor", img,
173 block_list=block_list)
174 return img.name
Doug Zongker3c84f562014-07-31 11:06:30 -0700175
Yueyao Zhu889ee5e2017-05-12 17:50:46 -0700176def FindDtboPrebuilt(prefix="IMAGES/"):
177 """Find the prebuilt image of DTBO partition."""
178
179 prebuilt_path = os.path.join(OPTIONS.input_tmp, prefix, "dtbo.img")
180 if os.path.exists(prebuilt_path):
181 return prebuilt_path
182 return None
Doug Zongker3c84f562014-07-31 11:06:30 -0700183
Dan Willemsen2ee00d52017-03-05 19:51:56 -0800184def CreateImage(input_dir, info_dict, what, output_file, block_list=None):
Tao Bao89fbb0f2017-01-10 10:47:58 -0800185 print("creating " + what + ".img...")
Doug Zongker3c84f562014-07-31 11:06:30 -0700186
Doug Zongker3c84f562014-07-31 11:06:30 -0700187 # The name of the directory it is making an image out of matters to
188 # mkyaffs2image. It wants "system" but we have a directory named
189 # "SYSTEM", so create a symlink.
Dan Willemsen2ee00d52017-03-05 19:51:56 -0800190 temp_dir = tempfile.mkdtemp()
191 OPTIONS.tempfiles.append(temp_dir)
Doug Zongker3c84f562014-07-31 11:06:30 -0700192 try:
193 os.symlink(os.path.join(input_dir, what.upper()),
Dan Willemsen2ee00d52017-03-05 19:51:56 -0800194 os.path.join(temp_dir, what))
Dan Albert8b72aef2015-03-23 19:13:21 -0700195 except OSError as e:
196 # bogus error on my mac version?
197 # File "./build/tools/releasetools/img_from_target_files"
198 # os.path.join(OPTIONS.input_tmp, "system"))
199 # OSError: [Errno 17] File exists
200 if e.errno == errno.EEXIST:
Doug Zongker3c84f562014-07-31 11:06:30 -0700201 pass
202
203 image_props = build_image.ImagePropFromGlobalDict(info_dict, what)
204 fstab = info_dict["fstab"]
Tianjie Xucfa86222016-03-07 16:31:19 -0800205 mount_point = "/" + what
206 if fstab and mount_point in fstab:
207 image_props["fs_type"] = fstab[mount_point].fs_type
Doug Zongker3c84f562014-07-31 11:06:30 -0700208
Tao Bao822f5842015-09-30 16:01:14 -0700209 # Use a fixed timestamp (01/01/2009) when packaging the image.
210 # Bug: 24377993
211 epoch = datetime.datetime.fromtimestamp(0)
212 timestamp = (datetime.datetime(2009, 1, 1) - epoch).total_seconds()
213 image_props["timestamp"] = int(timestamp)
214
Doug Zongker3c84f562014-07-31 11:06:30 -0700215 if what == "system":
216 fs_config_prefix = ""
217 else:
218 fs_config_prefix = what + "_"
219
220 fs_config = os.path.join(
221 input_dir, "META/" + fs_config_prefix + "filesystem_config.txt")
Dan Albert8b72aef2015-03-23 19:13:21 -0700222 if not os.path.exists(fs_config):
223 fs_config = None
Doug Zongker3c84f562014-07-31 11:06:30 -0700224
Ying Wanga2292c92015-03-24 19:07:40 -0700225 # Override values loaded from info_dict.
226 if fs_config:
227 image_props["fs_config"] = fs_config
Ying Wanga2292c92015-03-24 19:07:40 -0700228 if block_list:
Dan Willemsen2ee00d52017-03-05 19:51:56 -0800229 image_props["block_list"] = block_list.name
Ying Wanga2292c92015-03-24 19:07:40 -0700230
Dan Willemsen2ee00d52017-03-05 19:51:56 -0800231 succ = build_image.BuildImage(os.path.join(temp_dir, what),
232 image_props, output_file.name)
Doug Zongker3c84f562014-07-31 11:06:30 -0700233 assert succ, "build " + what + ".img image failed"
234
Dan Willemsen2ee00d52017-03-05 19:51:56 -0800235 output_file.Write()
236 if block_list:
237 block_list.Write()
238
Tianjie Xu6b2e1552017-06-01 11:32:32 -0700239 # Set the 'adjusted_partition_size' that excludes the verity blocks of the
240 # given image. When avb is enabled, this size is the max image size returned
241 # by the avb tool.
Tianjie Xuf1a13182017-01-19 17:39:30 -0800242 is_verity_partition = "verity_block_device" in image_props
Tianjie Xu6b2e1552017-06-01 11:32:32 -0700243 verity_supported = (image_props.get("verity") == "true" or
244 image_props.get("board_avb_enable") == "true")
245 is_avb_enable = image_props.get("avb_hashtree_enable") == "true"
246 if verity_supported and (is_verity_partition or is_avb_enable):
Tianjie Xuf1a13182017-01-19 17:39:30 -0800247 adjusted_blocks_value = image_props.get("partition_size")
248 if adjusted_blocks_value:
249 adjusted_blocks_key = what + "_adjusted_partition_size"
250 info_dict[adjusted_blocks_key] = int(adjusted_blocks_value)/4096 - 1
251
Doug Zongker3c84f562014-07-31 11:06:30 -0700252
253def AddUserdata(output_zip, prefix="IMAGES/"):
Ying Wang2a048392015-06-25 13:56:53 -0700254 """Create a userdata image and store it in output_zip.
255
256 In most case we just create and store an empty userdata.img;
257 But the invoker can also request to create userdata.img with real
258 data from the target files, by setting "userdata_img_with_data=true"
259 in OPTIONS.info_dict.
260 """
Doug Zongker3c84f562014-07-31 11:06:30 -0700261
Dan Willemsen2ee00d52017-03-05 19:51:56 -0800262 img = OutputFile(output_zip, OPTIONS.input_tmp, prefix, "userdata.img")
263 if os.path.exists(img.input_name):
Tao Bao89fbb0f2017-01-10 10:47:58 -0800264 print("userdata.img already exists in %s, no need to rebuild..." % (
265 prefix,))
Michael Runge2e0d8fc2014-11-13 21:41:08 -0800266 return
267
Elliott Hughes305b0882016-06-15 17:04:54 -0700268 # Skip userdata.img if no size.
Tao Bao2c15d9e2015-07-09 11:51:16 -0700269 image_props = build_image.ImagePropFromGlobalDict(OPTIONS.info_dict, "data")
Elliott Hughes305b0882016-06-15 17:04:54 -0700270 if not image_props.get("partition_size"):
Doug Zongker3c84f562014-07-31 11:06:30 -0700271 return
272
Tao Bao89fbb0f2017-01-10 10:47:58 -0800273 print("creating userdata.img...")
Doug Zongker3c84f562014-07-31 11:06:30 -0700274
Tao Bao822f5842015-09-30 16:01:14 -0700275 # Use a fixed timestamp (01/01/2009) when packaging the image.
276 # Bug: 24377993
277 epoch = datetime.datetime.fromtimestamp(0)
278 timestamp = (datetime.datetime(2009, 1, 1) - epoch).total_seconds()
279 image_props["timestamp"] = int(timestamp)
280
Doug Zongker3c84f562014-07-31 11:06:30 -0700281 # The name of the directory it is making an image out of matters to
282 # mkyaffs2image. So we create a temp dir, and within it we create an
Ying Wang2a048392015-06-25 13:56:53 -0700283 # empty dir named "data", or a symlink to the DATA dir,
284 # and build the image from that.
Doug Zongker3c84f562014-07-31 11:06:30 -0700285 temp_dir = tempfile.mkdtemp()
Dan Willemsen2ee00d52017-03-05 19:51:56 -0800286 OPTIONS.tempfiles.append(temp_dir)
Doug Zongker3c84f562014-07-31 11:06:30 -0700287 user_dir = os.path.join(temp_dir, "data")
Ying Wang2a048392015-06-25 13:56:53 -0700288 empty = (OPTIONS.info_dict.get("userdata_img_with_data") != "true")
289 if empty:
290 # Create an empty dir.
291 os.mkdir(user_dir)
292 else:
293 # Symlink to the DATA dir.
294 os.symlink(os.path.join(OPTIONS.input_tmp, "DATA"),
295 user_dir)
296
Doug Zongker3c84f562014-07-31 11:06:30 -0700297 fstab = OPTIONS.info_dict["fstab"]
298 if fstab:
Dan Albert8b72aef2015-03-23 19:13:21 -0700299 image_props["fs_type"] = fstab["/data"].fs_type
Doug Zongker3c84f562014-07-31 11:06:30 -0700300 succ = build_image.BuildImage(user_dir, image_props, img.name)
301 assert succ, "build userdata.img image failed"
302
303 common.CheckSize(img.name, "userdata.img", OPTIONS.info_dict)
Dan Willemsen2ee00d52017-03-05 19:51:56 -0800304 img.Write()
Doug Zongker3c84f562014-07-31 11:06:30 -0700305
306
Bowgo Tsai8ee4a3d2017-03-31 15:21:26 +0800307def AddVBMeta(output_zip, boot_img_path, system_img_path, vendor_img_path,
Yueyao Zhu889ee5e2017-05-12 17:50:46 -0700308 dtbo_img_path, prefix="IMAGES/"):
David Zeuthen2ce63ed2016-09-15 13:43:54 -0400309 """Create a VBMeta image and store it in output_zip."""
Dan Willemsen2ee00d52017-03-05 19:51:56 -0800310 img = OutputFile(output_zip, OPTIONS.input_tmp, prefix, "vbmeta.img")
David Zeuthen2ce63ed2016-09-15 13:43:54 -0400311 avbtool = os.getenv('AVBTOOL') or "avbtool"
312 cmd = [avbtool, "make_vbmeta_image",
Dan Willemsen2ee00d52017-03-05 19:51:56 -0800313 "--output", img.name,
David Zeuthen2ce63ed2016-09-15 13:43:54 -0400314 "--include_descriptors_from_image", boot_img_path,
Bowgo Tsai9b377602017-04-14 18:50:11 +0800315 "--include_descriptors_from_image", system_img_path]
Bowgo Tsai8ee4a3d2017-03-31 15:21:26 +0800316 if vendor_img_path is not None:
317 cmd.extend(["--include_descriptors_from_image", vendor_img_path])
Yueyao Zhu889ee5e2017-05-12 17:50:46 -0700318 if dtbo_img_path is not None:
319 cmd.extend(["--include_descriptors_from_image", dtbo_img_path])
Bowgo Tsai9b377602017-04-14 18:50:11 +0800320 if OPTIONS.info_dict.get("system_root_image", None) == "true":
321 cmd.extend(["--setup_rootfs_from_kernel", system_img_path])
David Zeuthen2ce63ed2016-09-15 13:43:54 -0400322 common.AppendAVBSigningArgs(cmd)
323 args = OPTIONS.info_dict.get("board_avb_make_vbmeta_image_args", None)
324 if args and args.strip():
325 cmd.extend(shlex.split(args))
326 p = common.Run(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
327 p.communicate()
328 assert p.returncode == 0, "avbtool make_vbmeta_image failed"
Dan Willemsen2ee00d52017-03-05 19:51:56 -0800329 img.Write()
David Zeuthen2ce63ed2016-09-15 13:43:54 -0400330
331
David Zeuthen25328622016-04-08 15:08:03 -0400332def AddPartitionTable(output_zip, prefix="IMAGES/"):
333 """Create a partition table image and store it in output_zip."""
334
Dan Willemsen2ee00d52017-03-05 19:51:56 -0800335 img = OutputFile(output_zip, OPTIONS.input_tmp, prefix, "partition-table.img")
336 bpt = OutputFile(output_zip, OPTIONS.input_tmp, prefix, "partition-table.bpt")
David Zeuthen25328622016-04-08 15:08:03 -0400337
338 # use BPTTOOL from environ, or "bpttool" if empty or not set.
339 bpttool = os.getenv("BPTTOOL") or "bpttool"
Dan Willemsen2ee00d52017-03-05 19:51:56 -0800340 cmd = [bpttool, "make_table", "--output_json", bpt.name,
341 "--output_gpt", img.name]
David Zeuthen25328622016-04-08 15:08:03 -0400342 input_files_str = OPTIONS.info_dict["board_bpt_input_files"]
343 input_files = input_files_str.split(" ")
344 for i in input_files:
345 cmd.extend(["--input", i])
346 disk_size = OPTIONS.info_dict.get("board_bpt_disk_size")
347 if disk_size:
348 cmd.extend(["--disk_size", disk_size])
349 args = OPTIONS.info_dict.get("board_bpt_make_table_args")
350 if args:
351 cmd.extend(shlex.split(args))
352
353 p = common.Run(cmd, stdout=subprocess.PIPE)
354 p.communicate()
355 assert p.returncode == 0, "bpttool make_table failed"
356
Dan Willemsen2ee00d52017-03-05 19:51:56 -0800357 img.Write()
358 bpt.Write()
David Zeuthen25328622016-04-08 15:08:03 -0400359
360
Doug Zongker3c84f562014-07-31 11:06:30 -0700361def AddCache(output_zip, prefix="IMAGES/"):
362 """Create an empty cache image and store it in output_zip."""
363
Dan Willemsen2ee00d52017-03-05 19:51:56 -0800364 img = OutputFile(output_zip, OPTIONS.input_tmp, prefix, "cache.img")
365 if os.path.exists(img.input_name):
Tao Bao89fbb0f2017-01-10 10:47:58 -0800366 print("cache.img already exists in %s, no need to rebuild..." % (prefix,))
Michael Runge2e0d8fc2014-11-13 21:41:08 -0800367 return
368
Tao Bao2c15d9e2015-07-09 11:51:16 -0700369 image_props = build_image.ImagePropFromGlobalDict(OPTIONS.info_dict, "cache")
Doug Zongker3c84f562014-07-31 11:06:30 -0700370 # The build system has to explicitly request for cache.img.
371 if "fs_type" not in image_props:
372 return
373
Tao Bao89fbb0f2017-01-10 10:47:58 -0800374 print("creating cache.img...")
Doug Zongker3c84f562014-07-31 11:06:30 -0700375
Tao Bao822f5842015-09-30 16:01:14 -0700376 # Use a fixed timestamp (01/01/2009) when packaging the image.
377 # Bug: 24377993
378 epoch = datetime.datetime.fromtimestamp(0)
379 timestamp = (datetime.datetime(2009, 1, 1) - epoch).total_seconds()
380 image_props["timestamp"] = int(timestamp)
381
Doug Zongker3c84f562014-07-31 11:06:30 -0700382 # The name of the directory it is making an image out of matters to
383 # mkyaffs2image. So we create a temp dir, and within it we create an
384 # empty dir named "cache", and build the image from that.
385 temp_dir = tempfile.mkdtemp()
Dan Willemsen2ee00d52017-03-05 19:51:56 -0800386 OPTIONS.tempfiles.append(temp_dir)
Doug Zongker3c84f562014-07-31 11:06:30 -0700387 user_dir = os.path.join(temp_dir, "cache")
388 os.mkdir(user_dir)
Doug Zongker3c84f562014-07-31 11:06:30 -0700389
390 fstab = OPTIONS.info_dict["fstab"]
391 if fstab:
Dan Albert8b72aef2015-03-23 19:13:21 -0700392 image_props["fs_type"] = fstab["/cache"].fs_type
Doug Zongker3c84f562014-07-31 11:06:30 -0700393 succ = build_image.BuildImage(user_dir, image_props, img.name)
394 assert succ, "build cache.img image failed"
395
396 common.CheckSize(img.name, "cache.img", OPTIONS.info_dict)
Dan Willemsen2ee00d52017-03-05 19:51:56 -0800397 img.Write()
Doug Zongker3c84f562014-07-31 11:06:30 -0700398
399
Tianjie Xu38af07f2017-05-25 17:38:53 -0700400def ReplaceRecoveryPatchFiles(zip_filename):
401 """Update the related files under SYSTEM/ after rebuilding recovery."""
402
403 cmd = ["zip", "-d", zip_filename] + OPTIONS.replace_recovery_patch_files_list
404 p = common.Run(cmd, stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
405 p.communicate()
406
407 output_zip = zipfile.ZipFile(zip_filename, "a",
408 compression=zipfile.ZIP_DEFLATED,
409 allowZip64=True)
410 for item in OPTIONS.replace_recovery_patch_files_list:
411 file_path = os.path.join(OPTIONS.input_tmp, item)
412 assert os.path.exists(file_path)
413 common.ZipWrite(output_zip, file_path, arcname=item)
414 common.ZipClose(output_zip)
415
416
Doug Zongker3c84f562014-07-31 11:06:30 -0700417def AddImagesToTargetFiles(filename):
Dan Willemsen2ee00d52017-03-05 19:51:56 -0800418 if os.path.isdir(filename):
419 OPTIONS.input_tmp = os.path.abspath(filename)
420 input_zip = None
421 else:
422 OPTIONS.input_tmp, input_zip = common.UnzipTemp(filename)
Doug Zongkerfc44a512014-08-26 13:10:25 -0700423
Michael Runge2e0d8fc2014-11-13 21:41:08 -0800424 if not OPTIONS.add_missing:
Dan Willemsen2ee00d52017-03-05 19:51:56 -0800425 if os.path.isdir(os.path.join(OPTIONS.input_tmp, "IMAGES")):
426 print("target_files appears to already contain images.")
427 sys.exit(1)
Doug Zongkerfc44a512014-08-26 13:10:25 -0700428
Dan Willemsen2ee00d52017-03-05 19:51:56 -0800429 has_vendor = os.path.isdir(os.path.join(OPTIONS.input_tmp, "VENDOR"))
430 has_system_other = os.path.isdir(os.path.join(OPTIONS.input_tmp,
431 "SYSTEM_OTHER"))
Doug Zongker3c84f562014-07-31 11:06:30 -0700432
Dan Willemsen2ee00d52017-03-05 19:51:56 -0800433 if input_zip:
434 OPTIONS.info_dict = common.LoadInfoDict(input_zip, OPTIONS.input_tmp)
Alex Light4e358ab2016-06-16 14:47:10 -0700435
Dan Willemsen2ee00d52017-03-05 19:51:56 -0800436 common.ZipClose(input_zip)
437 output_zip = zipfile.ZipFile(filename, "a",
438 compression=zipfile.ZIP_DEFLATED,
439 allowZip64=True)
440 else:
441 OPTIONS.info_dict = common.LoadInfoDict(filename, filename)
442 output_zip = None
443 images_dir = os.path.join(OPTIONS.input_tmp, "IMAGES")
444 if not os.path.isdir(images_dir):
445 os.makedirs(images_dir)
446 images_dir = None
Doug Zongker3c84f562014-07-31 11:06:30 -0700447
Tao Baodb45efa2015-10-27 19:25:18 -0700448 has_recovery = (OPTIONS.info_dict.get("no_recovery") != "true")
449
Doug Zongkerfc44a512014-08-26 13:10:25 -0700450 def banner(s):
Tao Bao89fbb0f2017-01-10 10:47:58 -0800451 print("\n\n++++ " + s + " ++++\n\n")
Doug Zongker3c84f562014-07-31 11:06:30 -0700452
Michael Runge2e0d8fc2014-11-13 21:41:08 -0800453 prebuilt_path = os.path.join(OPTIONS.input_tmp, "IMAGES", "boot.img")
454 boot_image = None
455 if os.path.exists(prebuilt_path):
David Zeuthend995f4b2016-01-29 16:59:17 -0500456 banner("boot")
Tao Bao89fbb0f2017-01-10 10:47:58 -0800457 print("boot.img already exists in IMAGES/, no need to rebuild...")
Michael Runge2e0d8fc2014-11-13 21:41:08 -0800458 if OPTIONS.rebuild_recovery:
459 boot_image = common.GetBootableImage(
460 "IMAGES/boot.img", "boot.img", OPTIONS.input_tmp, "BOOT")
461 else:
David Zeuthen2ce63ed2016-09-15 13:43:54 -0400462 banner("boot")
463 boot_image = common.GetBootableImage(
Michael Runge2e0d8fc2014-11-13 21:41:08 -0800464 "IMAGES/boot.img", "boot.img", OPTIONS.input_tmp, "BOOT")
David Zeuthen2ce63ed2016-09-15 13:43:54 -0400465 if boot_image:
Dan Willemsen2ee00d52017-03-05 19:51:56 -0800466 if output_zip:
467 boot_image.AddToZip(output_zip)
468 else:
469 boot_image.WriteToDir(OPTIONS.input_tmp)
Doug Zongker3c84f562014-07-31 11:06:30 -0700470
Michael Runge2e0d8fc2014-11-13 21:41:08 -0800471 recovery_image = None
Tao Baodb45efa2015-10-27 19:25:18 -0700472 if has_recovery:
473 banner("recovery")
474 prebuilt_path = os.path.join(OPTIONS.input_tmp, "IMAGES", "recovery.img")
475 if os.path.exists(prebuilt_path):
Tao Bao89fbb0f2017-01-10 10:47:58 -0800476 print("recovery.img already exists in IMAGES/, no need to rebuild...")
Tao Baodb45efa2015-10-27 19:25:18 -0700477 if OPTIONS.rebuild_recovery:
478 recovery_image = common.GetBootableImage(
479 "IMAGES/recovery.img", "recovery.img", OPTIONS.input_tmp,
480 "RECOVERY")
481 else:
Michael Runge2e0d8fc2014-11-13 21:41:08 -0800482 recovery_image = common.GetBootableImage(
483 "IMAGES/recovery.img", "recovery.img", OPTIONS.input_tmp, "RECOVERY")
Tao Baodb45efa2015-10-27 19:25:18 -0700484 if recovery_image:
Dan Willemsen2ee00d52017-03-05 19:51:56 -0800485 if output_zip:
486 recovery_image.AddToZip(output_zip)
487 else:
488 recovery_image.WriteToDir(OPTIONS.input_tmp)
Doug Zongker3c84f562014-07-31 11:06:30 -0700489
Tao Baod42e97e2016-11-30 12:11:57 -0800490 banner("recovery (two-step image)")
491 # The special recovery.img for two-step package use.
492 recovery_two_step_image = common.GetBootableImage(
493 "IMAGES/recovery-two-step.img", "recovery-two-step.img",
494 OPTIONS.input_tmp, "RECOVERY", two_step_image=True)
495 if recovery_two_step_image:
Dan Willemsen2ee00d52017-03-05 19:51:56 -0800496 if output_zip:
497 recovery_two_step_image.AddToZip(output_zip)
498 else:
499 recovery_two_step_image.WriteToDir(OPTIONS.input_tmp)
Tao Baod42e97e2016-11-30 12:11:57 -0800500
Doug Zongkerfc44a512014-08-26 13:10:25 -0700501 banner("system")
David Zeuthend995f4b2016-01-29 16:59:17 -0500502 system_img_path = AddSystem(
503 output_zip, recovery_img=recovery_image, boot_img=boot_image)
Tianjie Xu737afb92016-07-11 11:42:53 -0700504 vendor_img_path = None
Doug Zongkerfc44a512014-08-26 13:10:25 -0700505 if has_vendor:
506 banner("vendor")
Tianjie Xu737afb92016-07-11 11:42:53 -0700507 vendor_img_path = AddVendor(output_zip)
Alex Light4e358ab2016-06-16 14:47:10 -0700508 if has_system_other:
509 banner("system_other")
510 AddSystemOther(output_zip)
Tianjie Xub48589a2016-08-03 19:21:52 -0700511 if not OPTIONS.is_signing:
512 banner("userdata")
513 AddUserdata(output_zip)
514 banner("cache")
515 AddCache(output_zip)
David Zeuthen25328622016-04-08 15:08:03 -0400516 if OPTIONS.info_dict.get("board_bpt_enable", None) == "true":
517 banner("partition-table")
518 AddPartitionTable(output_zip)
David Zeuthen2ce63ed2016-09-15 13:43:54 -0400519 if OPTIONS.info_dict.get("board_avb_enable", None) == "true":
520 banner("vbmeta")
521 boot_contents = boot_image.WriteToTemp()
Yueyao Zhu889ee5e2017-05-12 17:50:46 -0700522 dtbo_img_path = FindDtboPrebuilt()
523 AddVBMeta(output_zip, boot_contents.name, system_img_path,
524 vendor_img_path, dtbo_img_path)
Doug Zongker3c84f562014-07-31 11:06:30 -0700525
Wei Wang2e735ca2016-05-10 22:48:13 -0700526 # For devices using A/B update, copy over images from RADIO/ and/or
527 # VENDOR_IMAGES/ to IMAGES/ and make sure we have all the needed
528 # images ready under IMAGES/. All images should have '.img' as extension.
Tianjie Xuaaca4212016-06-28 14:34:03 -0700529 banner("radio")
Tao Baoa0421cd2015-11-16 16:32:27 -0800530 ab_partitions = os.path.join(OPTIONS.input_tmp, "META", "ab_partitions.txt")
531 if os.path.exists(ab_partitions):
532 with open(ab_partitions, 'r') as f:
533 lines = f.readlines()
Tianjie Xucfa86222016-03-07 16:31:19 -0800534 # For devices using A/B update, generate care_map for system and vendor
535 # partitions (if present), then write this file to target_files package.
536 care_map_list = []
Tao Baoa0421cd2015-11-16 16:32:27 -0800537 for line in lines:
Tianjie Xu6b2e1552017-06-01 11:32:32 -0700538 if line.strip() == "system" and (
539 "system_verity_block_device" in OPTIONS.info_dict or
540 OPTIONS.info_dict.get("system_avb_hashtree_enable") == "true"):
Tianjie Xu737afb92016-07-11 11:42:53 -0700541 assert os.path.exists(system_img_path)
542 care_map_list += GetCareMap("system", system_img_path)
Tianjie Xu6b2e1552017-06-01 11:32:32 -0700543 if line.strip() == "vendor" and (
544 "vendor_verity_block_device" in OPTIONS.info_dict or
545 OPTIONS.info_dict.get("vendor_avb_hashtree_enable") == "true"):
Tianjie Xu737afb92016-07-11 11:42:53 -0700546 assert os.path.exists(vendor_img_path)
547 care_map_list += GetCareMap("vendor", vendor_img_path)
Tianjie Xucfa86222016-03-07 16:31:19 -0800548
Tao Baoa0421cd2015-11-16 16:32:27 -0800549 img_name = line.strip() + ".img"
Tianjie Xuaaca4212016-06-28 14:34:03 -0700550 prebuilt_path = os.path.join(OPTIONS.input_tmp, "IMAGES", img_name)
551 if os.path.exists(prebuilt_path):
Tao Bao89fbb0f2017-01-10 10:47:58 -0800552 print("%s already exists, no need to overwrite..." % (img_name,))
Tianjie Xuaaca4212016-06-28 14:34:03 -0700553 continue
554
Tao Baoa0421cd2015-11-16 16:32:27 -0800555 img_radio_path = os.path.join(OPTIONS.input_tmp, "RADIO", img_name)
Wei Wang2e735ca2016-05-10 22:48:13 -0700556 img_vendor_dir = os.path.join(
557 OPTIONS.input_tmp, "VENDOR_IMAGES")
Tao Baoa0421cd2015-11-16 16:32:27 -0800558 if os.path.exists(img_radio_path):
Dan Willemsen2ee00d52017-03-05 19:51:56 -0800559 if output_zip:
560 common.ZipWrite(output_zip, img_radio_path,
561 os.path.join("IMAGES", img_name))
562 else:
563 shutil.copy(img_radio_path, prebuilt_path)
Wei Wang2e735ca2016-05-10 22:48:13 -0700564 else:
565 for root, _, files in os.walk(img_vendor_dir):
566 if img_name in files:
Dan Willemsen2ee00d52017-03-05 19:51:56 -0800567 if output_zip:
568 common.ZipWrite(output_zip, os.path.join(root, img_name),
569 os.path.join("IMAGES", img_name))
570 else:
571 shutil.copy(os.path.join(root, img_name), prebuilt_path)
Wei Wang2e735ca2016-05-10 22:48:13 -0700572 break
Tao Baoa0421cd2015-11-16 16:32:27 -0800573
Dan Willemsen2ee00d52017-03-05 19:51:56 -0800574 if output_zip:
575 # Zip spec says: All slashes MUST be forward slashes.
576 img_path = 'IMAGES/' + img_name
577 assert img_path in output_zip.namelist(), "cannot find " + img_name
578 else:
579 img_path = os.path.join(OPTIONS.input_tmp, "IMAGES", img_name)
580 assert os.path.exists(img_path), "cannot find " + img_name
Tao Baoa0421cd2015-11-16 16:32:27 -0800581
Tianjie Xucfa86222016-03-07 16:31:19 -0800582 if care_map_list:
583 file_path = "META/care_map.txt"
Dan Willemsen2ee00d52017-03-05 19:51:56 -0800584 if output_zip:
585 common.ZipWriteStr(output_zip, file_path, '\n'.join(care_map_list))
586 else:
587 with open(os.path.join(OPTIONS.input_tmp, file_path), 'w') as fp:
588 fp.write('\n'.join(care_map_list))
Tianjie Xucfa86222016-03-07 16:31:19 -0800589
Dan Willemsen2ee00d52017-03-05 19:51:56 -0800590 if output_zip:
591 common.ZipClose(output_zip)
Tianjie Xu38af07f2017-05-25 17:38:53 -0700592 if OPTIONS.replace_recovery_patch_files_list:
593 ReplaceRecoveryPatchFiles(output_zip.filename)
594
Doug Zongker3c84f562014-07-31 11:06:30 -0700595
Doug Zongker3c84f562014-07-31 11:06:30 -0700596def main(argv):
Baligh Uddin59f4ff12015-09-16 21:20:30 -0700597 def option_handler(o, a):
Michael Runge2e0d8fc2014-11-13 21:41:08 -0800598 if o in ("-a", "--add_missing"):
599 OPTIONS.add_missing = True
600 elif o in ("-r", "--rebuild_recovery",):
601 OPTIONS.rebuild_recovery = True
Baligh Uddin59f4ff12015-09-16 21:20:30 -0700602 elif o == "--replace_verity_private_key":
603 OPTIONS.replace_verity_private_key = (True, a)
604 elif o == "--replace_verity_public_key":
605 OPTIONS.replace_verity_public_key = (True, a)
Tianjie Xub48589a2016-08-03 19:21:52 -0700606 elif o == "--is_signing":
607 OPTIONS.is_signing = True
Michael Runge2e0d8fc2014-11-13 21:41:08 -0800608 else:
609 return False
610 return True
611
Dan Albert8b72aef2015-03-23 19:13:21 -0700612 args = common.ParseOptions(
613 argv, __doc__, extra_opts="ar",
Baligh Uddin59f4ff12015-09-16 21:20:30 -0700614 extra_long_opts=["add_missing", "rebuild_recovery",
615 "replace_verity_public_key=",
616 "replace_verity_private_key=",
Tao Bao45810422016-10-17 16:20:12 -0700617 "is_signing"],
Dan Albert8b72aef2015-03-23 19:13:21 -0700618 extra_option_handler=option_handler)
Michael Runge2e0d8fc2014-11-13 21:41:08 -0800619
Doug Zongker3c84f562014-07-31 11:06:30 -0700620
621 if len(args) != 1:
622 common.Usage(__doc__)
623 sys.exit(1)
624
625 AddImagesToTargetFiles(args[0])
Tao Bao89fbb0f2017-01-10 10:47:58 -0800626 print("done.")
Doug Zongker3c84f562014-07-31 11:06:30 -0700627
628if __name__ == '__main__':
629 try:
630 common.CloseInheritedPipes()
631 main(sys.argv[1:])
Dan Albert8b72aef2015-03-23 19:13:21 -0700632 except common.ExternalError as e:
Tao Bao89fbb0f2017-01-10 10:47:58 -0800633 print("\n ERROR: %s\n" % (e,))
Doug Zongker3c84f562014-07-31 11:06:30 -0700634 sys.exit(1)
Doug Zongkerfc44a512014-08-26 13:10:25 -0700635 finally:
636 common.Cleanup()