blob: abdbbbb517677b94e312c5d296bc5583806d21f0 [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
169
Dan Willemsen2ee00d52017-03-05 19:51:56 -0800170def CreateImage(input_dir, info_dict, what, output_file, block_list=None):
Tao Bao89fbb0f2017-01-10 10:47:58 -0800171 print("creating " + what + ".img...")
Doug Zongker3c84f562014-07-31 11:06:30 -0700172
Doug Zongker3c84f562014-07-31 11:06:30 -0700173 # The name of the directory it is making an image out of matters to
174 # mkyaffs2image. It wants "system" but we have a directory named
175 # "SYSTEM", so create a symlink.
Dan Willemsen2ee00d52017-03-05 19:51:56 -0800176 temp_dir = tempfile.mkdtemp()
177 OPTIONS.tempfiles.append(temp_dir)
Doug Zongker3c84f562014-07-31 11:06:30 -0700178 try:
179 os.symlink(os.path.join(input_dir, what.upper()),
Dan Willemsen2ee00d52017-03-05 19:51:56 -0800180 os.path.join(temp_dir, what))
Dan Albert8b72aef2015-03-23 19:13:21 -0700181 except OSError as e:
182 # bogus error on my mac version?
183 # File "./build/tools/releasetools/img_from_target_files"
184 # os.path.join(OPTIONS.input_tmp, "system"))
185 # OSError: [Errno 17] File exists
186 if e.errno == errno.EEXIST:
Doug Zongker3c84f562014-07-31 11:06:30 -0700187 pass
188
189 image_props = build_image.ImagePropFromGlobalDict(info_dict, what)
190 fstab = info_dict["fstab"]
Tianjie Xucfa86222016-03-07 16:31:19 -0800191 mount_point = "/" + what
192 if fstab and mount_point in fstab:
193 image_props["fs_type"] = fstab[mount_point].fs_type
Doug Zongker3c84f562014-07-31 11:06:30 -0700194
Tao Bao822f5842015-09-30 16:01:14 -0700195 # Use a fixed timestamp (01/01/2009) when packaging the image.
196 # Bug: 24377993
197 epoch = datetime.datetime.fromtimestamp(0)
198 timestamp = (datetime.datetime(2009, 1, 1) - epoch).total_seconds()
199 image_props["timestamp"] = int(timestamp)
200
Doug Zongker3c84f562014-07-31 11:06:30 -0700201 if what == "system":
202 fs_config_prefix = ""
203 else:
204 fs_config_prefix = what + "_"
205
206 fs_config = os.path.join(
207 input_dir, "META/" + fs_config_prefix + "filesystem_config.txt")
Dan Albert8b72aef2015-03-23 19:13:21 -0700208 if not os.path.exists(fs_config):
209 fs_config = None
Doug Zongker3c84f562014-07-31 11:06:30 -0700210
Ying Wanga2292c92015-03-24 19:07:40 -0700211 # Override values loaded from info_dict.
212 if fs_config:
213 image_props["fs_config"] = fs_config
Ying Wanga2292c92015-03-24 19:07:40 -0700214 if block_list:
Dan Willemsen2ee00d52017-03-05 19:51:56 -0800215 image_props["block_list"] = block_list.name
Ying Wanga2292c92015-03-24 19:07:40 -0700216
Dan Willemsen2ee00d52017-03-05 19:51:56 -0800217 succ = build_image.BuildImage(os.path.join(temp_dir, what),
218 image_props, output_file.name)
Doug Zongker3c84f562014-07-31 11:06:30 -0700219 assert succ, "build " + what + ".img image failed"
220
Dan Willemsen2ee00d52017-03-05 19:51:56 -0800221 output_file.Write()
222 if block_list:
223 block_list.Write()
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 Zongker3c84f562014-07-31 11:06:30 -0700233
234def AddUserdata(output_zip, prefix="IMAGES/"):
Ying Wang2a048392015-06-25 13:56:53 -0700235 """Create a userdata image and store it in output_zip.
236
237 In most case we just create and store an empty userdata.img;
238 But the invoker can also request to create userdata.img with real
239 data from the target files, by setting "userdata_img_with_data=true"
240 in OPTIONS.info_dict.
241 """
Doug Zongker3c84f562014-07-31 11:06:30 -0700242
Dan Willemsen2ee00d52017-03-05 19:51:56 -0800243 img = OutputFile(output_zip, OPTIONS.input_tmp, prefix, "userdata.img")
244 if os.path.exists(img.input_name):
Tao Bao89fbb0f2017-01-10 10:47:58 -0800245 print("userdata.img already exists in %s, no need to rebuild..." % (
246 prefix,))
Michael Runge2e0d8fc2014-11-13 21:41:08 -0800247 return
248
Elliott Hughes305b0882016-06-15 17:04:54 -0700249 # Skip userdata.img if no size.
Tao Bao2c15d9e2015-07-09 11:51:16 -0700250 image_props = build_image.ImagePropFromGlobalDict(OPTIONS.info_dict, "data")
Elliott Hughes305b0882016-06-15 17:04:54 -0700251 if not image_props.get("partition_size"):
Doug Zongker3c84f562014-07-31 11:06:30 -0700252 return
253
Tao Bao89fbb0f2017-01-10 10:47:58 -0800254 print("creating userdata.img...")
Doug Zongker3c84f562014-07-31 11:06:30 -0700255
Tao Bao822f5842015-09-30 16:01:14 -0700256 # Use a fixed timestamp (01/01/2009) when packaging the image.
257 # Bug: 24377993
258 epoch = datetime.datetime.fromtimestamp(0)
259 timestamp = (datetime.datetime(2009, 1, 1) - epoch).total_seconds()
260 image_props["timestamp"] = int(timestamp)
261
Doug Zongker3c84f562014-07-31 11:06:30 -0700262 # The name of the directory it is making an image out of matters to
263 # mkyaffs2image. So we create a temp dir, and within it we create an
Ying Wang2a048392015-06-25 13:56:53 -0700264 # empty dir named "data", or a symlink to the DATA dir,
265 # and build the image from that.
Doug Zongker3c84f562014-07-31 11:06:30 -0700266 temp_dir = tempfile.mkdtemp()
Dan Willemsen2ee00d52017-03-05 19:51:56 -0800267 OPTIONS.tempfiles.append(temp_dir)
Doug Zongker3c84f562014-07-31 11:06:30 -0700268 user_dir = os.path.join(temp_dir, "data")
Ying Wang2a048392015-06-25 13:56:53 -0700269 empty = (OPTIONS.info_dict.get("userdata_img_with_data") != "true")
270 if empty:
271 # Create an empty dir.
272 os.mkdir(user_dir)
273 else:
274 # Symlink to the DATA dir.
275 os.symlink(os.path.join(OPTIONS.input_tmp, "DATA"),
276 user_dir)
277
Doug Zongker3c84f562014-07-31 11:06:30 -0700278 fstab = OPTIONS.info_dict["fstab"]
279 if fstab:
Dan Albert8b72aef2015-03-23 19:13:21 -0700280 image_props["fs_type"] = fstab["/data"].fs_type
Doug Zongker3c84f562014-07-31 11:06:30 -0700281 succ = build_image.BuildImage(user_dir, image_props, img.name)
282 assert succ, "build userdata.img image failed"
283
284 common.CheckSize(img.name, "userdata.img", OPTIONS.info_dict)
Dan Willemsen2ee00d52017-03-05 19:51:56 -0800285 img.Write()
Doug Zongker3c84f562014-07-31 11:06:30 -0700286
287
Bowgo Tsai8ee4a3d2017-03-31 15:21:26 +0800288def AddVBMeta(output_zip, boot_img_path, system_img_path, vendor_img_path,
289 prefix="IMAGES/"):
David Zeuthen2ce63ed2016-09-15 13:43:54 -0400290 """Create a VBMeta image and store it in output_zip."""
Dan Willemsen2ee00d52017-03-05 19:51:56 -0800291 img = OutputFile(output_zip, OPTIONS.input_tmp, prefix, "vbmeta.img")
David Zeuthen2ce63ed2016-09-15 13:43:54 -0400292 avbtool = os.getenv('AVBTOOL') or "avbtool"
293 cmd = [avbtool, "make_vbmeta_image",
Dan Willemsen2ee00d52017-03-05 19:51:56 -0800294 "--output", img.name,
David Zeuthen2ce63ed2016-09-15 13:43:54 -0400295 "--include_descriptors_from_image", boot_img_path,
296 "--include_descriptors_from_image", system_img_path,
297 "--generate_dm_verity_cmdline_from_hashtree", system_img_path]
Bowgo Tsai8ee4a3d2017-03-31 15:21:26 +0800298 if vendor_img_path is not None:
299 cmd.extend(["--include_descriptors_from_image", vendor_img_path])
David Zeuthen2ce63ed2016-09-15 13:43:54 -0400300 common.AppendAVBSigningArgs(cmd)
301 args = OPTIONS.info_dict.get("board_avb_make_vbmeta_image_args", None)
302 if args and args.strip():
303 cmd.extend(shlex.split(args))
304 p = common.Run(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
305 p.communicate()
306 assert p.returncode == 0, "avbtool make_vbmeta_image failed"
Dan Willemsen2ee00d52017-03-05 19:51:56 -0800307 img.Write()
David Zeuthen2ce63ed2016-09-15 13:43:54 -0400308
309
David Zeuthen25328622016-04-08 15:08:03 -0400310def AddPartitionTable(output_zip, prefix="IMAGES/"):
311 """Create a partition table image and store it in output_zip."""
312
Dan Willemsen2ee00d52017-03-05 19:51:56 -0800313 img = OutputFile(output_zip, OPTIONS.input_tmp, prefix, "partition-table.img")
314 bpt = OutputFile(output_zip, OPTIONS.input_tmp, prefix, "partition-table.bpt")
David Zeuthen25328622016-04-08 15:08:03 -0400315
316 # use BPTTOOL from environ, or "bpttool" if empty or not set.
317 bpttool = os.getenv("BPTTOOL") or "bpttool"
Dan Willemsen2ee00d52017-03-05 19:51:56 -0800318 cmd = [bpttool, "make_table", "--output_json", bpt.name,
319 "--output_gpt", img.name]
David Zeuthen25328622016-04-08 15:08:03 -0400320 input_files_str = OPTIONS.info_dict["board_bpt_input_files"]
321 input_files = input_files_str.split(" ")
322 for i in input_files:
323 cmd.extend(["--input", i])
324 disk_size = OPTIONS.info_dict.get("board_bpt_disk_size")
325 if disk_size:
326 cmd.extend(["--disk_size", disk_size])
327 args = OPTIONS.info_dict.get("board_bpt_make_table_args")
328 if args:
329 cmd.extend(shlex.split(args))
330
331 p = common.Run(cmd, stdout=subprocess.PIPE)
332 p.communicate()
333 assert p.returncode == 0, "bpttool make_table failed"
334
Dan Willemsen2ee00d52017-03-05 19:51:56 -0800335 img.Write()
336 bpt.Write()
David Zeuthen25328622016-04-08 15:08:03 -0400337
338
Doug Zongker3c84f562014-07-31 11:06:30 -0700339def AddCache(output_zip, prefix="IMAGES/"):
340 """Create an empty cache image and store it in output_zip."""
341
Dan Willemsen2ee00d52017-03-05 19:51:56 -0800342 img = OutputFile(output_zip, OPTIONS.input_tmp, prefix, "cache.img")
343 if os.path.exists(img.input_name):
Tao Bao89fbb0f2017-01-10 10:47:58 -0800344 print("cache.img already exists in %s, no need to rebuild..." % (prefix,))
Michael Runge2e0d8fc2014-11-13 21:41:08 -0800345 return
346
Tao Bao2c15d9e2015-07-09 11:51:16 -0700347 image_props = build_image.ImagePropFromGlobalDict(OPTIONS.info_dict, "cache")
Doug Zongker3c84f562014-07-31 11:06:30 -0700348 # The build system has to explicitly request for cache.img.
349 if "fs_type" not in image_props:
350 return
351
Tao Bao89fbb0f2017-01-10 10:47:58 -0800352 print("creating cache.img...")
Doug Zongker3c84f562014-07-31 11:06:30 -0700353
Tao Bao822f5842015-09-30 16:01:14 -0700354 # Use a fixed timestamp (01/01/2009) when packaging the image.
355 # Bug: 24377993
356 epoch = datetime.datetime.fromtimestamp(0)
357 timestamp = (datetime.datetime(2009, 1, 1) - epoch).total_seconds()
358 image_props["timestamp"] = int(timestamp)
359
Doug Zongker3c84f562014-07-31 11:06:30 -0700360 # The name of the directory it is making an image out of matters to
361 # mkyaffs2image. So we create a temp dir, and within it we create an
362 # empty dir named "cache", and build the image from that.
363 temp_dir = tempfile.mkdtemp()
Dan Willemsen2ee00d52017-03-05 19:51:56 -0800364 OPTIONS.tempfiles.append(temp_dir)
Doug Zongker3c84f562014-07-31 11:06:30 -0700365 user_dir = os.path.join(temp_dir, "cache")
366 os.mkdir(user_dir)
Doug Zongker3c84f562014-07-31 11:06:30 -0700367
368 fstab = OPTIONS.info_dict["fstab"]
369 if fstab:
Dan Albert8b72aef2015-03-23 19:13:21 -0700370 image_props["fs_type"] = fstab["/cache"].fs_type
Doug Zongker3c84f562014-07-31 11:06:30 -0700371 succ = build_image.BuildImage(user_dir, image_props, img.name)
372 assert succ, "build cache.img image failed"
373
374 common.CheckSize(img.name, "cache.img", OPTIONS.info_dict)
Dan Willemsen2ee00d52017-03-05 19:51:56 -0800375 img.Write()
Doug Zongker3c84f562014-07-31 11:06:30 -0700376
377
378def AddImagesToTargetFiles(filename):
Dan Willemsen2ee00d52017-03-05 19:51:56 -0800379 if os.path.isdir(filename):
380 OPTIONS.input_tmp = os.path.abspath(filename)
381 input_zip = None
382 else:
383 OPTIONS.input_tmp, input_zip = common.UnzipTemp(filename)
Doug Zongkerfc44a512014-08-26 13:10:25 -0700384
Michael Runge2e0d8fc2014-11-13 21:41:08 -0800385 if not OPTIONS.add_missing:
Dan Willemsen2ee00d52017-03-05 19:51:56 -0800386 if os.path.isdir(os.path.join(OPTIONS.input_tmp, "IMAGES")):
387 print("target_files appears to already contain images.")
388 sys.exit(1)
Doug Zongkerfc44a512014-08-26 13:10:25 -0700389
Dan Willemsen2ee00d52017-03-05 19:51:56 -0800390 has_vendor = os.path.isdir(os.path.join(OPTIONS.input_tmp, "VENDOR"))
391 has_system_other = os.path.isdir(os.path.join(OPTIONS.input_tmp,
392 "SYSTEM_OTHER"))
Doug Zongker3c84f562014-07-31 11:06:30 -0700393
Dan Willemsen2ee00d52017-03-05 19:51:56 -0800394 if input_zip:
395 OPTIONS.info_dict = common.LoadInfoDict(input_zip, OPTIONS.input_tmp)
Alex Light4e358ab2016-06-16 14:47:10 -0700396
Dan Willemsen2ee00d52017-03-05 19:51:56 -0800397 common.ZipClose(input_zip)
398 output_zip = zipfile.ZipFile(filename, "a",
399 compression=zipfile.ZIP_DEFLATED,
400 allowZip64=True)
401 else:
402 OPTIONS.info_dict = common.LoadInfoDict(filename, filename)
403 output_zip = None
404 images_dir = os.path.join(OPTIONS.input_tmp, "IMAGES")
405 if not os.path.isdir(images_dir):
406 os.makedirs(images_dir)
407 images_dir = None
Doug Zongker3c84f562014-07-31 11:06:30 -0700408
Tao Baodb45efa2015-10-27 19:25:18 -0700409 has_recovery = (OPTIONS.info_dict.get("no_recovery") != "true")
410
Doug Zongkerfc44a512014-08-26 13:10:25 -0700411 def banner(s):
Tao Bao89fbb0f2017-01-10 10:47:58 -0800412 print("\n\n++++ " + s + " ++++\n\n")
Doug Zongker3c84f562014-07-31 11:06:30 -0700413
Michael Runge2e0d8fc2014-11-13 21:41:08 -0800414 prebuilt_path = os.path.join(OPTIONS.input_tmp, "IMAGES", "boot.img")
415 boot_image = None
416 if os.path.exists(prebuilt_path):
David Zeuthend995f4b2016-01-29 16:59:17 -0500417 banner("boot")
Tao Bao89fbb0f2017-01-10 10:47:58 -0800418 print("boot.img already exists in IMAGES/, no need to rebuild...")
Michael Runge2e0d8fc2014-11-13 21:41:08 -0800419 if OPTIONS.rebuild_recovery:
420 boot_image = common.GetBootableImage(
421 "IMAGES/boot.img", "boot.img", OPTIONS.input_tmp, "BOOT")
422 else:
David Zeuthen2ce63ed2016-09-15 13:43:54 -0400423 banner("boot")
424 boot_image = common.GetBootableImage(
Michael Runge2e0d8fc2014-11-13 21:41:08 -0800425 "IMAGES/boot.img", "boot.img", OPTIONS.input_tmp, "BOOT")
David Zeuthen2ce63ed2016-09-15 13:43:54 -0400426 if boot_image:
Dan Willemsen2ee00d52017-03-05 19:51:56 -0800427 if output_zip:
428 boot_image.AddToZip(output_zip)
429 else:
430 boot_image.WriteToDir(OPTIONS.input_tmp)
Doug Zongker3c84f562014-07-31 11:06:30 -0700431
Michael Runge2e0d8fc2014-11-13 21:41:08 -0800432 recovery_image = None
Tao Baodb45efa2015-10-27 19:25:18 -0700433 if has_recovery:
434 banner("recovery")
435 prebuilt_path = os.path.join(OPTIONS.input_tmp, "IMAGES", "recovery.img")
436 if os.path.exists(prebuilt_path):
Tao Bao89fbb0f2017-01-10 10:47:58 -0800437 print("recovery.img already exists in IMAGES/, no need to rebuild...")
Tao Baodb45efa2015-10-27 19:25:18 -0700438 if OPTIONS.rebuild_recovery:
439 recovery_image = common.GetBootableImage(
440 "IMAGES/recovery.img", "recovery.img", OPTIONS.input_tmp,
441 "RECOVERY")
442 else:
Michael Runge2e0d8fc2014-11-13 21:41:08 -0800443 recovery_image = common.GetBootableImage(
444 "IMAGES/recovery.img", "recovery.img", OPTIONS.input_tmp, "RECOVERY")
Tao Baodb45efa2015-10-27 19:25:18 -0700445 if recovery_image:
Dan Willemsen2ee00d52017-03-05 19:51:56 -0800446 if output_zip:
447 recovery_image.AddToZip(output_zip)
448 else:
449 recovery_image.WriteToDir(OPTIONS.input_tmp)
Doug Zongker3c84f562014-07-31 11:06:30 -0700450
Tao Baod42e97e2016-11-30 12:11:57 -0800451 banner("recovery (two-step image)")
452 # The special recovery.img for two-step package use.
453 recovery_two_step_image = common.GetBootableImage(
454 "IMAGES/recovery-two-step.img", "recovery-two-step.img",
455 OPTIONS.input_tmp, "RECOVERY", two_step_image=True)
456 if recovery_two_step_image:
Dan Willemsen2ee00d52017-03-05 19:51:56 -0800457 if output_zip:
458 recovery_two_step_image.AddToZip(output_zip)
459 else:
460 recovery_two_step_image.WriteToDir(OPTIONS.input_tmp)
Tao Baod42e97e2016-11-30 12:11:57 -0800461
Doug Zongkerfc44a512014-08-26 13:10:25 -0700462 banner("system")
David Zeuthend995f4b2016-01-29 16:59:17 -0500463 system_img_path = AddSystem(
464 output_zip, recovery_img=recovery_image, boot_img=boot_image)
Tianjie Xu737afb92016-07-11 11:42:53 -0700465 vendor_img_path = None
Doug Zongkerfc44a512014-08-26 13:10:25 -0700466 if has_vendor:
467 banner("vendor")
Tianjie Xu737afb92016-07-11 11:42:53 -0700468 vendor_img_path = AddVendor(output_zip)
Alex Light4e358ab2016-06-16 14:47:10 -0700469 if has_system_other:
470 banner("system_other")
471 AddSystemOther(output_zip)
Tianjie Xub48589a2016-08-03 19:21:52 -0700472 if not OPTIONS.is_signing:
473 banner("userdata")
474 AddUserdata(output_zip)
475 banner("cache")
476 AddCache(output_zip)
David Zeuthen25328622016-04-08 15:08:03 -0400477 if OPTIONS.info_dict.get("board_bpt_enable", None) == "true":
478 banner("partition-table")
479 AddPartitionTable(output_zip)
David Zeuthen2ce63ed2016-09-15 13:43:54 -0400480 if OPTIONS.info_dict.get("board_avb_enable", None) == "true":
481 banner("vbmeta")
482 boot_contents = boot_image.WriteToTemp()
Bowgo Tsai8ee4a3d2017-03-31 15:21:26 +0800483 AddVBMeta(output_zip, boot_contents.name, system_img_path, vendor_img_path)
Doug Zongker3c84f562014-07-31 11:06:30 -0700484
Wei Wang2e735ca2016-05-10 22:48:13 -0700485 # For devices using A/B update, copy over images from RADIO/ and/or
486 # VENDOR_IMAGES/ to IMAGES/ and make sure we have all the needed
487 # images ready under IMAGES/. All images should have '.img' as extension.
Tianjie Xuaaca4212016-06-28 14:34:03 -0700488 banner("radio")
Tao Baoa0421cd2015-11-16 16:32:27 -0800489 ab_partitions = os.path.join(OPTIONS.input_tmp, "META", "ab_partitions.txt")
490 if os.path.exists(ab_partitions):
491 with open(ab_partitions, 'r') as f:
492 lines = f.readlines()
Tianjie Xucfa86222016-03-07 16:31:19 -0800493 # For devices using A/B update, generate care_map for system and vendor
494 # partitions (if present), then write this file to target_files package.
495 care_map_list = []
Tao Baoa0421cd2015-11-16 16:32:27 -0800496 for line in lines:
Tianjie Xucfa86222016-03-07 16:31:19 -0800497 if line.strip() == "system" and OPTIONS.info_dict.get(
498 "system_verity_block_device", None) is not None:
Tianjie Xu737afb92016-07-11 11:42:53 -0700499 assert os.path.exists(system_img_path)
500 care_map_list += GetCareMap("system", system_img_path)
Tianjie Xucfa86222016-03-07 16:31:19 -0800501 if line.strip() == "vendor" and OPTIONS.info_dict.get(
502 "vendor_verity_block_device", None) is not None:
Tianjie Xu737afb92016-07-11 11:42:53 -0700503 assert os.path.exists(vendor_img_path)
504 care_map_list += GetCareMap("vendor", vendor_img_path)
Tianjie Xucfa86222016-03-07 16:31:19 -0800505
Tao Baoa0421cd2015-11-16 16:32:27 -0800506 img_name = line.strip() + ".img"
Tianjie Xuaaca4212016-06-28 14:34:03 -0700507 prebuilt_path = os.path.join(OPTIONS.input_tmp, "IMAGES", img_name)
508 if os.path.exists(prebuilt_path):
Tao Bao89fbb0f2017-01-10 10:47:58 -0800509 print("%s already exists, no need to overwrite..." % (img_name,))
Tianjie Xuaaca4212016-06-28 14:34:03 -0700510 continue
511
Tao Baoa0421cd2015-11-16 16:32:27 -0800512 img_radio_path = os.path.join(OPTIONS.input_tmp, "RADIO", img_name)
Wei Wang2e735ca2016-05-10 22:48:13 -0700513 img_vendor_dir = os.path.join(
514 OPTIONS.input_tmp, "VENDOR_IMAGES")
Tao Baoa0421cd2015-11-16 16:32:27 -0800515 if os.path.exists(img_radio_path):
Dan Willemsen2ee00d52017-03-05 19:51:56 -0800516 if output_zip:
517 common.ZipWrite(output_zip, img_radio_path,
518 os.path.join("IMAGES", img_name))
519 else:
520 shutil.copy(img_radio_path, prebuilt_path)
Wei Wang2e735ca2016-05-10 22:48:13 -0700521 else:
522 for root, _, files in os.walk(img_vendor_dir):
523 if img_name in files:
Dan Willemsen2ee00d52017-03-05 19:51:56 -0800524 if output_zip:
525 common.ZipWrite(output_zip, os.path.join(root, img_name),
526 os.path.join("IMAGES", img_name))
527 else:
528 shutil.copy(os.path.join(root, img_name), prebuilt_path)
Wei Wang2e735ca2016-05-10 22:48:13 -0700529 break
Tao Baoa0421cd2015-11-16 16:32:27 -0800530
Dan Willemsen2ee00d52017-03-05 19:51:56 -0800531 if output_zip:
532 # Zip spec says: All slashes MUST be forward slashes.
533 img_path = 'IMAGES/' + img_name
534 assert img_path in output_zip.namelist(), "cannot find " + img_name
535 else:
536 img_path = os.path.join(OPTIONS.input_tmp, "IMAGES", img_name)
537 assert os.path.exists(img_path), "cannot find " + img_name
Tao Baoa0421cd2015-11-16 16:32:27 -0800538
Tianjie Xucfa86222016-03-07 16:31:19 -0800539 if care_map_list:
540 file_path = "META/care_map.txt"
Dan Willemsen2ee00d52017-03-05 19:51:56 -0800541 if output_zip:
542 common.ZipWriteStr(output_zip, file_path, '\n'.join(care_map_list))
543 else:
544 with open(os.path.join(OPTIONS.input_tmp, file_path), 'w') as fp:
545 fp.write('\n'.join(care_map_list))
Tianjie Xucfa86222016-03-07 16:31:19 -0800546
Dan Willemsen2ee00d52017-03-05 19:51:56 -0800547 if output_zip:
548 common.ZipClose(output_zip)
Doug Zongker3c84f562014-07-31 11:06:30 -0700549
Doug Zongker3c84f562014-07-31 11:06:30 -0700550def main(argv):
Baligh Uddin59f4ff12015-09-16 21:20:30 -0700551 def option_handler(o, a):
Michael Runge2e0d8fc2014-11-13 21:41:08 -0800552 if o in ("-a", "--add_missing"):
553 OPTIONS.add_missing = True
554 elif o in ("-r", "--rebuild_recovery",):
555 OPTIONS.rebuild_recovery = True
Baligh Uddin59f4ff12015-09-16 21:20:30 -0700556 elif o == "--replace_verity_private_key":
557 OPTIONS.replace_verity_private_key = (True, a)
558 elif o == "--replace_verity_public_key":
559 OPTIONS.replace_verity_public_key = (True, a)
Tianjie Xub48589a2016-08-03 19:21:52 -0700560 elif o == "--is_signing":
561 OPTIONS.is_signing = True
Michael Runge2e0d8fc2014-11-13 21:41:08 -0800562 else:
563 return False
564 return True
565
Dan Albert8b72aef2015-03-23 19:13:21 -0700566 args = common.ParseOptions(
567 argv, __doc__, extra_opts="ar",
Baligh Uddin59f4ff12015-09-16 21:20:30 -0700568 extra_long_opts=["add_missing", "rebuild_recovery",
569 "replace_verity_public_key=",
570 "replace_verity_private_key=",
Tao Bao45810422016-10-17 16:20:12 -0700571 "is_signing"],
Dan Albert8b72aef2015-03-23 19:13:21 -0700572 extra_option_handler=option_handler)
Michael Runge2e0d8fc2014-11-13 21:41:08 -0800573
Doug Zongker3c84f562014-07-31 11:06:30 -0700574
575 if len(args) != 1:
576 common.Usage(__doc__)
577 sys.exit(1)
578
579 AddImagesToTargetFiles(args[0])
Tao Bao89fbb0f2017-01-10 10:47:58 -0800580 print("done.")
Doug Zongker3c84f562014-07-31 11:06:30 -0700581
582if __name__ == '__main__':
583 try:
584 common.CloseInheritedPipes()
585 main(sys.argv[1:])
Dan Albert8b72aef2015-03-23 19:13:21 -0700586 except common.ExternalError as e:
Tao Bao89fbb0f2017-01-10 10:47:58 -0800587 print("\n ERROR: %s\n" % (e,))
Doug Zongker3c84f562014-07-31 11:06:30 -0700588 sys.exit(1)
Doug Zongkerfc44a512014-08-26 13:10:25 -0700589 finally:
590 common.Cleanup()