blob: 82394ca9074c15eccf697df5441c9c2e241145a0 [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
Dan Willemsen2ee00d52017-03-05 19:51:56 -080076
77class OutputFile(object):
78 def __init__(self, output_zip, input_dir, prefix, name):
79 self._output_zip = output_zip
80 self.input_name = os.path.join(input_dir, prefix, name)
81
82 if self._output_zip:
83 self._zip_name = os.path.join(prefix, name)
84
85 root, suffix = os.path.splitext(name)
86 self.name = common.MakeTempFile(prefix=root + '-', suffix=suffix)
87 else:
88 self.name = self.input_name
89
90 def Write(self):
91 if self._output_zip:
92 common.ZipWrite(self._output_zip, self.name, self._zip_name)
93
94
Tianjie Xucfa86222016-03-07 16:31:19 -080095def GetCareMap(which, imgname):
96 """Generate care_map of system (or vendor) partition"""
97
98 assert which in ("system", "vendor")
Tianjie Xucfa86222016-03-07 16:31:19 -080099
100 simg = sparse_img.SparseImage(imgname)
101 care_map_list = []
Tianjie Xu955629b2017-03-01 11:48:25 -0800102 care_map_list.append(which)
Tianjie Xuf1a13182017-01-19 17:39:30 -0800103
104 care_map_ranges = simg.care_map
105 key = which + "_adjusted_partition_size"
106 adjusted_blocks = OPTIONS.info_dict.get(key)
107 if adjusted_blocks:
108 assert adjusted_blocks > 0, "blocks should be positive for " + which
109 care_map_ranges = care_map_ranges.intersect(rangelib.RangeSet(
110 "0-%d" % (adjusted_blocks,)))
111
112 care_map_list.append(care_map_ranges.to_string_raw())
Tianjie Xucfa86222016-03-07 16:31:19 -0800113 return care_map_list
114
115
Michael Runge2e0d8fc2014-11-13 21:41:08 -0800116def AddSystem(output_zip, prefix="IMAGES/", recovery_img=None, boot_img=None):
Doug Zongker3c84f562014-07-31 11:06:30 -0700117 """Turn the contents of SYSTEM into a system image and store it in
David Zeuthend995f4b2016-01-29 16:59:17 -0500118 output_zip. Returns the name of the system image file."""
Michael Runge2e0d8fc2014-11-13 21:41:08 -0800119
Dan Willemsen2ee00d52017-03-05 19:51:56 -0800120 img = OutputFile(output_zip, OPTIONS.input_tmp, prefix, "system.img")
121 if os.path.exists(img.input_name):
Tao Bao89fbb0f2017-01-10 10:47:58 -0800122 print("system.img already exists in %s, no need to rebuild..." % (prefix,))
Dan Willemsen2ee00d52017-03-05 19:51:56 -0800123 return img.input_name
Michael Runge2e0d8fc2014-11-13 21:41:08 -0800124
125 def output_sink(fn, data):
Dan Albert8b72aef2015-03-23 19:13:21 -0700126 ofile = open(os.path.join(OPTIONS.input_tmp, "SYSTEM", fn), "w")
127 ofile.write(data)
128 ofile.close()
Michael Runge2e0d8fc2014-11-13 21:41:08 -0800129
130 if OPTIONS.rebuild_recovery:
Tao Bao89fbb0f2017-01-10 10:47:58 -0800131 print("Building new recovery patch")
Dan Albert8b72aef2015-03-23 19:13:21 -0700132 common.MakeRecoveryPatch(OPTIONS.input_tmp, output_sink, recovery_img,
133 boot_img, info_dict=OPTIONS.info_dict)
Michael Runge2e0d8fc2014-11-13 21:41:08 -0800134
Dan Willemsen2ee00d52017-03-05 19:51:56 -0800135 block_list = OutputFile(output_zip, OPTIONS.input_tmp, prefix, "system.map")
136 CreateImage(OPTIONS.input_tmp, OPTIONS.info_dict, "system", img,
137 block_list=block_list)
David Zeuthend995f4b2016-01-29 16:59:17 -0500138
Dan Willemsen2ee00d52017-03-05 19:51:56 -0800139 return img.name
Doug Zongkerfc44a512014-08-26 13:10:25 -0700140
141
Alex Light4e358ab2016-06-16 14:47:10 -0700142def AddSystemOther(output_zip, prefix="IMAGES/"):
143 """Turn the contents of SYSTEM_OTHER into a system_other image
144 and store it in output_zip."""
145
Dan Willemsen2ee00d52017-03-05 19:51:56 -0800146 img = OutputFile(output_zip, OPTIONS.input_tmp, prefix, "system_other.img")
147 if os.path.exists(img.input_name):
Tao Bao89fbb0f2017-01-10 10:47:58 -0800148 print("system_other.img already exists in %s, no need to rebuild..." % (
149 prefix,))
Alex Light4e358ab2016-06-16 14:47:10 -0700150 return
151
Dan Willemsen2ee00d52017-03-05 19:51:56 -0800152 CreateImage(OPTIONS.input_tmp, OPTIONS.info_dict, "system_other", img)
Alex Light4e358ab2016-06-16 14:47:10 -0700153
154
Doug Zongkerfc44a512014-08-26 13:10:25 -0700155def AddVendor(output_zip, prefix="IMAGES/"):
156 """Turn the contents of VENDOR into a vendor image and store in it
157 output_zip."""
Michael Runge2e0d8fc2014-11-13 21:41:08 -0800158
Dan Willemsen2ee00d52017-03-05 19:51:56 -0800159 img = OutputFile(output_zip, OPTIONS.input_tmp, prefix, "vendor.img")
160 if os.path.exists(img.input_name):
Tao Bao89fbb0f2017-01-10 10:47:58 -0800161 print("vendor.img already exists in %s, no need to rebuild..." % (prefix,))
Dan Willemsen2ee00d52017-03-05 19:51:56 -0800162 return img.input_name
Michael Runge2e0d8fc2014-11-13 21:41:08 -0800163
Dan Willemsen2ee00d52017-03-05 19:51:56 -0800164 block_list = OutputFile(output_zip, OPTIONS.input_tmp, prefix, "vendor.map")
165 CreateImage(OPTIONS.input_tmp, OPTIONS.info_dict, "vendor", img,
166 block_list=block_list)
167 return img.name
Doug Zongker3c84f562014-07-31 11:06:30 -0700168
Yueyao Zhu889ee5e2017-05-12 17:50:46 -0700169def FindDtboPrebuilt(prefix="IMAGES/"):
170 """Find the prebuilt image of DTBO partition."""
171
172 prebuilt_path = os.path.join(OPTIONS.input_tmp, prefix, "dtbo.img")
173 if os.path.exists(prebuilt_path):
174 return prebuilt_path
175 return None
Doug Zongker3c84f562014-07-31 11:06:30 -0700176
Dan Willemsen2ee00d52017-03-05 19:51:56 -0800177def CreateImage(input_dir, info_dict, what, output_file, block_list=None):
Tao Bao89fbb0f2017-01-10 10:47:58 -0800178 print("creating " + what + ".img...")
Doug Zongker3c84f562014-07-31 11:06:30 -0700179
Doug Zongker3c84f562014-07-31 11:06:30 -0700180 # 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.
Dan Willemsen2ee00d52017-03-05 19:51:56 -0800183 temp_dir = tempfile.mkdtemp()
184 OPTIONS.tempfiles.append(temp_dir)
Doug Zongker3c84f562014-07-31 11:06:30 -0700185 try:
186 os.symlink(os.path.join(input_dir, what.upper()),
Dan Willemsen2ee00d52017-03-05 19:51:56 -0800187 os.path.join(temp_dir, what))
Dan Albert8b72aef2015-03-23 19:13:21 -0700188 except OSError as e:
189 # bogus error on my mac version?
190 # File "./build/tools/releasetools/img_from_target_files"
191 # os.path.join(OPTIONS.input_tmp, "system"))
192 # OSError: [Errno 17] File exists
193 if e.errno == errno.EEXIST:
Doug Zongker3c84f562014-07-31 11:06:30 -0700194 pass
195
196 image_props = build_image.ImagePropFromGlobalDict(info_dict, what)
197 fstab = info_dict["fstab"]
Tianjie Xucfa86222016-03-07 16:31:19 -0800198 mount_point = "/" + what
199 if fstab and mount_point in fstab:
200 image_props["fs_type"] = fstab[mount_point].fs_type
Doug Zongker3c84f562014-07-31 11:06:30 -0700201
Tao Bao822f5842015-09-30 16:01:14 -0700202 # Use a fixed timestamp (01/01/2009) when packaging the image.
203 # Bug: 24377993
204 epoch = datetime.datetime.fromtimestamp(0)
205 timestamp = (datetime.datetime(2009, 1, 1) - epoch).total_seconds()
206 image_props["timestamp"] = int(timestamp)
207
Doug Zongker3c84f562014-07-31 11:06:30 -0700208 if what == "system":
209 fs_config_prefix = ""
210 else:
211 fs_config_prefix = what + "_"
212
213 fs_config = os.path.join(
214 input_dir, "META/" + fs_config_prefix + "filesystem_config.txt")
Dan Albert8b72aef2015-03-23 19:13:21 -0700215 if not os.path.exists(fs_config):
216 fs_config = None
Doug Zongker3c84f562014-07-31 11:06:30 -0700217
Ying Wanga2292c92015-03-24 19:07:40 -0700218 # Override values loaded from info_dict.
219 if fs_config:
220 image_props["fs_config"] = fs_config
Ying Wanga2292c92015-03-24 19:07:40 -0700221 if block_list:
Dan Willemsen2ee00d52017-03-05 19:51:56 -0800222 image_props["block_list"] = block_list.name
Ying Wanga2292c92015-03-24 19:07:40 -0700223
Dan Willemsen2ee00d52017-03-05 19:51:56 -0800224 succ = build_image.BuildImage(os.path.join(temp_dir, what),
225 image_props, output_file.name)
Doug Zongker3c84f562014-07-31 11:06:30 -0700226 assert succ, "build " + what + ".img image failed"
227
Dan Willemsen2ee00d52017-03-05 19:51:56 -0800228 output_file.Write()
229 if block_list:
230 block_list.Write()
231
Tianjie Xuf1a13182017-01-19 17:39:30 -0800232 is_verity_partition = "verity_block_device" in image_props
233 verity_supported = image_props.get("verity") == "true"
234 if is_verity_partition and verity_supported:
235 adjusted_blocks_value = image_props.get("partition_size")
236 if adjusted_blocks_value:
237 adjusted_blocks_key = what + "_adjusted_partition_size"
238 info_dict[adjusted_blocks_key] = int(adjusted_blocks_value)/4096 - 1
239
Doug Zongker3c84f562014-07-31 11:06:30 -0700240
241def AddUserdata(output_zip, prefix="IMAGES/"):
Ying Wang2a048392015-06-25 13:56:53 -0700242 """Create a userdata image and store it in output_zip.
243
244 In most case we just create and store an empty userdata.img;
245 But the invoker can also request to create userdata.img with real
246 data from the target files, by setting "userdata_img_with_data=true"
247 in OPTIONS.info_dict.
248 """
Doug Zongker3c84f562014-07-31 11:06:30 -0700249
Dan Willemsen2ee00d52017-03-05 19:51:56 -0800250 img = OutputFile(output_zip, OPTIONS.input_tmp, prefix, "userdata.img")
251 if os.path.exists(img.input_name):
Tao Bao89fbb0f2017-01-10 10:47:58 -0800252 print("userdata.img already exists in %s, no need to rebuild..." % (
253 prefix,))
Michael Runge2e0d8fc2014-11-13 21:41:08 -0800254 return
255
Elliott Hughes305b0882016-06-15 17:04:54 -0700256 # Skip userdata.img if no size.
Tao Bao2c15d9e2015-07-09 11:51:16 -0700257 image_props = build_image.ImagePropFromGlobalDict(OPTIONS.info_dict, "data")
Elliott Hughes305b0882016-06-15 17:04:54 -0700258 if not image_props.get("partition_size"):
Doug Zongker3c84f562014-07-31 11:06:30 -0700259 return
260
Tao Bao89fbb0f2017-01-10 10:47:58 -0800261 print("creating userdata.img...")
Doug Zongker3c84f562014-07-31 11:06:30 -0700262
Tao Bao822f5842015-09-30 16:01:14 -0700263 # Use a fixed timestamp (01/01/2009) when packaging the image.
264 # Bug: 24377993
265 epoch = datetime.datetime.fromtimestamp(0)
266 timestamp = (datetime.datetime(2009, 1, 1) - epoch).total_seconds()
267 image_props["timestamp"] = int(timestamp)
268
Doug Zongker3c84f562014-07-31 11:06:30 -0700269 # The name of the directory it is making an image out of matters to
270 # mkyaffs2image. So we create a temp dir, and within it we create an
Ying Wang2a048392015-06-25 13:56:53 -0700271 # empty dir named "data", or a symlink to the DATA dir,
272 # and build the image from that.
Doug Zongker3c84f562014-07-31 11:06:30 -0700273 temp_dir = tempfile.mkdtemp()
Dan Willemsen2ee00d52017-03-05 19:51:56 -0800274 OPTIONS.tempfiles.append(temp_dir)
Doug Zongker3c84f562014-07-31 11:06:30 -0700275 user_dir = os.path.join(temp_dir, "data")
Ying Wang2a048392015-06-25 13:56:53 -0700276 empty = (OPTIONS.info_dict.get("userdata_img_with_data") != "true")
277 if empty:
278 # Create an empty dir.
279 os.mkdir(user_dir)
280 else:
281 # Symlink to the DATA dir.
282 os.symlink(os.path.join(OPTIONS.input_tmp, "DATA"),
283 user_dir)
284
Doug Zongker3c84f562014-07-31 11:06:30 -0700285 fstab = OPTIONS.info_dict["fstab"]
286 if fstab:
Dan Albert8b72aef2015-03-23 19:13:21 -0700287 image_props["fs_type"] = fstab["/data"].fs_type
Doug Zongker3c84f562014-07-31 11:06:30 -0700288 succ = build_image.BuildImage(user_dir, image_props, img.name)
289 assert succ, "build userdata.img image failed"
290
291 common.CheckSize(img.name, "userdata.img", OPTIONS.info_dict)
Dan Willemsen2ee00d52017-03-05 19:51:56 -0800292 img.Write()
Doug Zongker3c84f562014-07-31 11:06:30 -0700293
294
Bowgo Tsai8ee4a3d2017-03-31 15:21:26 +0800295def AddVBMeta(output_zip, boot_img_path, system_img_path, vendor_img_path,
Yueyao Zhu889ee5e2017-05-12 17:50:46 -0700296 dtbo_img_path, prefix="IMAGES/"):
David Zeuthen2ce63ed2016-09-15 13:43:54 -0400297 """Create a VBMeta image and store it in output_zip."""
Dan Willemsen2ee00d52017-03-05 19:51:56 -0800298 img = OutputFile(output_zip, OPTIONS.input_tmp, prefix, "vbmeta.img")
David Zeuthen2ce63ed2016-09-15 13:43:54 -0400299 avbtool = os.getenv('AVBTOOL') or "avbtool"
300 cmd = [avbtool, "make_vbmeta_image",
Dan Willemsen2ee00d52017-03-05 19:51:56 -0800301 "--output", img.name,
David Zeuthen2ce63ed2016-09-15 13:43:54 -0400302 "--include_descriptors_from_image", boot_img_path,
Bowgo Tsai9b377602017-04-14 18:50:11 +0800303 "--include_descriptors_from_image", system_img_path]
Bowgo Tsai8ee4a3d2017-03-31 15:21:26 +0800304 if vendor_img_path is not None:
305 cmd.extend(["--include_descriptors_from_image", vendor_img_path])
Yueyao Zhu889ee5e2017-05-12 17:50:46 -0700306 if dtbo_img_path is not None:
307 cmd.extend(["--include_descriptors_from_image", dtbo_img_path])
Bowgo Tsai9b377602017-04-14 18:50:11 +0800308 if OPTIONS.info_dict.get("system_root_image", None) == "true":
309 cmd.extend(["--setup_rootfs_from_kernel", system_img_path])
David Zeuthen2ce63ed2016-09-15 13:43:54 -0400310 common.AppendAVBSigningArgs(cmd)
311 args = OPTIONS.info_dict.get("board_avb_make_vbmeta_image_args", None)
312 if args and args.strip():
313 cmd.extend(shlex.split(args))
314 p = common.Run(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
315 p.communicate()
316 assert p.returncode == 0, "avbtool make_vbmeta_image failed"
Dan Willemsen2ee00d52017-03-05 19:51:56 -0800317 img.Write()
David Zeuthen2ce63ed2016-09-15 13:43:54 -0400318
319
David Zeuthen25328622016-04-08 15:08:03 -0400320def AddPartitionTable(output_zip, prefix="IMAGES/"):
321 """Create a partition table image and store it in output_zip."""
322
Dan Willemsen2ee00d52017-03-05 19:51:56 -0800323 img = OutputFile(output_zip, OPTIONS.input_tmp, prefix, "partition-table.img")
324 bpt = OutputFile(output_zip, OPTIONS.input_tmp, prefix, "partition-table.bpt")
David Zeuthen25328622016-04-08 15:08:03 -0400325
326 # use BPTTOOL from environ, or "bpttool" if empty or not set.
327 bpttool = os.getenv("BPTTOOL") or "bpttool"
Dan Willemsen2ee00d52017-03-05 19:51:56 -0800328 cmd = [bpttool, "make_table", "--output_json", bpt.name,
329 "--output_gpt", img.name]
David Zeuthen25328622016-04-08 15:08:03 -0400330 input_files_str = OPTIONS.info_dict["board_bpt_input_files"]
331 input_files = input_files_str.split(" ")
332 for i in input_files:
333 cmd.extend(["--input", i])
334 disk_size = OPTIONS.info_dict.get("board_bpt_disk_size")
335 if disk_size:
336 cmd.extend(["--disk_size", disk_size])
337 args = OPTIONS.info_dict.get("board_bpt_make_table_args")
338 if args:
339 cmd.extend(shlex.split(args))
340
341 p = common.Run(cmd, stdout=subprocess.PIPE)
342 p.communicate()
343 assert p.returncode == 0, "bpttool make_table failed"
344
Dan Willemsen2ee00d52017-03-05 19:51:56 -0800345 img.Write()
346 bpt.Write()
David Zeuthen25328622016-04-08 15:08:03 -0400347
348
Doug Zongker3c84f562014-07-31 11:06:30 -0700349def AddCache(output_zip, prefix="IMAGES/"):
350 """Create an empty cache image and store it in output_zip."""
351
Dan Willemsen2ee00d52017-03-05 19:51:56 -0800352 img = OutputFile(output_zip, OPTIONS.input_tmp, prefix, "cache.img")
353 if os.path.exists(img.input_name):
Tao Bao89fbb0f2017-01-10 10:47:58 -0800354 print("cache.img already exists in %s, no need to rebuild..." % (prefix,))
Michael Runge2e0d8fc2014-11-13 21:41:08 -0800355 return
356
Tao Bao2c15d9e2015-07-09 11:51:16 -0700357 image_props = build_image.ImagePropFromGlobalDict(OPTIONS.info_dict, "cache")
Doug Zongker3c84f562014-07-31 11:06:30 -0700358 # The build system has to explicitly request for cache.img.
359 if "fs_type" not in image_props:
360 return
361
Tao Bao89fbb0f2017-01-10 10:47:58 -0800362 print("creating cache.img...")
Doug Zongker3c84f562014-07-31 11:06:30 -0700363
Tao Bao822f5842015-09-30 16:01:14 -0700364 # Use a fixed timestamp (01/01/2009) when packaging the image.
365 # Bug: 24377993
366 epoch = datetime.datetime.fromtimestamp(0)
367 timestamp = (datetime.datetime(2009, 1, 1) - epoch).total_seconds()
368 image_props["timestamp"] = int(timestamp)
369
Doug Zongker3c84f562014-07-31 11:06:30 -0700370 # The name of the directory it is making an image out of matters to
371 # mkyaffs2image. So we create a temp dir, and within it we create an
372 # empty dir named "cache", and build the image from that.
373 temp_dir = tempfile.mkdtemp()
Dan Willemsen2ee00d52017-03-05 19:51:56 -0800374 OPTIONS.tempfiles.append(temp_dir)
Doug Zongker3c84f562014-07-31 11:06:30 -0700375 user_dir = os.path.join(temp_dir, "cache")
376 os.mkdir(user_dir)
Doug Zongker3c84f562014-07-31 11:06:30 -0700377
378 fstab = OPTIONS.info_dict["fstab"]
379 if fstab:
Dan Albert8b72aef2015-03-23 19:13:21 -0700380 image_props["fs_type"] = fstab["/cache"].fs_type
Doug Zongker3c84f562014-07-31 11:06:30 -0700381 succ = build_image.BuildImage(user_dir, image_props, img.name)
382 assert succ, "build cache.img image failed"
383
384 common.CheckSize(img.name, "cache.img", OPTIONS.info_dict)
Dan Willemsen2ee00d52017-03-05 19:51:56 -0800385 img.Write()
Doug Zongker3c84f562014-07-31 11:06:30 -0700386
387
388def AddImagesToTargetFiles(filename):
Dan Willemsen2ee00d52017-03-05 19:51:56 -0800389 if os.path.isdir(filename):
390 OPTIONS.input_tmp = os.path.abspath(filename)
391 input_zip = None
392 else:
393 OPTIONS.input_tmp, input_zip = common.UnzipTemp(filename)
Doug Zongkerfc44a512014-08-26 13:10:25 -0700394
Michael Runge2e0d8fc2014-11-13 21:41:08 -0800395 if not OPTIONS.add_missing:
Dan Willemsen2ee00d52017-03-05 19:51:56 -0800396 if os.path.isdir(os.path.join(OPTIONS.input_tmp, "IMAGES")):
397 print("target_files appears to already contain images.")
398 sys.exit(1)
Doug Zongkerfc44a512014-08-26 13:10:25 -0700399
Dan Willemsen2ee00d52017-03-05 19:51:56 -0800400 has_vendor = os.path.isdir(os.path.join(OPTIONS.input_tmp, "VENDOR"))
401 has_system_other = os.path.isdir(os.path.join(OPTIONS.input_tmp,
402 "SYSTEM_OTHER"))
Doug Zongker3c84f562014-07-31 11:06:30 -0700403
Dan Willemsen2ee00d52017-03-05 19:51:56 -0800404 if input_zip:
405 OPTIONS.info_dict = common.LoadInfoDict(input_zip, OPTIONS.input_tmp)
Alex Light4e358ab2016-06-16 14:47:10 -0700406
Dan Willemsen2ee00d52017-03-05 19:51:56 -0800407 common.ZipClose(input_zip)
408 output_zip = zipfile.ZipFile(filename, "a",
409 compression=zipfile.ZIP_DEFLATED,
410 allowZip64=True)
411 else:
412 OPTIONS.info_dict = common.LoadInfoDict(filename, filename)
413 output_zip = None
414 images_dir = os.path.join(OPTIONS.input_tmp, "IMAGES")
415 if not os.path.isdir(images_dir):
416 os.makedirs(images_dir)
417 images_dir = None
Doug Zongker3c84f562014-07-31 11:06:30 -0700418
Tao Baodb45efa2015-10-27 19:25:18 -0700419 has_recovery = (OPTIONS.info_dict.get("no_recovery") != "true")
420
Doug Zongkerfc44a512014-08-26 13:10:25 -0700421 def banner(s):
Tao Bao89fbb0f2017-01-10 10:47:58 -0800422 print("\n\n++++ " + s + " ++++\n\n")
Doug Zongker3c84f562014-07-31 11:06:30 -0700423
Michael Runge2e0d8fc2014-11-13 21:41:08 -0800424 prebuilt_path = os.path.join(OPTIONS.input_tmp, "IMAGES", "boot.img")
425 boot_image = None
426 if os.path.exists(prebuilt_path):
David Zeuthend995f4b2016-01-29 16:59:17 -0500427 banner("boot")
Tao Bao89fbb0f2017-01-10 10:47:58 -0800428 print("boot.img already exists in IMAGES/, no need to rebuild...")
Michael Runge2e0d8fc2014-11-13 21:41:08 -0800429 if OPTIONS.rebuild_recovery:
430 boot_image = common.GetBootableImage(
431 "IMAGES/boot.img", "boot.img", OPTIONS.input_tmp, "BOOT")
432 else:
David Zeuthen2ce63ed2016-09-15 13:43:54 -0400433 banner("boot")
434 boot_image = common.GetBootableImage(
Michael Runge2e0d8fc2014-11-13 21:41:08 -0800435 "IMAGES/boot.img", "boot.img", OPTIONS.input_tmp, "BOOT")
David Zeuthen2ce63ed2016-09-15 13:43:54 -0400436 if boot_image:
Dan Willemsen2ee00d52017-03-05 19:51:56 -0800437 if output_zip:
438 boot_image.AddToZip(output_zip)
439 else:
440 boot_image.WriteToDir(OPTIONS.input_tmp)
Doug Zongker3c84f562014-07-31 11:06:30 -0700441
Michael Runge2e0d8fc2014-11-13 21:41:08 -0800442 recovery_image = None
Tao Baodb45efa2015-10-27 19:25:18 -0700443 if has_recovery:
444 banner("recovery")
445 prebuilt_path = os.path.join(OPTIONS.input_tmp, "IMAGES", "recovery.img")
446 if os.path.exists(prebuilt_path):
Tao Bao89fbb0f2017-01-10 10:47:58 -0800447 print("recovery.img already exists in IMAGES/, no need to rebuild...")
Tao Baodb45efa2015-10-27 19:25:18 -0700448 if OPTIONS.rebuild_recovery:
449 recovery_image = common.GetBootableImage(
450 "IMAGES/recovery.img", "recovery.img", OPTIONS.input_tmp,
451 "RECOVERY")
452 else:
Michael Runge2e0d8fc2014-11-13 21:41:08 -0800453 recovery_image = common.GetBootableImage(
454 "IMAGES/recovery.img", "recovery.img", OPTIONS.input_tmp, "RECOVERY")
Tao Baodb45efa2015-10-27 19:25:18 -0700455 if recovery_image:
Dan Willemsen2ee00d52017-03-05 19:51:56 -0800456 if output_zip:
457 recovery_image.AddToZip(output_zip)
458 else:
459 recovery_image.WriteToDir(OPTIONS.input_tmp)
Doug Zongker3c84f562014-07-31 11:06:30 -0700460
Tao Baod42e97e2016-11-30 12:11:57 -0800461 banner("recovery (two-step image)")
462 # The special recovery.img for two-step package use.
463 recovery_two_step_image = common.GetBootableImage(
464 "IMAGES/recovery-two-step.img", "recovery-two-step.img",
465 OPTIONS.input_tmp, "RECOVERY", two_step_image=True)
466 if recovery_two_step_image:
Dan Willemsen2ee00d52017-03-05 19:51:56 -0800467 if output_zip:
468 recovery_two_step_image.AddToZip(output_zip)
469 else:
470 recovery_two_step_image.WriteToDir(OPTIONS.input_tmp)
Tao Baod42e97e2016-11-30 12:11:57 -0800471
Doug Zongkerfc44a512014-08-26 13:10:25 -0700472 banner("system")
David Zeuthend995f4b2016-01-29 16:59:17 -0500473 system_img_path = AddSystem(
474 output_zip, recovery_img=recovery_image, boot_img=boot_image)
Tianjie Xu737afb92016-07-11 11:42:53 -0700475 vendor_img_path = None
Doug Zongkerfc44a512014-08-26 13:10:25 -0700476 if has_vendor:
477 banner("vendor")
Tianjie Xu737afb92016-07-11 11:42:53 -0700478 vendor_img_path = AddVendor(output_zip)
Alex Light4e358ab2016-06-16 14:47:10 -0700479 if has_system_other:
480 banner("system_other")
481 AddSystemOther(output_zip)
Tianjie Xub48589a2016-08-03 19:21:52 -0700482 if not OPTIONS.is_signing:
483 banner("userdata")
484 AddUserdata(output_zip)
485 banner("cache")
486 AddCache(output_zip)
David Zeuthen25328622016-04-08 15:08:03 -0400487 if OPTIONS.info_dict.get("board_bpt_enable", None) == "true":
488 banner("partition-table")
489 AddPartitionTable(output_zip)
David Zeuthen2ce63ed2016-09-15 13:43:54 -0400490 if OPTIONS.info_dict.get("board_avb_enable", None) == "true":
491 banner("vbmeta")
492 boot_contents = boot_image.WriteToTemp()
Yueyao Zhu889ee5e2017-05-12 17:50:46 -0700493 dtbo_img_path = FindDtboPrebuilt()
494 AddVBMeta(output_zip, boot_contents.name, system_img_path,
495 vendor_img_path, dtbo_img_path)
Doug Zongker3c84f562014-07-31 11:06:30 -0700496
Wei Wang2e735ca2016-05-10 22:48:13 -0700497 # For devices using A/B update, copy over images from RADIO/ and/or
498 # VENDOR_IMAGES/ to IMAGES/ and make sure we have all the needed
499 # images ready under IMAGES/. All images should have '.img' as extension.
Tianjie Xuaaca4212016-06-28 14:34:03 -0700500 banner("radio")
Tao Baoa0421cd2015-11-16 16:32:27 -0800501 ab_partitions = os.path.join(OPTIONS.input_tmp, "META", "ab_partitions.txt")
502 if os.path.exists(ab_partitions):
503 with open(ab_partitions, 'r') as f:
504 lines = f.readlines()
Tianjie Xucfa86222016-03-07 16:31:19 -0800505 # For devices using A/B update, generate care_map for system and vendor
506 # partitions (if present), then write this file to target_files package.
507 care_map_list = []
Tao Baoa0421cd2015-11-16 16:32:27 -0800508 for line in lines:
Tianjie Xucfa86222016-03-07 16:31:19 -0800509 if line.strip() == "system" and OPTIONS.info_dict.get(
510 "system_verity_block_device", None) is not None:
Tianjie Xu737afb92016-07-11 11:42:53 -0700511 assert os.path.exists(system_img_path)
512 care_map_list += GetCareMap("system", system_img_path)
Tianjie Xucfa86222016-03-07 16:31:19 -0800513 if line.strip() == "vendor" and OPTIONS.info_dict.get(
514 "vendor_verity_block_device", None) is not None:
Tianjie Xu737afb92016-07-11 11:42:53 -0700515 assert os.path.exists(vendor_img_path)
516 care_map_list += GetCareMap("vendor", vendor_img_path)
Tianjie Xucfa86222016-03-07 16:31:19 -0800517
Tao Baoa0421cd2015-11-16 16:32:27 -0800518 img_name = line.strip() + ".img"
Tianjie Xuaaca4212016-06-28 14:34:03 -0700519 prebuilt_path = os.path.join(OPTIONS.input_tmp, "IMAGES", img_name)
520 if os.path.exists(prebuilt_path):
Tao Bao89fbb0f2017-01-10 10:47:58 -0800521 print("%s already exists, no need to overwrite..." % (img_name,))
Tianjie Xuaaca4212016-06-28 14:34:03 -0700522 continue
523
Tao Baoa0421cd2015-11-16 16:32:27 -0800524 img_radio_path = os.path.join(OPTIONS.input_tmp, "RADIO", img_name)
Wei Wang2e735ca2016-05-10 22:48:13 -0700525 img_vendor_dir = os.path.join(
526 OPTIONS.input_tmp, "VENDOR_IMAGES")
Tao Baoa0421cd2015-11-16 16:32:27 -0800527 if os.path.exists(img_radio_path):
Dan Willemsen2ee00d52017-03-05 19:51:56 -0800528 if output_zip:
529 common.ZipWrite(output_zip, img_radio_path,
530 os.path.join("IMAGES", img_name))
531 else:
532 shutil.copy(img_radio_path, prebuilt_path)
Wei Wang2e735ca2016-05-10 22:48:13 -0700533 else:
534 for root, _, files in os.walk(img_vendor_dir):
535 if img_name in files:
Dan Willemsen2ee00d52017-03-05 19:51:56 -0800536 if output_zip:
537 common.ZipWrite(output_zip, os.path.join(root, img_name),
538 os.path.join("IMAGES", img_name))
539 else:
540 shutil.copy(os.path.join(root, img_name), prebuilt_path)
Wei Wang2e735ca2016-05-10 22:48:13 -0700541 break
Tao Baoa0421cd2015-11-16 16:32:27 -0800542
Dan Willemsen2ee00d52017-03-05 19:51:56 -0800543 if output_zip:
544 # Zip spec says: All slashes MUST be forward slashes.
545 img_path = 'IMAGES/' + img_name
546 assert img_path in output_zip.namelist(), "cannot find " + img_name
547 else:
548 img_path = os.path.join(OPTIONS.input_tmp, "IMAGES", img_name)
549 assert os.path.exists(img_path), "cannot find " + img_name
Tao Baoa0421cd2015-11-16 16:32:27 -0800550
Tianjie Xucfa86222016-03-07 16:31:19 -0800551 if care_map_list:
552 file_path = "META/care_map.txt"
Dan Willemsen2ee00d52017-03-05 19:51:56 -0800553 if output_zip:
554 common.ZipWriteStr(output_zip, file_path, '\n'.join(care_map_list))
555 else:
556 with open(os.path.join(OPTIONS.input_tmp, file_path), 'w') as fp:
557 fp.write('\n'.join(care_map_list))
Tianjie Xucfa86222016-03-07 16:31:19 -0800558
Dan Willemsen2ee00d52017-03-05 19:51:56 -0800559 if output_zip:
560 common.ZipClose(output_zip)
Doug Zongker3c84f562014-07-31 11:06:30 -0700561
Doug Zongker3c84f562014-07-31 11:06:30 -0700562def main(argv):
Baligh Uddin59f4ff12015-09-16 21:20:30 -0700563 def option_handler(o, a):
Michael Runge2e0d8fc2014-11-13 21:41:08 -0800564 if o in ("-a", "--add_missing"):
565 OPTIONS.add_missing = True
566 elif o in ("-r", "--rebuild_recovery",):
567 OPTIONS.rebuild_recovery = True
Baligh Uddin59f4ff12015-09-16 21:20:30 -0700568 elif o == "--replace_verity_private_key":
569 OPTIONS.replace_verity_private_key = (True, a)
570 elif o == "--replace_verity_public_key":
571 OPTIONS.replace_verity_public_key = (True, a)
Tianjie Xub48589a2016-08-03 19:21:52 -0700572 elif o == "--is_signing":
573 OPTIONS.is_signing = True
Michael Runge2e0d8fc2014-11-13 21:41:08 -0800574 else:
575 return False
576 return True
577
Dan Albert8b72aef2015-03-23 19:13:21 -0700578 args = common.ParseOptions(
579 argv, __doc__, extra_opts="ar",
Baligh Uddin59f4ff12015-09-16 21:20:30 -0700580 extra_long_opts=["add_missing", "rebuild_recovery",
581 "replace_verity_public_key=",
582 "replace_verity_private_key=",
Tao Bao45810422016-10-17 16:20:12 -0700583 "is_signing"],
Dan Albert8b72aef2015-03-23 19:13:21 -0700584 extra_option_handler=option_handler)
Michael Runge2e0d8fc2014-11-13 21:41:08 -0800585
Doug Zongker3c84f562014-07-31 11:06:30 -0700586
587 if len(args) != 1:
588 common.Usage(__doc__)
589 sys.exit(1)
590
591 AddImagesToTargetFiles(args[0])
Tao Bao89fbb0f2017-01-10 10:47:58 -0800592 print("done.")
Doug Zongker3c84f562014-07-31 11:06:30 -0700593
594if __name__ == '__main__':
595 try:
596 common.CloseInheritedPipes()
597 main(sys.argv[1:])
Dan Albert8b72aef2015-03-23 19:13:21 -0700598 except common.ExternalError as e:
Tao Bao89fbb0f2017-01-10 10:47:58 -0800599 print("\n ERROR: %s\n" % (e,))
Doug Zongker3c84f562014-07-31 11:06:30 -0700600 sys.exit(1)
Doug Zongkerfc44a512014-08-26 13:10:25 -0700601 finally:
602 common.Cleanup()