blob: 521b319ed55a3f341193b60629239b2bf86031a1 [file] [log] [blame]
Ying Wangbd93d422011-10-28 17:02:30 -07001#!/usr/bin/env python
2#
3# Copyright (C) 2011 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"""
Tao Baoc72727a2017-12-07 10:33:00 -080018Builds output_image from the given input_directory, properties_file,
19and writes the image to target_output_directory.
Ying Wangbd93d422011-10-28 17:02:30 -070020
Yifan Hongbbcba1e2018-06-18 16:32:35 -070021If argument generated_prop_file exists, write additional properties to the file.
22
Tao Baoc72727a2017-12-07 10:33:00 -080023Usage: build_image.py input_directory properties_file output_image \\
Yifan Hongbbcba1e2018-06-18 16:32:35 -070024 target_output_directory [generated_prop_file]
Ying Wangbd93d422011-10-28 17:02:30 -070025"""
Tao Baoc72727a2017-12-07 10:33:00 -080026
27from __future__ import print_function
28
Tao Bao32fcdab2018-10-12 10:30:39 -070029import logging
Ying Wangbd93d422011-10-28 17:02:30 -070030import os
Ying Wang69e9b4d2012-11-26 18:10:23 -080031import os.path
Tao Baoc7a6f1e2015-06-23 11:16:05 -070032import re
Geremy Condrafd6f7512013-06-16 17:26:08 -070033import shutil
Tao Baoc72727a2017-12-07 10:33:00 -080034import sys
35
36import common
Tao Bao71197512018-10-11 14:08:45 -070037import verity_utils
Ying Wangbd93d422011-10-28 17:02:30 -070038
Tao Bao32fcdab2018-10-12 10:30:39 -070039logger = logging.getLogger(__name__)
40
Baligh Uddin601ddea2015-06-09 15:48:14 -070041OPTIONS = common.OPTIONS
Tao Bao71197512018-10-11 14:08:45 -070042BLOCK_SIZE = common.BLOCK_SIZE
Yifan Hongbbcba1e2018-06-18 16:32:35 -070043BYTES_IN_MB = 1024 * 1024
Geremy Condrae8e982a2014-05-16 19:14:30 -070044
Tao Baoc72727a2017-12-07 10:33:00 -080045
Tao Baoc6bd70a2018-09-27 16:58:00 -070046class BuildImageError(Exception):
47 """An Exception raised during image building."""
48
49 def __init__(self, message):
50 Exception.__init__(self, message)
51
52
Yifan Hongbbcba1e2018-06-18 16:32:35 -070053def GetDiskUsage(path):
Tao Baoc6bd70a2018-09-27 16:58:00 -070054 """Returns the number of bytes that "path" occupies on host.
Yifan Hongbbcba1e2018-06-18 16:32:35 -070055
56 Args:
Mark Salyzyn780f5952018-10-19 13:44:36 -070057 path: The directory or file to calculate size on.
Tao Baoc6bd70a2018-09-27 16:58:00 -070058
Yifan Hongbbcba1e2018-06-18 16:32:35 -070059 Returns:
Mark Salyzyn780f5952018-10-19 13:44:36 -070060 The number of bytes based on a 1K block_size.
Yifan Hongbbcba1e2018-06-18 16:32:35 -070061 """
Mark Salyzyn780f5952018-10-19 13:44:36 -070062 cmd = ["du", "-k", "-s", path]
Tao Baof3fc62c2018-10-25 12:23:12 -070063 output = common.RunAndCheckOutput(cmd, verbose=False)
Mark Salyzyn780f5952018-10-19 13:44:36 -070064 return int(output.split()[0]) * 1024
65
66
67def GetInodeUsage(path):
68 """Returns the number of inodes that "path" occupies on host.
69
70 Args:
71 path: The directory or file to calculate inode number on.
72
73 Returns:
74 The number of inodes used.
Mark Salyzyn780f5952018-10-19 13:44:36 -070075 """
76 cmd = ["find", path, "-print"]
Tao Baof3fc62c2018-10-25 12:23:12 -070077 output = common.RunAndCheckOutput(cmd, verbose=False)
Hridya Valsarajue8e79582019-01-03 17:19:50 -080078 # TODO(b/122328872) Fix estimation algorithm to not need the multiplier.
79 return output.count('\n') * 2
Mark Salyzyn780f5952018-10-19 13:44:36 -070080
81
Mark Salyzyn6541d0a2019-01-10 14:30:51 -080082def GetFilesystemCharacteristics(image_path, sparse_image=True):
83 """Returns various filesystem characteristics of "image_path".
Mark Salyzyn780f5952018-10-19 13:44:36 -070084
85 Args:
Mark Salyzyn6541d0a2019-01-10 14:30:51 -080086 image_path: The file to analyze.
87 sparse_image: Image is sparse
Mark Salyzyn780f5952018-10-19 13:44:36 -070088
89 Returns:
90 The characteristics dictionary.
Mark Salyzyn780f5952018-10-19 13:44:36 -070091 """
Mark Salyzyn6541d0a2019-01-10 14:30:51 -080092 unsparse_image_path = image_path
93 if sparse_image:
94 unsparse_image_path = UnsparseImage(image_path, replace=False)
Mark Salyzyn780f5952018-10-19 13:44:36 -070095
96 cmd = ["tune2fs", "-l", unsparse_image_path]
97 try:
98 output = common.RunAndCheckOutput(cmd, verbose=False)
Tao Baof3fc62c2018-10-25 12:23:12 -070099 finally:
Mark Salyzyn6541d0a2019-01-10 14:30:51 -0800100 if sparse_image:
101 os.remove(unsparse_image_path)
Tao Baof3fc62c2018-10-25 12:23:12 -0700102 fs_dict = {}
Mark Salyzyn780f5952018-10-19 13:44:36 -0700103 for line in output.splitlines():
104 fields = line.split(":")
105 if len(fields) == 2:
106 fs_dict[fields[0].strip()] = fields[1].strip()
107 return fs_dict
Yifan Hongbbcba1e2018-06-18 16:32:35 -0700108
109
Geremy Condra6e8f53c2013-12-05 17:09:18 -0800110def UnsparseImage(sparse_image_path, replace=True):
Geremy Condrafd6f7512013-06-16 17:26:08 -0700111 img_dir = os.path.dirname(sparse_image_path)
112 unsparse_image_path = "unsparse_" + os.path.basename(sparse_image_path)
113 unsparse_image_path = os.path.join(img_dir, unsparse_image_path)
114 if os.path.exists(unsparse_image_path):
Geremy Condra6e8f53c2013-12-05 17:09:18 -0800115 if replace:
116 os.unlink(unsparse_image_path)
117 else:
Tao Baoc6bd70a2018-09-27 16:58:00 -0700118 return unsparse_image_path
Geremy Condrafd6f7512013-06-16 17:26:08 -0700119 inflate_command = ["simg2img", sparse_image_path, unsparse_image_path]
Tao Bao986ee862018-10-04 15:46:16 -0700120 try:
121 common.RunAndCheckOutput(inflate_command)
122 except:
Geremy Condrafd6f7512013-06-16 17:26:08 -0700123 os.remove(unsparse_image_path)
Tao Bao986ee862018-10-04 15:46:16 -0700124 raise
Tao Baoc6bd70a2018-09-27 16:58:00 -0700125 return unsparse_image_path
Geremy Condrafd6f7512013-06-16 17:26:08 -0700126
Tao Baoc72727a2017-12-07 10:33:00 -0800127
Mohamad Ayyashf8765552016-03-02 21:07:23 -0800128def ConvertBlockMapToBaseFs(block_map_file):
Tao Bao1c830bf2017-12-25 10:43:47 -0800129 base_fs_file = common.MakeTempFile(prefix="script_gen_", suffix=".base_fs")
Mohamad Ayyashf8765552016-03-02 21:07:23 -0800130 convert_command = ["blk_alloc_to_base_fs", block_map_file, base_fs_file]
Tao Bao986ee862018-10-04 15:46:16 -0700131 common.RunAndCheckOutput(convert_command)
Tao Baoc6bd70a2018-09-27 16:58:00 -0700132 return base_fs_file
Mohamad Ayyashf8765552016-03-02 21:07:23 -0800133
Tao Baod4349f22017-12-07 23:01:25 -0800134
Tao Baoc2606eb2018-07-20 14:44:46 -0700135def SetUpInDirAndFsConfig(origin_in, prop_dict):
136 """Returns the in_dir and fs_config that should be used for image building.
137
Tom Cherryd14b8952018-08-09 14:26:00 -0700138 When building system.img for all targets, it creates and returns a staged dir
139 that combines the contents of /system (i.e. in the given in_dir) and root.
Tao Baoc2606eb2018-07-20 14:44:46 -0700140
141 Args:
142 origin_in: Path to the input directory.
143 prop_dict: A property dict that contains info like partition size. Values
144 may be updated.
145
146 Returns:
147 A tuple of in_dir and fs_config that should be used to build the image.
148 """
149 fs_config = prop_dict.get("fs_config")
Tom Cherryd14b8952018-08-09 14:26:00 -0700150
151 if prop_dict["mount_point"] == "system_other":
152 prop_dict["mount_point"] = "system"
153 return origin_in, fs_config
154
155 if prop_dict["mount_point"] != "system":
Tao Baoc2606eb2018-07-20 14:44:46 -0700156 return origin_in, fs_config
157
Mark Salyzyn780f5952018-10-19 13:44:36 -0700158 if "first_pass" in prop_dict:
159 prop_dict["mount_point"] = "/"
160 return prop_dict["first_pass"]
161
Tao Baoc2606eb2018-07-20 14:44:46 -0700162 # Construct a staging directory of the root file system.
163 in_dir = common.MakeTempDir()
164 root_dir = prop_dict.get("root_dir")
165 if root_dir:
166 shutil.rmtree(in_dir)
167 shutil.copytree(root_dir, in_dir, symlinks=True)
168 in_dir_system = os.path.join(in_dir, "system")
169 shutil.rmtree(in_dir_system, ignore_errors=True)
170 shutil.copytree(origin_in, in_dir_system, symlinks=True)
171
172 # Change the mount point to "/".
173 prop_dict["mount_point"] = "/"
174 if fs_config:
175 # We need to merge the fs_config files of system and root.
176 merged_fs_config = common.MakeTempFile(
177 prefix="merged_fs_config", suffix=".txt")
178 with open(merged_fs_config, "w") as fw:
179 if "root_fs_config" in prop_dict:
180 with open(prop_dict["root_fs_config"]) as fr:
181 fw.writelines(fr.readlines())
182 with open(fs_config) as fr:
183 fw.writelines(fr.readlines())
184 fs_config = merged_fs_config
Mark Salyzyn780f5952018-10-19 13:44:36 -0700185 prop_dict["first_pass"] = (in_dir, fs_config)
Tao Baoc2606eb2018-07-20 14:44:46 -0700186 return in_dir, fs_config
187
188
Tao Baod4349f22017-12-07 23:01:25 -0800189def CheckHeadroom(ext4fs_output, prop_dict):
190 """Checks if there's enough headroom space available.
191
192 Headroom is the reserved space on system image (via PRODUCT_SYSTEM_HEADROOM),
193 which is useful for devices with low disk space that have system image
194 variation between builds. The 'partition_headroom' in prop_dict is the size
195 in bytes, while the numbers in 'ext4fs_output' are for 4K-blocks.
196
197 Args:
198 ext4fs_output: The output string from mke2fs command.
199 prop_dict: The property dict.
200
Tao Baod8a953d2018-01-02 21:19:27 -0800201 Raises:
202 AssertionError: On invalid input.
Tao Baoc6bd70a2018-09-27 16:58:00 -0700203 BuildImageError: On check failure.
Tao Baod4349f22017-12-07 23:01:25 -0800204 """
Tao Baod8a953d2018-01-02 21:19:27 -0800205 assert ext4fs_output is not None
206 assert prop_dict.get('fs_type', '').startswith('ext4')
207 assert 'partition_headroom' in prop_dict
208 assert 'mount_point' in prop_dict
209
Tao Baod4349f22017-12-07 23:01:25 -0800210 ext4fs_stats = re.compile(
211 r'Created filesystem with .* (?P<used_blocks>[0-9]+)/'
212 r'(?P<total_blocks>[0-9]+) blocks')
Tao Baoc72727a2017-12-07 10:33:00 -0800213 last_line = ext4fs_output.strip().split('\n')[-1]
214 m = ext4fs_stats.match(last_line)
Tao Baod4349f22017-12-07 23:01:25 -0800215 used_blocks = int(m.groupdict().get('used_blocks'))
216 total_blocks = int(m.groupdict().get('total_blocks'))
Mark Salyzyn780f5952018-10-19 13:44:36 -0700217 headroom_blocks = int(prop_dict['partition_headroom']) // BLOCK_SIZE
Tao Baod4349f22017-12-07 23:01:25 -0800218 adjusted_blocks = total_blocks - headroom_blocks
219 if used_blocks > adjusted_blocks:
Tao Baod8a953d2018-01-02 21:19:27 -0800220 mount_point = prop_dict["mount_point"]
Tao Baoc6bd70a2018-09-27 16:58:00 -0700221 raise BuildImageError(
222 "Error: Not enough room on {} (total: {} blocks, used: {} blocks, "
223 "headroom: {} blocks, available: {} blocks)".format(
224 mount_point, total_blocks, used_blocks, headroom_blocks,
225 adjusted_blocks))
Tao Baod4349f22017-12-07 23:01:25 -0800226
227
Mark Salyzyn3cd24602018-11-07 07:40:31 -0800228def BuildImageMkfs(in_dir, prop_dict, out_file, target_out, fs_config):
229 """Builds a pure image for the files under in_dir and writes it to out_file.
Tao Baoc2606eb2018-07-20 14:44:46 -0700230
Ying Wangbd93d422011-10-28 17:02:30 -0700231 Args:
Tao Baoc2606eb2018-07-20 14:44:46 -0700232 in_dir: Path to input directory.
233 prop_dict: A property dict that contains info like partition size. Values
234 will be updated with computed values.
235 out_file: The output image file.
236 target_out: Path to the TARGET_OUT directory as in Makefile. It actually
237 points to the /system directory under PRODUCT_OUT. fs_config (the one
238 under system/core/libcutils) reads device specific FS config files from
239 there.
Mark Salyzyn3cd24602018-11-07 07:40:31 -0800240 fs_config: The fs_config file that drives the prototype
Ying Wangbd93d422011-10-28 17:02:30 -0700241
Tao Baoc6bd70a2018-09-27 16:58:00 -0700242 Raises:
243 BuildImageError: On build image failures.
Ying Wangbd93d422011-10-28 17:02:30 -0700244 """
245 build_command = []
246 fs_type = prop_dict.get("fs_type", "")
Tao Baoc72727a2017-12-07 10:33:00 -0800247 run_e2fsck = False
Geremy Condrafd6f7512013-06-16 17:26:08 -0700248
Ying Wangbd93d422011-10-28 17:02:30 -0700249 if fs_type.startswith("ext"):
Adrien Schildknecht9a072cc2016-11-18 17:06:29 -0800250 build_command = [prop_dict["ext_mkuserimg"]]
Ying Wangbd93d422011-10-28 17:02:30 -0700251 if "extfs_sparse_flag" in prop_dict:
252 build_command.append(prop_dict["extfs_sparse_flag"])
Tao Baoc72727a2017-12-07 10:33:00 -0800253 run_e2fsck = True
Ying Wangbd93d422011-10-28 17:02:30 -0700254 build_command.extend([in_dir, out_file, fs_type,
255 prop_dict["mount_point"]])
Tao Bao35f4ebc2018-09-27 15:31:11 -0700256 build_command.append(prop_dict["image_size"])
Ying Wangf3b86352014-11-18 18:03:13 -0800257 if "journal_size" in prop_dict:
258 build_command.extend(["-j", prop_dict["journal_size"]])
Doug Zongker850b8072013-12-05 15:54:55 -0800259 if "timestamp" in prop_dict:
260 build_command.extend(["-T", str(prop_dict["timestamp"])])
Ying Wanga2292c92015-03-24 19:07:40 -0700261 if fs_config:
Doug Zongker82822822014-06-16 09:10:55 -0700262 build_command.extend(["-C", fs_config])
Thierry Strudel74a81e62015-07-09 09:54:55 -0700263 if target_out:
264 build_command.extend(["-D", target_out])
Ying Wanga2292c92015-03-24 19:07:40 -0700265 if "block_list" in prop_dict:
266 build_command.extend(["-B", prop_dict["block_list"]])
Mohamad Ayyashf8765552016-03-02 21:07:23 -0800267 if "base_fs_file" in prop_dict:
268 base_fs_file = ConvertBlockMapToBaseFs(prop_dict["base_fs_file"])
Mohamad Ayyashf8765552016-03-02 21:07:23 -0800269 build_command.extend(["-d", base_fs_file])
Christoffer Dall8ed01f32014-12-17 21:34:12 +0100270 build_command.extend(["-L", prop_dict["mount_point"]])
Patrick Tjina1900842016-10-20 10:58:12 -0700271 if "extfs_inode_count" in prop_dict:
272 build_command.extend(["-i", prop_dict["extfs_inode_count"]])
Patrick Tjin3f5f9932018-03-23 11:36:43 -0700273 if "extfs_rsv_pct" in prop_dict:
274 build_command.extend(["-M", prop_dict["extfs_rsv_pct"]])
Connor O'Brien20f08c32017-01-05 16:48:14 -0800275 if "flash_erase_block_size" in prop_dict:
276 build_command.extend(["-e", prop_dict["flash_erase_block_size"]])
277 if "flash_logical_block_size" in prop_dict:
278 build_command.extend(["-o", prop_dict["flash_logical_block_size"]])
Tao Baod86e3112017-09-22 15:45:33 -0700279 # Specify UUID and hash_seed if using mke2fs.
Tianjie Xu57332222018-08-15 16:16:21 -0700280 if prop_dict["ext_mkuserimg"] == "mkuserimg_mke2fs":
Tao Baod86e3112017-09-22 15:45:33 -0700281 if "uuid" in prop_dict:
282 build_command.extend(["-U", prop_dict["uuid"]])
283 if "hash_seed" in prop_dict:
284 build_command.extend(["-S", prop_dict["hash_seed"]])
Jin Qianfde9f792018-01-22 13:15:46 -0800285 if "ext4_share_dup_blocks" in prop_dict:
286 build_command.append("-c")
Mark Salyzync777eaa2019-01-08 10:08:04 -0800287 build_command.extend(["--inode_size", "256"])
Ying Wanga2292c92015-03-24 19:07:40 -0700288 if "selinux_fc" in prop_dict:
Kenny Rootf32dc712012-04-08 10:42:34 -0700289 build_command.append(prop_dict["selinux_fc"])
Mohamad Ayyashb97746e2015-03-03 12:30:37 -0800290 elif fs_type.startswith("squash"):
291 build_command = ["mksquashfsimage.sh"]
292 build_command.extend([in_dir, out_file])
Todd Poynorb2a555e2015-12-15 18:00:14 -0800293 if "squashfs_sparse_flag" in prop_dict:
294 build_command.extend([prop_dict["squashfs_sparse_flag"]])
Mohamad Ayyashb97746e2015-03-03 12:30:37 -0800295 build_command.extend(["-m", prop_dict["mount_point"]])
Thierry Strudel74a81e62015-07-09 09:54:55 -0700296 if target_out:
297 build_command.extend(["-d", target_out])
Mohamad Ayyash88378822016-04-07 22:10:51 -0700298 if fs_config:
299 build_command.extend(["-C", fs_config])
Ying Wanga2292c92015-03-24 19:07:40 -0700300 if "selinux_fc" in prop_dict:
Mohamad Ayyashb97746e2015-03-03 12:30:37 -0800301 build_command.extend(["-c", prop_dict["selinux_fc"]])
Mohamad Ayyashc3484f72016-06-13 09:46:58 -0700302 if "block_list" in prop_dict:
303 build_command.extend(["-B", prop_dict["block_list"]])
Ng Zhi An9446c1d2018-01-19 15:51:46 -0800304 if "squashfs_block_size" in prop_dict:
305 build_command.extend(["-b", prop_dict["squashfs_block_size"]])
Simon Wilsonf86e7ee2015-06-17 12:35:15 -0700306 if "squashfs_compressor" in prop_dict:
307 build_command.extend(["-z", prop_dict["squashfs_compressor"]])
308 if "squashfs_compressor_opt" in prop_dict:
309 build_command.extend(["-zo", prop_dict["squashfs_compressor_opt"]])
Tao Baoc72727a2017-12-07 10:33:00 -0800310 if prop_dict.get("squashfs_disable_4k_align") == "true":
Mohamad Ayyash1b6d3482016-06-15 15:53:07 -0700311 build_command.extend(["-a"])
JP Abgrall5bfed5a2014-06-16 14:17:40 -0700312 elif fs_type.startswith("f2fs"):
313 build_command = ["mkf2fsuserimg.sh"]
Tao Bao35f4ebc2018-09-27 15:31:11 -0700314 build_command.extend([out_file, prop_dict["image_size"]])
Jaegeuk Kim2ea1eba2017-11-28 19:21:28 -0800315 if fs_config:
316 build_command.extend(["-C", fs_config])
317 build_command.extend(["-f", in_dir])
318 if target_out:
319 build_command.extend(["-D", target_out])
320 if "selinux_fc" in prop_dict:
321 build_command.extend(["-s", prop_dict["selinux_fc"]])
322 build_command.extend(["-t", prop_dict["mount_point"]])
323 if "timestamp" in prop_dict:
324 build_command.extend(["-T", str(prop_dict["timestamp"])])
325 build_command.extend(["-L", prop_dict["mount_point"]])
Ying Wangbd93d422011-10-28 17:02:30 -0700326 else:
Tao Baoc6bd70a2018-09-27 16:58:00 -0700327 raise BuildImageError(
328 "Error: unknown filesystem type: {}".format(fs_type))
Ying Wangbd93d422011-10-28 17:02:30 -0700329
Tao Bao986ee862018-10-04 15:46:16 -0700330 try:
331 mkfs_output = common.RunAndCheckOutput(build_command)
332 except:
Tao Baoc6bd70a2018-09-27 16:58:00 -0700333 try:
334 du = GetDiskUsage(in_dir)
335 du_str = "{} bytes ({} MB)".format(du, du // BYTES_IN_MB)
Tao Bao986ee862018-10-04 15:46:16 -0700336 # Suppress any errors from GetDiskUsage() to avoid hiding the real errors
337 # from common.RunAndCheckOutput().
Tao Bao32fcdab2018-10-12 10:30:39 -0700338 except Exception: # pylint: disable=broad-except
339 logger.exception("Failed to compute disk usage with du")
Tao Baoc6bd70a2018-09-27 16:58:00 -0700340 du_str = "unknown"
Tao Bao4251fe92018-07-23 13:05:00 -0700341 print(
Mark Salyzyn3cd24602018-11-07 07:40:31 -0800342 "Out of space? Out of inodes? The tree size of {} is {}, "
343 "with reserved space of {} bytes ({} MB).".format(
Tao Baoc2606eb2018-07-20 14:44:46 -0700344 in_dir, du_str,
Tao Bao4251fe92018-07-23 13:05:00 -0700345 int(prop_dict.get("partition_reserved_size", 0)),
346 int(prop_dict.get("partition_reserved_size", 0)) // BYTES_IN_MB))
Tao Bao35f4ebc2018-09-27 15:31:11 -0700347 print(
Mark Salyzyn780f5952018-10-19 13:44:36 -0700348 "The max image size for filesystem files is {} bytes ({} MB), out of a "
Tao Bao35f4ebc2018-09-27 15:31:11 -0700349 "total partition size of {} bytes ({} MB).".format(
350 int(prop_dict["image_size"]),
351 int(prop_dict["image_size"]) // BYTES_IN_MB,
352 int(prop_dict["partition_size"]),
353 int(prop_dict["partition_size"]) // BYTES_IN_MB))
Tao Bao986ee862018-10-04 15:46:16 -0700354 raise
Ying Wang69e9b4d2012-11-26 18:10:23 -0800355
Mark Salyzyn3cd24602018-11-07 07:40:31 -0800356 if run_e2fsck and prop_dict.get("skip_fsck") != "true":
357 unsparse_image = UnsparseImage(out_file, replace=False)
358
359 # Run e2fsck on the inflated image file
360 e2fsck_command = ["e2fsck", "-f", "-n", unsparse_image]
361 try:
362 common.RunAndCheckOutput(e2fsck_command)
363 finally:
364 os.remove(unsparse_image)
365
366 return mkfs_output
367
368
369def BuildImage(in_dir, prop_dict, out_file, target_out=None):
370 """Builds an image for the files under in_dir and writes it to out_file.
371
372 Args:
373 in_dir: Path to input directory.
374 prop_dict: A property dict that contains info like partition size. Values
375 will be updated with computed values.
376 out_file: The output image file.
377 target_out: Path to the TARGET_OUT directory as in Makefile. It actually
378 points to the /system directory under PRODUCT_OUT. fs_config (the one
379 under system/core/libcutils) reads device specific FS config files from
380 there.
381
382 Raises:
383 BuildImageError: On build image failures.
384 """
385 in_dir, fs_config = SetUpInDirAndFsConfig(in_dir, prop_dict)
386
387 build_command = []
388 fs_type = prop_dict.get("fs_type", "")
389
390 fs_spans_partition = True
391 if fs_type.startswith("squash"):
392 fs_spans_partition = False
393
394 # Get a builder for creating an image that's to be verified by Verified Boot,
395 # or None if not applicable.
396 verity_image_builder = verity_utils.CreateVerityImageBuilder(prop_dict)
397
398 if (prop_dict.get("use_dynamic_partition_size") == "true" and
399 "partition_size" not in prop_dict):
400 # If partition_size is not defined, use output of `du' + reserved_size.
401 size = GetDiskUsage(in_dir)
402 logger.info(
403 "The tree size of %s is %d MB.", in_dir, size // BYTES_IN_MB)
404 # If not specified, give us 16MB margin for GetDiskUsage error ...
405 reserved_size = int(prop_dict.get("partition_reserved_size", BYTES_IN_MB * 16))
406 partition_headroom = int(prop_dict.get("partition_headroom", 0))
407 if fs_type.startswith("ext4") and partition_headroom > reserved_size:
408 reserved_size = partition_headroom
409 size += reserved_size
410 # Round this up to a multiple of 4K so that avbtool works
411 size = common.RoundUpTo4K(size)
412 if fs_type.startswith("ext"):
413 prop_dict["partition_size"] = str(size)
414 prop_dict["image_size"] = str(size)
415 if "extfs_inode_count" not in prop_dict:
416 prop_dict["extfs_inode_count"] = str(GetInodeUsage(in_dir))
417 logger.info(
418 "First Pass based on estimates of %d MB and %s inodes.",
419 size // BYTES_IN_MB, prop_dict["extfs_inode_count"])
420 BuildImageMkfs(in_dir, prop_dict, out_file, target_out, fs_config)
Mark Salyzyn6541d0a2019-01-10 14:30:51 -0800421 sparse_image = False
422 if "extfs_sparse_flag" in prop_dict:
423 sparse_image = True
424 fs_dict = GetFilesystemCharacteristics(out_file, sparse_image)
Mark Salyzyn3cd24602018-11-07 07:40:31 -0800425 os.remove(out_file)
426 block_size = int(fs_dict.get("Block size", "4096"))
427 free_size = int(fs_dict.get("Free blocks", "0")) * block_size
428 reserved_size = int(prop_dict.get("partition_reserved_size", 0))
429 partition_headroom = int(fs_dict.get("partition_headroom", 0))
430 if fs_type.startswith("ext4") and partition_headroom > reserved_size:
431 reserved_size = partition_headroom
432 if free_size <= reserved_size:
433 logger.info(
434 "Not worth reducing image %d <= %d.", free_size, reserved_size)
435 else:
436 size -= free_size
437 size += reserved_size
Mark Salyzyn60a716f2019-01-10 08:36:34 -0800438 if reserved_size == 0:
439 # add .2% margin
440 size = size * 1002 // 1000
441 # Use a minimum size, otherwise we will fail to calculate an AVB footer
442 # or fail to construct an ext4 image.
443 size = max(size, 256 * 1024)
Mark Salyzyn3cd24602018-11-07 07:40:31 -0800444 if block_size <= 4096:
445 size = common.RoundUpTo4K(size)
446 else:
447 size = ((size + block_size - 1) // block_size) * block_size
448 extfs_inode_count = prop_dict["extfs_inode_count"]
449 inodes = int(fs_dict.get("Inode count", extfs_inode_count))
450 inodes -= int(fs_dict.get("Free inodes", "0"))
Mark Salyzyn60a716f2019-01-10 08:36:34 -0800451 # add .2% margin
452 inodes = inodes * 1002 // 1000
Mark Salyzyn3cd24602018-11-07 07:40:31 -0800453 prop_dict["extfs_inode_count"] = str(inodes)
454 prop_dict["partition_size"] = str(size)
455 logger.info(
456 "Allocating %d Inodes for %s.", inodes, out_file)
457 if verity_image_builder:
458 size = verity_image_builder.CalculateDynamicPartitionSize(size)
459 prop_dict["partition_size"] = str(size)
460 logger.info(
461 "Allocating %d MB for %s.", size // BYTES_IN_MB, out_file)
462
463 prop_dict["image_size"] = prop_dict["partition_size"]
464
465 # Adjust the image size to make room for the hashes if this is to be verified.
466 if verity_image_builder:
467 max_image_size = verity_image_builder.CalculateMaxImageSize()
468 prop_dict["image_size"] = str(max_image_size)
469
470 mkfs_output = BuildImageMkfs(in_dir, prop_dict, out_file, target_out, fs_config)
471
Tao Baod4349f22017-12-07 23:01:25 -0800472 # Check if there's enough headroom space available for ext4 image.
Tao Bao79d52f82017-12-07 14:07:44 -0800473 if "partition_headroom" in prop_dict and fs_type.startswith("ext4"):
Tao Baoc6bd70a2018-09-27 16:58:00 -0700474 CheckHeadroom(mkfs_output, prop_dict)
Tao Baoc7a6f1e2015-06-23 11:16:05 -0700475
Tao Bao7549e5e2018-10-03 14:23:59 -0700476 if not fs_spans_partition and verity_image_builder:
477 verity_image_builder.PadSparseImage(out_file)
Mohamad Ayyashdd063522015-03-24 12:42:03 -0700478
Tao Baoc72727a2017-12-07 10:33:00 -0800479 # Create the verified image if this is to be verified.
Tao Bao7549e5e2018-10-03 14:23:59 -0700480 if verity_image_builder:
481 verity_image_builder.Build(out_file)
David Zeuthen4014a9d2016-09-30 17:29:22 -0400482
Ying Wangbd93d422011-10-28 17:02:30 -0700483
484def ImagePropFromGlobalDict(glob_dict, mount_point):
485 """Build an image property dictionary from the global dictionary.
486
487 Args:
488 glob_dict: the global dictionary from the build system.
489 mount_point: such as "system", "data" etc.
490 """
Doug Zongker1ad7ade2013-12-06 11:53:27 -0800491 d = {}
Tao Bao052ae352015-09-28 13:44:13 -0700492
Tao Bao822f5842015-09-30 16:01:14 -0700493 if "build.prop" in glob_dict:
494 bp = glob_dict["build.prop"]
495 if "ro.build.date.utc" in bp:
496 d["timestamp"] = bp["ro.build.date.utc"]
Ying Wang9f8e8db2011-11-04 11:37:01 -0700497
498 def copy_prop(src_p, dest_p):
Patrick Tjin3f5f9932018-03-23 11:36:43 -0700499 """Copy a property from the global dictionary.
500
501 Args:
502 src_p: The source property in the global dictionary.
503 dest_p: The destination property.
504 Returns:
505 True if property was found and copied, False otherwise.
506 """
Ying Wang9f8e8db2011-11-04 11:37:01 -0700507 if src_p in glob_dict:
508 d[dest_p] = str(glob_dict[src_p])
Patrick Tjin3f5f9932018-03-23 11:36:43 -0700509 return True
510 return False
Ying Wang9f8e8db2011-11-04 11:37:01 -0700511
Ying Wangbd93d422011-10-28 17:02:30 -0700512 common_props = (
Ying Wangbd93d422011-10-28 17:02:30 -0700513 "extfs_sparse_flag",
Todd Poynorb2a555e2015-12-15 18:00:14 -0800514 "squashfs_sparse_flag",
Kenny Rootf32dc712012-04-08 10:42:34 -0700515 "selinux_fc",
Ying Wang6a42a252013-02-27 13:54:02 -0800516 "skip_fsck",
Adrien Schildknecht9a072cc2016-11-18 17:06:29 -0800517 "ext_mkuserimg",
Geremy Condrafd6f7512013-06-16 17:26:08 -0700518 "verity",
Geremy Condrafd6f7512013-06-16 17:26:08 -0700519 "verity_key",
Sami Tolvanenf99b5312015-05-20 07:30:57 +0100520 "verity_signer_cmd",
David Zeuthen4014a9d2016-09-30 17:29:22 -0400521 "verity_fec",
Bowgo Tsai6ceeb1a2017-10-11 16:21:48 +0800522 "verity_disable",
Bowgo Tsai3e599ea2017-05-26 18:30:04 +0800523 "avb_enable",
Tao Bao2b6dfd62017-09-27 17:17:43 -0700524 "avb_avbtool",
525 "avb_salt",
Yifan Hong2dae5722018-07-31 12:47:27 -0700526 "use_dynamic_partition_size",
Tao Bao2b6dfd62017-09-27 17:17:43 -0700527 )
Ying Wangbd93d422011-10-28 17:02:30 -0700528 for p in common_props:
Ying Wang9f8e8db2011-11-04 11:37:01 -0700529 copy_prop(p, p)
Ying Wangbd93d422011-10-28 17:02:30 -0700530
531 d["mount_point"] = mount_point
532 if mount_point == "system":
Bowgo Tsai3e599ea2017-05-26 18:30:04 +0800533 copy_prop("avb_system_hashtree_enable", "avb_hashtree_enable")
534 copy_prop("avb_system_add_hashtree_footer_args",
535 "avb_add_hashtree_footer_args")
536 copy_prop("avb_system_key_path", "avb_key_path")
537 copy_prop("avb_system_algorithm", "avb_algorithm")
Ying Wang9f8e8db2011-11-04 11:37:01 -0700538 copy_prop("fs_type", "fs_type")
Julius D'souza001c6762017-05-03 13:43:27 -0700539 # Copy the generic system fs type first, override with specific one if
Dan Albert8b72aef2015-03-23 19:13:21 -0700540 # available.
Mohamad Ayyashb97746e2015-03-03 12:30:37 -0800541 copy_prop("system_fs_type", "fs_type")
Julius D'souza001c6762017-05-03 13:43:27 -0700542 copy_prop("system_headroom", "partition_headroom")
Ying Wang9f8e8db2011-11-04 11:37:01 -0700543 copy_prop("system_size", "partition_size")
Tao Bao332a96b2018-03-31 10:27:35 -0700544 if not copy_prop("system_journal_size", "journal_size"):
545 d["journal_size"] = "0"
Daniel Rosenbergf4eabc32014-07-10 15:42:38 -0700546 copy_prop("system_verity_block_device", "verity_block_device")
Tao Baof3282b42015-04-01 11:21:55 -0700547 copy_prop("system_root_image", "system_root_image")
Tao Bao8bfd3c72018-07-20 15:20:28 -0700548 copy_prop("root_dir", "root_dir")
549 copy_prop("root_fs_config", "root_fs_config")
Jin Qianfde9f792018-01-22 13:15:46 -0800550 copy_prop("ext4_share_dup_blocks", "ext4_share_dup_blocks")
Simon Wilsonf86e7ee2015-06-17 12:35:15 -0700551 copy_prop("system_squashfs_compressor", "squashfs_compressor")
552 copy_prop("system_squashfs_compressor_opt", "squashfs_compressor_opt")
Mohamad Ayyashdfec8152016-05-24 12:59:30 -0700553 copy_prop("system_squashfs_block_size", "squashfs_block_size")
Mohamad Ayyash1b6d3482016-06-15 15:53:07 -0700554 copy_prop("system_squashfs_disable_4k_align", "squashfs_disable_4k_align")
Mohamad Ayyashf8765552016-03-02 21:07:23 -0800555 copy_prop("system_base_fs_file", "base_fs_file")
Patrick Tjina1900842016-10-20 10:58:12 -0700556 copy_prop("system_extfs_inode_count", "extfs_inode_count")
Patrick Tjin3f5f9932018-03-23 11:36:43 -0700557 if not copy_prop("system_extfs_rsv_pct", "extfs_rsv_pct"):
558 d["extfs_rsv_pct"] = "0"
Yifan Hongbbcba1e2018-06-18 16:32:35 -0700559 copy_prop("system_reserved_size", "partition_reserved_size")
Alex Light4e358ab2016-06-16 14:47:10 -0700560 elif mount_point == "system_other":
Tao Baoc72727a2017-12-07 10:33:00 -0800561 # We inherit the selinux policies of /system since we contain some of its
562 # files.
Bowgo Tsai3e599ea2017-05-26 18:30:04 +0800563 copy_prop("avb_system_hashtree_enable", "avb_hashtree_enable")
564 copy_prop("avb_system_add_hashtree_footer_args",
565 "avb_add_hashtree_footer_args")
566 copy_prop("avb_system_key_path", "avb_key_path")
567 copy_prop("avb_system_algorithm", "avb_algorithm")
Alex Light4e358ab2016-06-16 14:47:10 -0700568 copy_prop("fs_type", "fs_type")
569 copy_prop("system_fs_type", "fs_type")
570 copy_prop("system_size", "partition_size")
Tao Bao332a96b2018-03-31 10:27:35 -0700571 if not copy_prop("system_journal_size", "journal_size"):
572 d["journal_size"] = "0"
Alex Light4e358ab2016-06-16 14:47:10 -0700573 copy_prop("system_verity_block_device", "verity_block_device")
Mark Salyzynf0cef8d2018-10-29 10:55:06 -0700574 copy_prop("ext4_share_dup_blocks", "ext4_share_dup_blocks")
Alex Light4e358ab2016-06-16 14:47:10 -0700575 copy_prop("system_squashfs_compressor", "squashfs_compressor")
576 copy_prop("system_squashfs_compressor_opt", "squashfs_compressor_opt")
577 copy_prop("system_squashfs_block_size", "squashfs_block_size")
578 copy_prop("system_base_fs_file", "base_fs_file")
Patrick Tjina1900842016-10-20 10:58:12 -0700579 copy_prop("system_extfs_inode_count", "extfs_inode_count")
Patrick Tjin3f5f9932018-03-23 11:36:43 -0700580 if not copy_prop("system_extfs_rsv_pct", "extfs_rsv_pct"):
581 d["extfs_rsv_pct"] = "0"
Yifan Hongbbcba1e2018-06-18 16:32:35 -0700582 copy_prop("system_reserved_size", "partition_reserved_size")
Ying Wangbd93d422011-10-28 17:02:30 -0700583 elif mount_point == "data":
JP Abgrall5bfed5a2014-06-16 14:17:40 -0700584 # Copy the generic fs type first, override with specific one if available.
Ying Wang9f8e8db2011-11-04 11:37:01 -0700585 copy_prop("fs_type", "fs_type")
JP Abgrall5bfed5a2014-06-16 14:17:40 -0700586 copy_prop("userdata_fs_type", "fs_type")
Ying Wang9f8e8db2011-11-04 11:37:01 -0700587 copy_prop("userdata_size", "partition_size")
Tao Baoc72727a2017-12-07 10:33:00 -0800588 copy_prop("flash_logical_block_size", "flash_logical_block_size")
Connor O'Brien20f08c32017-01-05 16:48:14 -0800589 copy_prop("flash_erase_block_size", "flash_erase_block_size")
Ying Wang9f8e8db2011-11-04 11:37:01 -0700590 elif mount_point == "cache":
591 copy_prop("cache_fs_type", "fs_type")
592 copy_prop("cache_size", "partition_size")
Ying Wanga0febe52013-03-20 11:02:05 -0700593 elif mount_point == "vendor":
Bowgo Tsai3e599ea2017-05-26 18:30:04 +0800594 copy_prop("avb_vendor_hashtree_enable", "avb_hashtree_enable")
595 copy_prop("avb_vendor_add_hashtree_footer_args",
596 "avb_add_hashtree_footer_args")
597 copy_prop("avb_vendor_key_path", "avb_key_path")
598 copy_prop("avb_vendor_algorithm", "avb_algorithm")
Ying Wanga0febe52013-03-20 11:02:05 -0700599 copy_prop("vendor_fs_type", "fs_type")
600 copy_prop("vendor_size", "partition_size")
Tao Bao332a96b2018-03-31 10:27:35 -0700601 if not copy_prop("vendor_journal_size", "journal_size"):
602 d["journal_size"] = "0"
Daniel Rosenbergf4eabc32014-07-10 15:42:38 -0700603 copy_prop("vendor_verity_block_device", "verity_block_device")
Jin Qianfde9f792018-01-22 13:15:46 -0800604 copy_prop("ext4_share_dup_blocks", "ext4_share_dup_blocks")
Patrick Tjine11aa502016-02-09 15:40:38 -0800605 copy_prop("vendor_squashfs_compressor", "squashfs_compressor")
606 copy_prop("vendor_squashfs_compressor_opt", "squashfs_compressor_opt")
Mohamad Ayyashdfec8152016-05-24 12:59:30 -0700607 copy_prop("vendor_squashfs_block_size", "squashfs_block_size")
Mohamad Ayyash1b6d3482016-06-15 15:53:07 -0700608 copy_prop("vendor_squashfs_disable_4k_align", "squashfs_disable_4k_align")
Mohamad Ayyashf8765552016-03-02 21:07:23 -0800609 copy_prop("vendor_base_fs_file", "base_fs_file")
Patrick Tjina1900842016-10-20 10:58:12 -0700610 copy_prop("vendor_extfs_inode_count", "extfs_inode_count")
Patrick Tjin3f5f9932018-03-23 11:36:43 -0700611 if not copy_prop("vendor_extfs_rsv_pct", "extfs_rsv_pct"):
612 d["extfs_rsv_pct"] = "0"
Yifan Hong749062d2018-06-19 16:23:16 -0700613 copy_prop("vendor_reserved_size", "partition_reserved_size")
Jaekyun Seokb7735d82017-11-27 17:04:47 +0900614 elif mount_point == "product":
615 copy_prop("avb_product_hashtree_enable", "avb_hashtree_enable")
616 copy_prop("avb_product_add_hashtree_footer_args",
617 "avb_add_hashtree_footer_args")
618 copy_prop("avb_product_key_path", "avb_key_path")
619 copy_prop("avb_product_algorithm", "avb_algorithm")
620 copy_prop("product_fs_type", "fs_type")
621 copy_prop("product_size", "partition_size")
Tao Bao332a96b2018-03-31 10:27:35 -0700622 if not copy_prop("product_journal_size", "journal_size"):
623 d["journal_size"] = "0"
Jaekyun Seokb7735d82017-11-27 17:04:47 +0900624 copy_prop("product_verity_block_device", "verity_block_device")
Mark Salyzynf0cef8d2018-10-29 10:55:06 -0700625 copy_prop("ext4_share_dup_blocks", "ext4_share_dup_blocks")
Jaekyun Seokb7735d82017-11-27 17:04:47 +0900626 copy_prop("product_squashfs_compressor", "squashfs_compressor")
627 copy_prop("product_squashfs_compressor_opt", "squashfs_compressor_opt")
628 copy_prop("product_squashfs_block_size", "squashfs_block_size")
629 copy_prop("product_squashfs_disable_4k_align", "squashfs_disable_4k_align")
630 copy_prop("product_base_fs_file", "base_fs_file")
631 copy_prop("product_extfs_inode_count", "extfs_inode_count")
Patrick Tjin3f5f9932018-03-23 11:36:43 -0700632 if not copy_prop("product_extfs_rsv_pct", "extfs_rsv_pct"):
633 d["extfs_rsv_pct"] = "0"
Yifan Hong56a6c3b2018-07-20 15:19:34 -0700634 copy_prop("product_reserved_size", "partition_reserved_size")
Dario Freni924af7d2018-08-17 00:56:14 +0100635 elif mount_point == "product_services":
Yifan Hongebc041a2018-07-26 16:02:52 -0700636 copy_prop("avb_product_services_hashtree_enable", "avb_hashtree_enable")
637 copy_prop("avb_product_services_add_hashtree_footer_args",
Dario Freni5f681e12018-05-29 13:09:01 +0100638 "avb_add_hashtree_footer_args")
Yifan Hongebc041a2018-07-26 16:02:52 -0700639 copy_prop("avb_product_services_key_path", "avb_key_path")
640 copy_prop("avb_product_services_algorithm", "avb_algorithm")
641 copy_prop("product_services_fs_type", "fs_type")
642 copy_prop("product_services_size", "partition_size")
643 if not copy_prop("product_services_journal_size", "journal_size"):
Dario Freni5f681e12018-05-29 13:09:01 +0100644 d["journal_size"] = "0"
Yifan Hongebc041a2018-07-26 16:02:52 -0700645 copy_prop("product_services_verity_block_device", "verity_block_device")
Mark Salyzynf0cef8d2018-10-29 10:55:06 -0700646 copy_prop("ext4_share_dup_blocks", "ext4_share_dup_blocks")
Yifan Hongebc041a2018-07-26 16:02:52 -0700647 copy_prop("product_services_squashfs_compressor", "squashfs_compressor")
648 copy_prop("product_services_squashfs_compressor_opt",
Dario Freni5f681e12018-05-29 13:09:01 +0100649 "squashfs_compressor_opt")
Yifan Hongebc041a2018-07-26 16:02:52 -0700650 copy_prop("product_services_squashfs_block_size", "squashfs_block_size")
651 copy_prop("product_services_squashfs_disable_4k_align",
Dario Freni5f681e12018-05-29 13:09:01 +0100652 "squashfs_disable_4k_align")
Yifan Hongebc041a2018-07-26 16:02:52 -0700653 copy_prop("product_services_base_fs_file", "base_fs_file")
654 copy_prop("product_services_extfs_inode_count", "extfs_inode_count")
655 if not copy_prop("product_services_extfs_rsv_pct", "extfs_rsv_pct"):
Dario Freni5f681e12018-05-29 13:09:01 +0100656 d["extfs_rsv_pct"] = "0"
Yifan Hongebc041a2018-07-26 16:02:52 -0700657 copy_prop("product_services_reserved_size", "partition_reserved_size")
Bowgo Tsaid624fa62017-11-14 23:42:30 +0800658 elif mount_point == "odm":
659 copy_prop("avb_odm_hashtree_enable", "avb_hashtree_enable")
660 copy_prop("avb_odm_add_hashtree_footer_args",
661 "avb_add_hashtree_footer_args")
662 copy_prop("avb_odm_key_path", "avb_key_path")
663 copy_prop("avb_odm_algorithm", "avb_algorithm")
664 copy_prop("odm_fs_type", "fs_type")
665 copy_prop("odm_size", "partition_size")
666 if not copy_prop("odm_journal_size", "journal_size"):
667 d["journal_size"] = "0"
668 copy_prop("odm_verity_block_device", "verity_block_device")
Mark Salyzynf0cef8d2018-10-29 10:55:06 -0700669 copy_prop("ext4_share_dup_blocks", "ext4_share_dup_blocks")
Bowgo Tsaid624fa62017-11-14 23:42:30 +0800670 copy_prop("odm_squashfs_compressor", "squashfs_compressor")
671 copy_prop("odm_squashfs_compressor_opt", "squashfs_compressor_opt")
672 copy_prop("odm_squashfs_block_size", "squashfs_block_size")
673 copy_prop("odm_squashfs_disable_4k_align", "squashfs_disable_4k_align")
674 copy_prop("odm_base_fs_file", "base_fs_file")
675 copy_prop("odm_extfs_inode_count", "extfs_inode_count")
676 if not copy_prop("odm_extfs_rsv_pct", "extfs_rsv_pct"):
677 d["extfs_rsv_pct"] = "0"
678 copy_prop("odm_reserved_size", "partition_reserved_size")
Ying Wangb8888432014-03-11 17:13:27 -0700679 elif mount_point == "oem":
680 copy_prop("fs_type", "fs_type")
681 copy_prop("oem_size", "partition_size")
Tao Bao332a96b2018-03-31 10:27:35 -0700682 if not copy_prop("oem_journal_size", "journal_size"):
683 d["journal_size"] = "0"
Patrick Tjina1900842016-10-20 10:58:12 -0700684 copy_prop("oem_extfs_inode_count", "extfs_inode_count")
Mark Salyzynf0cef8d2018-10-29 10:55:06 -0700685 copy_prop("ext4_share_dup_blocks", "ext4_share_dup_blocks")
Patrick Tjin3f5f9932018-03-23 11:36:43 -0700686 if not copy_prop("oem_extfs_rsv_pct", "extfs_rsv_pct"):
687 d["extfs_rsv_pct"] = "0"
David Zeuthen4014a9d2016-09-30 17:29:22 -0400688 d["partition_name"] = mount_point
Ying Wangbd93d422011-10-28 17:02:30 -0700689 return d
690
691
692def LoadGlobalDict(filename):
693 """Load "name=value" pairs from filename"""
694 d = {}
695 f = open(filename)
696 for line in f:
697 line = line.strip()
698 if not line or line.startswith("#"):
699 continue
700 k, v = line.split("=", 1)
701 d[k] = v
702 f.close()
703 return d
704
705
Yifan Hongbbcba1e2018-06-18 16:32:35 -0700706def GlobalDictFromImageProp(image_prop, mount_point):
707 d = {}
708 def copy_prop(src_p, dest_p):
709 if src_p in image_prop:
710 d[dest_p] = image_prop[src_p]
711 return True
712 return False
Tao Bao4251fe92018-07-23 13:05:00 -0700713
Yifan Hongbbcba1e2018-06-18 16:32:35 -0700714 if mount_point == "system":
Tao Bao35f4ebc2018-09-27 15:31:11 -0700715 copy_prop("partition_size", "system_size")
Yifan Hongbbcba1e2018-06-18 16:32:35 -0700716 elif mount_point == "system_other":
Tao Bao35f4ebc2018-09-27 15:31:11 -0700717 copy_prop("partition_size", "system_size")
Yifan Hong749062d2018-06-19 16:23:16 -0700718 elif mount_point == "vendor":
Tao Bao35f4ebc2018-09-27 15:31:11 -0700719 copy_prop("partition_size", "vendor_size")
Bowgo Tsaid624fa62017-11-14 23:42:30 +0800720 elif mount_point == "odm":
Tao Bao35f4ebc2018-09-27 15:31:11 -0700721 copy_prop("partition_size", "odm_size")
Yifan Hong56a6c3b2018-07-20 15:19:34 -0700722 elif mount_point == "product":
Tao Bao35f4ebc2018-09-27 15:31:11 -0700723 copy_prop("partition_size", "product_size")
Dario Freni924af7d2018-08-17 00:56:14 +0100724 elif mount_point == "product_services":
Tao Bao35f4ebc2018-09-27 15:31:11 -0700725 copy_prop("partition_size", "product_services_size")
Yifan Hongbbcba1e2018-06-18 16:32:35 -0700726 return d
727
728
729def SaveGlobalDict(filename, glob_dict):
730 with open(filename, "w") as f:
731 f.writelines(["%s=%s" % (key, value) for (key, value) in glob_dict.items()])
732
733
Ying Wangbd93d422011-10-28 17:02:30 -0700734def main(argv):
Yifan Hongbbcba1e2018-06-18 16:32:35 -0700735 if len(argv) < 4 or len(argv) > 5:
Tao Baoc72727a2017-12-07 10:33:00 -0800736 print(__doc__)
Ying Wangbd93d422011-10-28 17:02:30 -0700737 sys.exit(1)
738
Tao Bao32fcdab2018-10-12 10:30:39 -0700739 common.InitLogging()
740
Ying Wangbd93d422011-10-28 17:02:30 -0700741 in_dir = argv[0]
742 glob_dict_file = argv[1]
743 out_file = argv[2]
Thierry Strudel74a81e62015-07-09 09:54:55 -0700744 target_out = argv[3]
Yifan Hongbbcba1e2018-06-18 16:32:35 -0700745 prop_file_out = argv[4] if len(argv) >= 5 else None
Ying Wangbd93d422011-10-28 17:02:30 -0700746
747 glob_dict = LoadGlobalDict(glob_dict_file)
Ying Wangae61f502015-03-12 18:30:39 -0700748 if "mount_point" in glob_dict:
Mark Salyzyn780f5952018-10-19 13:44:36 -0700749 # The caller knows the mount point and provides a dictionary needed by
Tao Baoc7a6f1e2015-06-23 11:16:05 -0700750 # BuildImage().
Ying Wangae61f502015-03-12 18:30:39 -0700751 image_properties = glob_dict
Ying Wang9f8e8db2011-11-04 11:37:01 -0700752 else:
Ying Wangae61f502015-03-12 18:30:39 -0700753 image_filename = os.path.basename(out_file)
754 mount_point = ""
755 if image_filename == "system.img":
756 mount_point = "system"
Alex Light4e358ab2016-06-16 14:47:10 -0700757 elif image_filename == "system_other.img":
758 mount_point = "system_other"
Ying Wangae61f502015-03-12 18:30:39 -0700759 elif image_filename == "userdata.img":
760 mount_point = "data"
761 elif image_filename == "cache.img":
762 mount_point = "cache"
763 elif image_filename == "vendor.img":
764 mount_point = "vendor"
Bowgo Tsaid624fa62017-11-14 23:42:30 +0800765 elif image_filename == "odm.img":
766 mount_point = "odm"
Ying Wangae61f502015-03-12 18:30:39 -0700767 elif image_filename == "oem.img":
768 mount_point = "oem"
Jaekyun Seokb7735d82017-11-27 17:04:47 +0900769 elif image_filename == "product.img":
770 mount_point = "product"
Dario Freni924af7d2018-08-17 00:56:14 +0100771 elif image_filename == "product_services.img":
772 mount_point = "product_services"
Ying Wangae61f502015-03-12 18:30:39 -0700773 else:
Tao Bao32fcdab2018-10-12 10:30:39 -0700774 logger.error("Unknown image file name %s", image_filename)
Tao Bao1c830bf2017-12-25 10:43:47 -0800775 sys.exit(1)
Ying Wangbd93d422011-10-28 17:02:30 -0700776
Ying Wangae61f502015-03-12 18:30:39 -0700777 image_properties = ImagePropFromGlobalDict(glob_dict, mount_point)
778
Tao Baoc6bd70a2018-09-27 16:58:00 -0700779 try:
780 BuildImage(in_dir, image_properties, out_file, target_out)
781 except:
Tao Bao32fcdab2018-10-12 10:30:39 -0700782 logger.error("Failed to build %s from %s", out_file, in_dir)
Tao Baoc6bd70a2018-09-27 16:58:00 -0700783 raise
Ying Wangbd93d422011-10-28 17:02:30 -0700784
Yifan Hongbbcba1e2018-06-18 16:32:35 -0700785 if prop_file_out:
786 glob_dict_out = GlobalDictFromImageProp(image_properties, mount_point)
787 SaveGlobalDict(prop_file_out, glob_dict_out)
Ying Wangbd93d422011-10-28 17:02:30 -0700788
Tao Bao32fcdab2018-10-12 10:30:39 -0700789
Ying Wangbd93d422011-10-28 17:02:30 -0700790if __name__ == '__main__':
Tao Bao1c830bf2017-12-25 10:43:47 -0800791 try:
792 main(sys.argv[1:])
793 finally:
794 common.Cleanup()