blob: 317a6d915102018d81491824d37cdc277f82c699 [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
Tao Bao2bbb07c2019-05-07 13:12:21 -070021Usage: build_image input_directory properties_file output_image \\
Yifan Hong8c3dce02019-04-09 17:03:57 +000022 target_output_directory
Ying Wangbd93d422011-10-28 17:02:30 -070023"""
Tao Baoc72727a2017-12-07 10:33:00 -080024
25from __future__ import print_function
26
Tao Bao32fcdab2018-10-12 10:30:39 -070027import logging
Ying Wangbd93d422011-10-28 17:02:30 -070028import os
Ying Wang69e9b4d2012-11-26 18:10:23 -080029import os.path
Tao Baoc7a6f1e2015-06-23 11:16:05 -070030import re
Geremy Condrafd6f7512013-06-16 17:26:08 -070031import shutil
Tao Baoc72727a2017-12-07 10:33:00 -080032import sys
33
34import common
Tao Bao71197512018-10-11 14:08:45 -070035import verity_utils
Ying Wangbd93d422011-10-28 17:02:30 -070036
Tao Bao32fcdab2018-10-12 10:30:39 -070037logger = logging.getLogger(__name__)
38
Baligh Uddin601ddea2015-06-09 15:48:14 -070039OPTIONS = common.OPTIONS
Tao Bao71197512018-10-11 14:08:45 -070040BLOCK_SIZE = common.BLOCK_SIZE
Yifan Hongbbcba1e2018-06-18 16:32:35 -070041BYTES_IN_MB = 1024 * 1024
Geremy Condrae8e982a2014-05-16 19:14:30 -070042
Tao Baoc72727a2017-12-07 10:33:00 -080043
Tao Baoc6bd70a2018-09-27 16:58:00 -070044class BuildImageError(Exception):
45 """An Exception raised during image building."""
46
47 def __init__(self, message):
48 Exception.__init__(self, message)
49
50
Yifan Hongbbcba1e2018-06-18 16:32:35 -070051def GetDiskUsage(path):
Tao Baoc6bd70a2018-09-27 16:58:00 -070052 """Returns the number of bytes that "path" occupies on host.
Yifan Hongbbcba1e2018-06-18 16:32:35 -070053
54 Args:
Mark Salyzyn780f5952018-10-19 13:44:36 -070055 path: The directory or file to calculate size on.
Tao Baoc6bd70a2018-09-27 16:58:00 -070056
Yifan Hongbbcba1e2018-06-18 16:32:35 -070057 Returns:
Mark Salyzyn780f5952018-10-19 13:44:36 -070058 The number of bytes based on a 1K block_size.
Yifan Hongbbcba1e2018-06-18 16:32:35 -070059 """
Mark Salyzyn780f5952018-10-19 13:44:36 -070060 cmd = ["du", "-k", "-s", path]
Tao Baof3fc62c2018-10-25 12:23:12 -070061 output = common.RunAndCheckOutput(cmd, verbose=False)
Mark Salyzyn780f5952018-10-19 13:44:36 -070062 return int(output.split()[0]) * 1024
63
64
65def GetInodeUsage(path):
66 """Returns the number of inodes that "path" occupies on host.
67
68 Args:
69 path: The directory or file to calculate inode number on.
70
71 Returns:
72 The number of inodes used.
Mark Salyzyn780f5952018-10-19 13:44:36 -070073 """
74 cmd = ["find", path, "-print"]
Tao Baof3fc62c2018-10-25 12:23:12 -070075 output = common.RunAndCheckOutput(cmd, verbose=False)
Mark Salyzyn9f23b892019-01-08 08:17:46 -080076 # increase by > 4% as number of files and directories is not whole picture.
Mark Salyzync25b2bf2019-01-16 08:03:10 -080077 inodes = output.count('\n')
78 spare_inodes = inodes * 4 // 100
Mark Salyzyn60fa99d2019-01-16 08:03:10 -080079 min_spare_inodes = 12
Mark Salyzync25b2bf2019-01-16 08:03:10 -080080 if spare_inodes < min_spare_inodes:
81 spare_inodes = min_spare_inodes
82 return inodes + spare_inodes
Mark Salyzyn780f5952018-10-19 13:44:36 -070083
84
Mark Salyzyn6541d0a2019-01-10 14:30:51 -080085def GetFilesystemCharacteristics(image_path, sparse_image=True):
86 """Returns various filesystem characteristics of "image_path".
Mark Salyzyn780f5952018-10-19 13:44:36 -070087
88 Args:
Mark Salyzyn6541d0a2019-01-10 14:30:51 -080089 image_path: The file to analyze.
90 sparse_image: Image is sparse
Mark Salyzyn780f5952018-10-19 13:44:36 -070091
92 Returns:
93 The characteristics dictionary.
Mark Salyzyn780f5952018-10-19 13:44:36 -070094 """
Mark Salyzyn6541d0a2019-01-10 14:30:51 -080095 unsparse_image_path = image_path
96 if sparse_image:
97 unsparse_image_path = UnsparseImage(image_path, replace=False)
Mark Salyzyn780f5952018-10-19 13:44:36 -070098
99 cmd = ["tune2fs", "-l", unsparse_image_path]
100 try:
101 output = common.RunAndCheckOutput(cmd, verbose=False)
Tao Baof3fc62c2018-10-25 12:23:12 -0700102 finally:
Mark Salyzyn6541d0a2019-01-10 14:30:51 -0800103 if sparse_image:
104 os.remove(unsparse_image_path)
Tao Baof3fc62c2018-10-25 12:23:12 -0700105 fs_dict = {}
Mark Salyzyn780f5952018-10-19 13:44:36 -0700106 for line in output.splitlines():
107 fields = line.split(":")
108 if len(fields) == 2:
109 fs_dict[fields[0].strip()] = fields[1].strip()
110 return fs_dict
Yifan Hongbbcba1e2018-06-18 16:32:35 -0700111
112
Geremy Condra6e8f53c2013-12-05 17:09:18 -0800113def UnsparseImage(sparse_image_path, replace=True):
Geremy Condrafd6f7512013-06-16 17:26:08 -0700114 img_dir = os.path.dirname(sparse_image_path)
115 unsparse_image_path = "unsparse_" + os.path.basename(sparse_image_path)
116 unsparse_image_path = os.path.join(img_dir, unsparse_image_path)
117 if os.path.exists(unsparse_image_path):
Geremy Condra6e8f53c2013-12-05 17:09:18 -0800118 if replace:
119 os.unlink(unsparse_image_path)
120 else:
Tao Baoc6bd70a2018-09-27 16:58:00 -0700121 return unsparse_image_path
Geremy Condrafd6f7512013-06-16 17:26:08 -0700122 inflate_command = ["simg2img", sparse_image_path, unsparse_image_path]
Tao Bao986ee862018-10-04 15:46:16 -0700123 try:
124 common.RunAndCheckOutput(inflate_command)
125 except:
Geremy Condrafd6f7512013-06-16 17:26:08 -0700126 os.remove(unsparse_image_path)
Tao Bao986ee862018-10-04 15:46:16 -0700127 raise
Tao Baoc6bd70a2018-09-27 16:58:00 -0700128 return unsparse_image_path
Geremy Condrafd6f7512013-06-16 17:26:08 -0700129
Tao Baoc72727a2017-12-07 10:33:00 -0800130
Mohamad Ayyashf8765552016-03-02 21:07:23 -0800131def ConvertBlockMapToBaseFs(block_map_file):
Tao Bao1c830bf2017-12-25 10:43:47 -0800132 base_fs_file = common.MakeTempFile(prefix="script_gen_", suffix=".base_fs")
Mohamad Ayyashf8765552016-03-02 21:07:23 -0800133 convert_command = ["blk_alloc_to_base_fs", block_map_file, base_fs_file]
Tao Bao986ee862018-10-04 15:46:16 -0700134 common.RunAndCheckOutput(convert_command)
Tao Baoc6bd70a2018-09-27 16:58:00 -0700135 return base_fs_file
Mohamad Ayyashf8765552016-03-02 21:07:23 -0800136
Tao Baod4349f22017-12-07 23:01:25 -0800137
Tao Baoc2606eb2018-07-20 14:44:46 -0700138def SetUpInDirAndFsConfig(origin_in, prop_dict):
139 """Returns the in_dir and fs_config that should be used for image building.
140
Tom Cherryd14b8952018-08-09 14:26:00 -0700141 When building system.img for all targets, it creates and returns a staged dir
142 that combines the contents of /system (i.e. in the given in_dir) and root.
Tao Baoc2606eb2018-07-20 14:44:46 -0700143
144 Args:
145 origin_in: Path to the input directory.
146 prop_dict: A property dict that contains info like partition size. Values
147 may be updated.
148
149 Returns:
150 A tuple of in_dir and fs_config that should be used to build the image.
151 """
152 fs_config = prop_dict.get("fs_config")
Tom Cherryd14b8952018-08-09 14:26:00 -0700153
154 if prop_dict["mount_point"] == "system_other":
155 prop_dict["mount_point"] = "system"
156 return origin_in, fs_config
157
158 if prop_dict["mount_point"] != "system":
Tao Baoc2606eb2018-07-20 14:44:46 -0700159 return origin_in, fs_config
160
Mark Salyzyn780f5952018-10-19 13:44:36 -0700161 if "first_pass" in prop_dict:
162 prop_dict["mount_point"] = "/"
163 return prop_dict["first_pass"]
164
Tao Baoc2606eb2018-07-20 14:44:46 -0700165 # Construct a staging directory of the root file system.
166 in_dir = common.MakeTempDir()
167 root_dir = prop_dict.get("root_dir")
168 if root_dir:
169 shutil.rmtree(in_dir)
170 shutil.copytree(root_dir, in_dir, symlinks=True)
171 in_dir_system = os.path.join(in_dir, "system")
172 shutil.rmtree(in_dir_system, ignore_errors=True)
173 shutil.copytree(origin_in, in_dir_system, symlinks=True)
174
175 # Change the mount point to "/".
176 prop_dict["mount_point"] = "/"
177 if fs_config:
178 # We need to merge the fs_config files of system and root.
179 merged_fs_config = common.MakeTempFile(
180 prefix="merged_fs_config", suffix=".txt")
181 with open(merged_fs_config, "w") as fw:
182 if "root_fs_config" in prop_dict:
183 with open(prop_dict["root_fs_config"]) as fr:
184 fw.writelines(fr.readlines())
185 with open(fs_config) as fr:
186 fw.writelines(fr.readlines())
187 fs_config = merged_fs_config
Mark Salyzyn780f5952018-10-19 13:44:36 -0700188 prop_dict["first_pass"] = (in_dir, fs_config)
Tao Baoc2606eb2018-07-20 14:44:46 -0700189 return in_dir, fs_config
190
191
Tao Baod4349f22017-12-07 23:01:25 -0800192def CheckHeadroom(ext4fs_output, prop_dict):
193 """Checks if there's enough headroom space available.
194
195 Headroom is the reserved space on system image (via PRODUCT_SYSTEM_HEADROOM),
196 which is useful for devices with low disk space that have system image
197 variation between builds. The 'partition_headroom' in prop_dict is the size
198 in bytes, while the numbers in 'ext4fs_output' are for 4K-blocks.
199
200 Args:
201 ext4fs_output: The output string from mke2fs command.
202 prop_dict: The property dict.
203
Tao Baod8a953d2018-01-02 21:19:27 -0800204 Raises:
205 AssertionError: On invalid input.
Tao Baoc6bd70a2018-09-27 16:58:00 -0700206 BuildImageError: On check failure.
Tao Baod4349f22017-12-07 23:01:25 -0800207 """
Tao Baod8a953d2018-01-02 21:19:27 -0800208 assert ext4fs_output is not None
209 assert prop_dict.get('fs_type', '').startswith('ext4')
210 assert 'partition_headroom' in prop_dict
211 assert 'mount_point' in prop_dict
212
Tao Baod4349f22017-12-07 23:01:25 -0800213 ext4fs_stats = re.compile(
214 r'Created filesystem with .* (?P<used_blocks>[0-9]+)/'
215 r'(?P<total_blocks>[0-9]+) blocks')
Tao Baoc72727a2017-12-07 10:33:00 -0800216 last_line = ext4fs_output.strip().split('\n')[-1]
217 m = ext4fs_stats.match(last_line)
Tao Baod4349f22017-12-07 23:01:25 -0800218 used_blocks = int(m.groupdict().get('used_blocks'))
219 total_blocks = int(m.groupdict().get('total_blocks'))
Mark Salyzyn780f5952018-10-19 13:44:36 -0700220 headroom_blocks = int(prop_dict['partition_headroom']) // BLOCK_SIZE
Tao Baod4349f22017-12-07 23:01:25 -0800221 adjusted_blocks = total_blocks - headroom_blocks
222 if used_blocks > adjusted_blocks:
Tao Baod8a953d2018-01-02 21:19:27 -0800223 mount_point = prop_dict["mount_point"]
Tao Baoc6bd70a2018-09-27 16:58:00 -0700224 raise BuildImageError(
225 "Error: Not enough room on {} (total: {} blocks, used: {} blocks, "
226 "headroom: {} blocks, available: {} blocks)".format(
227 mount_point, total_blocks, used_blocks, headroom_blocks,
228 adjusted_blocks))
Tao Baod4349f22017-12-07 23:01:25 -0800229
230
Mark Salyzyn3cd24602018-11-07 07:40:31 -0800231def BuildImageMkfs(in_dir, prop_dict, out_file, target_out, fs_config):
232 """Builds a pure image for the files under in_dir and writes it to out_file.
Tao Baoc2606eb2018-07-20 14:44:46 -0700233
Ying Wangbd93d422011-10-28 17:02:30 -0700234 Args:
Tao Baoc2606eb2018-07-20 14:44:46 -0700235 in_dir: Path to input directory.
236 prop_dict: A property dict that contains info like partition size. Values
237 will be updated with computed values.
238 out_file: The output image file.
239 target_out: Path to the TARGET_OUT directory as in Makefile. It actually
240 points to the /system directory under PRODUCT_OUT. fs_config (the one
241 under system/core/libcutils) reads device specific FS config files from
242 there.
Mark Salyzyn3cd24602018-11-07 07:40:31 -0800243 fs_config: The fs_config file that drives the prototype
Ying Wangbd93d422011-10-28 17:02:30 -0700244
Tao Baoc6bd70a2018-09-27 16:58:00 -0700245 Raises:
246 BuildImageError: On build image failures.
Ying Wangbd93d422011-10-28 17:02:30 -0700247 """
248 build_command = []
249 fs_type = prop_dict.get("fs_type", "")
Tao Baoc72727a2017-12-07 10:33:00 -0800250 run_e2fsck = False
Geremy Condrafd6f7512013-06-16 17:26:08 -0700251
Ying Wangbd93d422011-10-28 17:02:30 -0700252 if fs_type.startswith("ext"):
Adrien Schildknecht9a072cc2016-11-18 17:06:29 -0800253 build_command = [prop_dict["ext_mkuserimg"]]
Ying Wangbd93d422011-10-28 17:02:30 -0700254 if "extfs_sparse_flag" in prop_dict:
255 build_command.append(prop_dict["extfs_sparse_flag"])
Tao Baoc72727a2017-12-07 10:33:00 -0800256 run_e2fsck = True
Ying Wangbd93d422011-10-28 17:02:30 -0700257 build_command.extend([in_dir, out_file, fs_type,
258 prop_dict["mount_point"]])
Tao Bao35f4ebc2018-09-27 15:31:11 -0700259 build_command.append(prop_dict["image_size"])
Ying Wangf3b86352014-11-18 18:03:13 -0800260 if "journal_size" in prop_dict:
261 build_command.extend(["-j", prop_dict["journal_size"]])
Doug Zongker850b8072013-12-05 15:54:55 -0800262 if "timestamp" in prop_dict:
263 build_command.extend(["-T", str(prop_dict["timestamp"])])
Ying Wanga2292c92015-03-24 19:07:40 -0700264 if fs_config:
Doug Zongker82822822014-06-16 09:10:55 -0700265 build_command.extend(["-C", fs_config])
Thierry Strudel74a81e62015-07-09 09:54:55 -0700266 if target_out:
267 build_command.extend(["-D", target_out])
Ying Wanga2292c92015-03-24 19:07:40 -0700268 if "block_list" in prop_dict:
269 build_command.extend(["-B", prop_dict["block_list"]])
Mohamad Ayyashf8765552016-03-02 21:07:23 -0800270 if "base_fs_file" in prop_dict:
271 base_fs_file = ConvertBlockMapToBaseFs(prop_dict["base_fs_file"])
Mohamad Ayyashf8765552016-03-02 21:07:23 -0800272 build_command.extend(["-d", base_fs_file])
Christoffer Dall8ed01f32014-12-17 21:34:12 +0100273 build_command.extend(["-L", prop_dict["mount_point"]])
Patrick Tjina1900842016-10-20 10:58:12 -0700274 if "extfs_inode_count" in prop_dict:
275 build_command.extend(["-i", prop_dict["extfs_inode_count"]])
Patrick Tjin3f5f9932018-03-23 11:36:43 -0700276 if "extfs_rsv_pct" in prop_dict:
277 build_command.extend(["-M", prop_dict["extfs_rsv_pct"]])
Connor O'Brien20f08c32017-01-05 16:48:14 -0800278 if "flash_erase_block_size" in prop_dict:
279 build_command.extend(["-e", prop_dict["flash_erase_block_size"]])
280 if "flash_logical_block_size" in prop_dict:
281 build_command.extend(["-o", prop_dict["flash_logical_block_size"]])
Tao Baod86e3112017-09-22 15:45:33 -0700282 # Specify UUID and hash_seed if using mke2fs.
Tianjie Xu57332222018-08-15 16:16:21 -0700283 if prop_dict["ext_mkuserimg"] == "mkuserimg_mke2fs":
Tao Baod86e3112017-09-22 15:45:33 -0700284 if "uuid" in prop_dict:
285 build_command.extend(["-U", prop_dict["uuid"]])
286 if "hash_seed" in prop_dict:
287 build_command.extend(["-S", prop_dict["hash_seed"]])
Jin Qianfde9f792018-01-22 13:15:46 -0800288 if "ext4_share_dup_blocks" in prop_dict:
289 build_command.append("-c")
Mark Salyzync777eaa2019-01-08 10:08:04 -0800290 build_command.extend(["--inode_size", "256"])
Ying Wanga2292c92015-03-24 19:07:40 -0700291 if "selinux_fc" in prop_dict:
Kenny Rootf32dc712012-04-08 10:42:34 -0700292 build_command.append(prop_dict["selinux_fc"])
Mohamad Ayyashb97746e2015-03-03 12:30:37 -0800293 elif fs_type.startswith("squash"):
294 build_command = ["mksquashfsimage.sh"]
295 build_command.extend([in_dir, out_file])
Todd Poynorb2a555e2015-12-15 18:00:14 -0800296 if "squashfs_sparse_flag" in prop_dict:
297 build_command.extend([prop_dict["squashfs_sparse_flag"]])
Mohamad Ayyashb97746e2015-03-03 12:30:37 -0800298 build_command.extend(["-m", prop_dict["mount_point"]])
Thierry Strudel74a81e62015-07-09 09:54:55 -0700299 if target_out:
300 build_command.extend(["-d", target_out])
Mohamad Ayyash88378822016-04-07 22:10:51 -0700301 if fs_config:
302 build_command.extend(["-C", fs_config])
Ying Wanga2292c92015-03-24 19:07:40 -0700303 if "selinux_fc" in prop_dict:
Mohamad Ayyashb97746e2015-03-03 12:30:37 -0800304 build_command.extend(["-c", prop_dict["selinux_fc"]])
Mohamad Ayyashc3484f72016-06-13 09:46:58 -0700305 if "block_list" in prop_dict:
306 build_command.extend(["-B", prop_dict["block_list"]])
Ng Zhi An9446c1d2018-01-19 15:51:46 -0800307 if "squashfs_block_size" in prop_dict:
308 build_command.extend(["-b", prop_dict["squashfs_block_size"]])
Simon Wilsonf86e7ee2015-06-17 12:35:15 -0700309 if "squashfs_compressor" in prop_dict:
310 build_command.extend(["-z", prop_dict["squashfs_compressor"]])
311 if "squashfs_compressor_opt" in prop_dict:
312 build_command.extend(["-zo", prop_dict["squashfs_compressor_opt"]])
Tao Baoc72727a2017-12-07 10:33:00 -0800313 if prop_dict.get("squashfs_disable_4k_align") == "true":
Mohamad Ayyash1b6d3482016-06-15 15:53:07 -0700314 build_command.extend(["-a"])
JP Abgrall5bfed5a2014-06-16 14:17:40 -0700315 elif fs_type.startswith("f2fs"):
316 build_command = ["mkf2fsuserimg.sh"]
Tao Bao35f4ebc2018-09-27 15:31:11 -0700317 build_command.extend([out_file, prop_dict["image_size"]])
Alistair Delva91238cc2019-10-16 10:53:41 -0700318 if "f2fs_sparse_flag" in prop_dict:
319 build_command.extend([prop_dict["f2fs_sparse_flag"]])
Jaegeuk Kim2ea1eba2017-11-28 19:21:28 -0800320 if fs_config:
321 build_command.extend(["-C", fs_config])
322 build_command.extend(["-f", in_dir])
323 if target_out:
324 build_command.extend(["-D", target_out])
325 if "selinux_fc" in prop_dict:
326 build_command.extend(["-s", prop_dict["selinux_fc"]])
327 build_command.extend(["-t", prop_dict["mount_point"]])
328 if "timestamp" in prop_dict:
329 build_command.extend(["-T", str(prop_dict["timestamp"])])
330 build_command.extend(["-L", prop_dict["mount_point"]])
Ying Wangbd93d422011-10-28 17:02:30 -0700331 else:
Tao Baoc6bd70a2018-09-27 16:58:00 -0700332 raise BuildImageError(
333 "Error: unknown filesystem type: {}".format(fs_type))
Ying Wangbd93d422011-10-28 17:02:30 -0700334
Tao Bao986ee862018-10-04 15:46:16 -0700335 try:
336 mkfs_output = common.RunAndCheckOutput(build_command)
337 except:
Tao Baoc6bd70a2018-09-27 16:58:00 -0700338 try:
339 du = GetDiskUsage(in_dir)
340 du_str = "{} bytes ({} MB)".format(du, du // BYTES_IN_MB)
Tao Bao986ee862018-10-04 15:46:16 -0700341 # Suppress any errors from GetDiskUsage() to avoid hiding the real errors
342 # from common.RunAndCheckOutput().
Tao Bao32fcdab2018-10-12 10:30:39 -0700343 except Exception: # pylint: disable=broad-except
344 logger.exception("Failed to compute disk usage with du")
Tao Baoc6bd70a2018-09-27 16:58:00 -0700345 du_str = "unknown"
Tao Bao4251fe92018-07-23 13:05:00 -0700346 print(
Mark Salyzyn3cd24602018-11-07 07:40:31 -0800347 "Out of space? Out of inodes? The tree size of {} is {}, "
348 "with reserved space of {} bytes ({} MB).".format(
Tao Baoc2606eb2018-07-20 14:44:46 -0700349 in_dir, du_str,
Tao Bao4251fe92018-07-23 13:05:00 -0700350 int(prop_dict.get("partition_reserved_size", 0)),
351 int(prop_dict.get("partition_reserved_size", 0)) // BYTES_IN_MB))
Tao Bao35f4ebc2018-09-27 15:31:11 -0700352 print(
Mark Salyzyn780f5952018-10-19 13:44:36 -0700353 "The max image size for filesystem files is {} bytes ({} MB), out of a "
Tao Bao35f4ebc2018-09-27 15:31:11 -0700354 "total partition size of {} bytes ({} MB).".format(
355 int(prop_dict["image_size"]),
356 int(prop_dict["image_size"]) // BYTES_IN_MB,
357 int(prop_dict["partition_size"]),
358 int(prop_dict["partition_size"]) // BYTES_IN_MB))
Tao Bao986ee862018-10-04 15:46:16 -0700359 raise
Ying Wang69e9b4d2012-11-26 18:10:23 -0800360
Mark Salyzyn3cd24602018-11-07 07:40:31 -0800361 if run_e2fsck and prop_dict.get("skip_fsck") != "true":
362 unsparse_image = UnsparseImage(out_file, replace=False)
363
364 # Run e2fsck on the inflated image file
365 e2fsck_command = ["e2fsck", "-f", "-n", unsparse_image]
366 try:
367 common.RunAndCheckOutput(e2fsck_command)
368 finally:
369 os.remove(unsparse_image)
370
371 return mkfs_output
372
373
374def BuildImage(in_dir, prop_dict, out_file, target_out=None):
375 """Builds an image for the files under in_dir and writes it to out_file.
376
377 Args:
378 in_dir: Path to input directory.
379 prop_dict: A property dict that contains info like partition size. Values
380 will be updated with computed values.
381 out_file: The output image file.
382 target_out: Path to the TARGET_OUT directory as in Makefile. It actually
383 points to the /system directory under PRODUCT_OUT. fs_config (the one
384 under system/core/libcutils) reads device specific FS config files from
385 there.
386
387 Raises:
388 BuildImageError: On build image failures.
389 """
390 in_dir, fs_config = SetUpInDirAndFsConfig(in_dir, prop_dict)
391
392 build_command = []
393 fs_type = prop_dict.get("fs_type", "")
394
395 fs_spans_partition = True
396 if fs_type.startswith("squash"):
397 fs_spans_partition = False
398
399 # Get a builder for creating an image that's to be verified by Verified Boot,
400 # or None if not applicable.
401 verity_image_builder = verity_utils.CreateVerityImageBuilder(prop_dict)
402
403 if (prop_dict.get("use_dynamic_partition_size") == "true" and
404 "partition_size" not in prop_dict):
405 # If partition_size is not defined, use output of `du' + reserved_size.
406 size = GetDiskUsage(in_dir)
407 logger.info(
408 "The tree size of %s is %d MB.", in_dir, size // BYTES_IN_MB)
409 # If not specified, give us 16MB margin for GetDiskUsage error ...
410 reserved_size = int(prop_dict.get("partition_reserved_size", BYTES_IN_MB * 16))
411 partition_headroom = int(prop_dict.get("partition_headroom", 0))
412 if fs_type.startswith("ext4") and partition_headroom > reserved_size:
413 reserved_size = partition_headroom
414 size += reserved_size
415 # Round this up to a multiple of 4K so that avbtool works
416 size = common.RoundUpTo4K(size)
417 if fs_type.startswith("ext"):
418 prop_dict["partition_size"] = str(size)
419 prop_dict["image_size"] = str(size)
420 if "extfs_inode_count" not in prop_dict:
421 prop_dict["extfs_inode_count"] = str(GetInodeUsage(in_dir))
422 logger.info(
423 "First Pass based on estimates of %d MB and %s inodes.",
424 size // BYTES_IN_MB, prop_dict["extfs_inode_count"])
425 BuildImageMkfs(in_dir, prop_dict, out_file, target_out, fs_config)
Mark Salyzyn6541d0a2019-01-10 14:30:51 -0800426 sparse_image = False
427 if "extfs_sparse_flag" in prop_dict:
428 sparse_image = True
429 fs_dict = GetFilesystemCharacteristics(out_file, sparse_image)
Mark Salyzyn3cd24602018-11-07 07:40:31 -0800430 os.remove(out_file)
431 block_size = int(fs_dict.get("Block size", "4096"))
432 free_size = int(fs_dict.get("Free blocks", "0")) * block_size
433 reserved_size = int(prop_dict.get("partition_reserved_size", 0))
434 partition_headroom = int(fs_dict.get("partition_headroom", 0))
435 if fs_type.startswith("ext4") and partition_headroom > reserved_size:
436 reserved_size = partition_headroom
437 if free_size <= reserved_size:
438 logger.info(
439 "Not worth reducing image %d <= %d.", free_size, reserved_size)
440 else:
441 size -= free_size
442 size += reserved_size
Mark Salyzyn60a716f2019-01-10 08:36:34 -0800443 if reserved_size == 0:
Mark Salyzync25b2bf2019-01-16 08:03:10 -0800444 # add .3% margin
445 size = size * 1003 // 1000
Mark Salyzyn60a716f2019-01-10 08:36:34 -0800446 # Use a minimum size, otherwise we will fail to calculate an AVB footer
447 # or fail to construct an ext4 image.
448 size = max(size, 256 * 1024)
Mark Salyzyn3cd24602018-11-07 07:40:31 -0800449 if block_size <= 4096:
450 size = common.RoundUpTo4K(size)
451 else:
452 size = ((size + block_size - 1) // block_size) * block_size
453 extfs_inode_count = prop_dict["extfs_inode_count"]
454 inodes = int(fs_dict.get("Inode count", extfs_inode_count))
455 inodes -= int(fs_dict.get("Free inodes", "0"))
Mark Salyzync25b2bf2019-01-16 08:03:10 -0800456 # add .2% margin or 1 inode, whichever is greater
457 spare_inodes = inodes * 2 // 1000
458 min_spare_inodes = 1
459 if spare_inodes < min_spare_inodes:
460 spare_inodes = min_spare_inodes
461 inodes += spare_inodes
Mark Salyzyn3cd24602018-11-07 07:40:31 -0800462 prop_dict["extfs_inode_count"] = str(inodes)
463 prop_dict["partition_size"] = str(size)
464 logger.info(
465 "Allocating %d Inodes for %s.", inodes, out_file)
466 if verity_image_builder:
467 size = verity_image_builder.CalculateDynamicPartitionSize(size)
468 prop_dict["partition_size"] = str(size)
469 logger.info(
470 "Allocating %d MB for %s.", size // BYTES_IN_MB, out_file)
471
472 prop_dict["image_size"] = prop_dict["partition_size"]
473
474 # Adjust the image size to make room for the hashes if this is to be verified.
475 if verity_image_builder:
476 max_image_size = verity_image_builder.CalculateMaxImageSize()
477 prop_dict["image_size"] = str(max_image_size)
478
479 mkfs_output = BuildImageMkfs(in_dir, prop_dict, out_file, target_out, fs_config)
480
Tao Baod4349f22017-12-07 23:01:25 -0800481 # Check if there's enough headroom space available for ext4 image.
Tao Bao79d52f82017-12-07 14:07:44 -0800482 if "partition_headroom" in prop_dict and fs_type.startswith("ext4"):
Tao Baoc6bd70a2018-09-27 16:58:00 -0700483 CheckHeadroom(mkfs_output, prop_dict)
Tao Baoc7a6f1e2015-06-23 11:16:05 -0700484
Tao Bao7549e5e2018-10-03 14:23:59 -0700485 if not fs_spans_partition and verity_image_builder:
486 verity_image_builder.PadSparseImage(out_file)
Mohamad Ayyashdd063522015-03-24 12:42:03 -0700487
Tao Baoc72727a2017-12-07 10:33:00 -0800488 # Create the verified image if this is to be verified.
Tao Bao7549e5e2018-10-03 14:23:59 -0700489 if verity_image_builder:
490 verity_image_builder.Build(out_file)
David Zeuthen4014a9d2016-09-30 17:29:22 -0400491
Ying Wangbd93d422011-10-28 17:02:30 -0700492
493def ImagePropFromGlobalDict(glob_dict, mount_point):
494 """Build an image property dictionary from the global dictionary.
495
496 Args:
497 glob_dict: the global dictionary from the build system.
498 mount_point: such as "system", "data" etc.
499 """
Doug Zongker1ad7ade2013-12-06 11:53:27 -0800500 d = {}
Tao Bao052ae352015-09-28 13:44:13 -0700501
Tao Bao822f5842015-09-30 16:01:14 -0700502 if "build.prop" in glob_dict:
503 bp = glob_dict["build.prop"]
504 if "ro.build.date.utc" in bp:
505 d["timestamp"] = bp["ro.build.date.utc"]
Ying Wang9f8e8db2011-11-04 11:37:01 -0700506
507 def copy_prop(src_p, dest_p):
Patrick Tjin3f5f9932018-03-23 11:36:43 -0700508 """Copy a property from the global dictionary.
509
510 Args:
511 src_p: The source property in the global dictionary.
512 dest_p: The destination property.
513 Returns:
514 True if property was found and copied, False otherwise.
515 """
Ying Wang9f8e8db2011-11-04 11:37:01 -0700516 if src_p in glob_dict:
517 d[dest_p] = str(glob_dict[src_p])
Patrick Tjin3f5f9932018-03-23 11:36:43 -0700518 return True
519 return False
Ying Wang9f8e8db2011-11-04 11:37:01 -0700520
Ying Wangbd93d422011-10-28 17:02:30 -0700521 common_props = (
Ying Wangbd93d422011-10-28 17:02:30 -0700522 "extfs_sparse_flag",
Todd Poynorb2a555e2015-12-15 18:00:14 -0800523 "squashfs_sparse_flag",
Alistair Delva91238cc2019-10-16 10:53:41 -0700524 "f2fs_sparse_flag",
Ying Wang6a42a252013-02-27 13:54:02 -0800525 "skip_fsck",
Adrien Schildknecht9a072cc2016-11-18 17:06:29 -0800526 "ext_mkuserimg",
Geremy Condrafd6f7512013-06-16 17:26:08 -0700527 "verity",
Geremy Condrafd6f7512013-06-16 17:26:08 -0700528 "verity_key",
Sami Tolvanenf99b5312015-05-20 07:30:57 +0100529 "verity_signer_cmd",
David Zeuthen4014a9d2016-09-30 17:29:22 -0400530 "verity_fec",
Bowgo Tsai6ceeb1a2017-10-11 16:21:48 +0800531 "verity_disable",
Bowgo Tsai3e599ea2017-05-26 18:30:04 +0800532 "avb_enable",
Tao Bao2b6dfd62017-09-27 17:17:43 -0700533 "avb_avbtool",
534 "avb_salt",
Yifan Hong2dae5722018-07-31 12:47:27 -0700535 "use_dynamic_partition_size",
Tao Bao2b6dfd62017-09-27 17:17:43 -0700536 )
Ying Wangbd93d422011-10-28 17:02:30 -0700537 for p in common_props:
Ying Wang9f8e8db2011-11-04 11:37:01 -0700538 copy_prop(p, p)
Ying Wangbd93d422011-10-28 17:02:30 -0700539
540 d["mount_point"] = mount_point
541 if mount_point == "system":
Bowgo Tsai3e599ea2017-05-26 18:30:04 +0800542 copy_prop("avb_system_hashtree_enable", "avb_hashtree_enable")
543 copy_prop("avb_system_add_hashtree_footer_args",
544 "avb_add_hashtree_footer_args")
545 copy_prop("avb_system_key_path", "avb_key_path")
546 copy_prop("avb_system_algorithm", "avb_algorithm")
Ying Wang9f8e8db2011-11-04 11:37:01 -0700547 copy_prop("fs_type", "fs_type")
Julius D'souza001c6762017-05-03 13:43:27 -0700548 # Copy the generic system fs type first, override with specific one if
Dan Albert8b72aef2015-03-23 19:13:21 -0700549 # available.
Mohamad Ayyashb97746e2015-03-03 12:30:37 -0800550 copy_prop("system_fs_type", "fs_type")
Julius D'souza001c6762017-05-03 13:43:27 -0700551 copy_prop("system_headroom", "partition_headroom")
Ying Wang9f8e8db2011-11-04 11:37:01 -0700552 copy_prop("system_size", "partition_size")
Tao Bao332a96b2018-03-31 10:27:35 -0700553 if not copy_prop("system_journal_size", "journal_size"):
554 d["journal_size"] = "0"
Daniel Rosenbergf4eabc32014-07-10 15:42:38 -0700555 copy_prop("system_verity_block_device", "verity_block_device")
Tao Baof3282b42015-04-01 11:21:55 -0700556 copy_prop("system_root_image", "system_root_image")
Tao Bao8bfd3c72018-07-20 15:20:28 -0700557 copy_prop("root_dir", "root_dir")
558 copy_prop("root_fs_config", "root_fs_config")
Jin Qianfde9f792018-01-22 13:15:46 -0800559 copy_prop("ext4_share_dup_blocks", "ext4_share_dup_blocks")
Simon Wilsonf86e7ee2015-06-17 12:35:15 -0700560 copy_prop("system_squashfs_compressor", "squashfs_compressor")
561 copy_prop("system_squashfs_compressor_opt", "squashfs_compressor_opt")
Mohamad Ayyashdfec8152016-05-24 12:59:30 -0700562 copy_prop("system_squashfs_block_size", "squashfs_block_size")
Mohamad Ayyash1b6d3482016-06-15 15:53:07 -0700563 copy_prop("system_squashfs_disable_4k_align", "squashfs_disable_4k_align")
Mohamad Ayyashf8765552016-03-02 21:07:23 -0800564 copy_prop("system_base_fs_file", "base_fs_file")
Patrick Tjina1900842016-10-20 10:58:12 -0700565 copy_prop("system_extfs_inode_count", "extfs_inode_count")
Patrick Tjin3f5f9932018-03-23 11:36:43 -0700566 if not copy_prop("system_extfs_rsv_pct", "extfs_rsv_pct"):
567 d["extfs_rsv_pct"] = "0"
Yifan Hongbbcba1e2018-06-18 16:32:35 -0700568 copy_prop("system_reserved_size", "partition_reserved_size")
Daniel Norman72c626f2019-05-13 15:58:14 -0700569 copy_prop("system_selinux_fc", "selinux_fc")
Alex Light4e358ab2016-06-16 14:47:10 -0700570 elif mount_point == "system_other":
Tao Baoc72727a2017-12-07 10:33:00 -0800571 # We inherit the selinux policies of /system since we contain some of its
572 # files.
Bowgo Tsai1e04bf72019-01-23 22:19:19 +0800573 copy_prop("avb_system_other_hashtree_enable", "avb_hashtree_enable")
574 copy_prop("avb_system_other_add_hashtree_footer_args",
Bowgo Tsai3e599ea2017-05-26 18:30:04 +0800575 "avb_add_hashtree_footer_args")
Bowgo Tsai1e04bf72019-01-23 22:19:19 +0800576 copy_prop("avb_system_other_key_path", "avb_key_path")
577 copy_prop("avb_system_other_algorithm", "avb_algorithm")
Alex Light4e358ab2016-06-16 14:47:10 -0700578 copy_prop("fs_type", "fs_type")
579 copy_prop("system_fs_type", "fs_type")
Bowgo Tsai867ab662019-01-29 13:30:18 +0800580 copy_prop("system_other_size", "partition_size")
Tao Bao332a96b2018-03-31 10:27:35 -0700581 if not copy_prop("system_journal_size", "journal_size"):
582 d["journal_size"] = "0"
Alex Light4e358ab2016-06-16 14:47:10 -0700583 copy_prop("system_verity_block_device", "verity_block_device")
Mark Salyzynf0cef8d2018-10-29 10:55:06 -0700584 copy_prop("ext4_share_dup_blocks", "ext4_share_dup_blocks")
Alex Light4e358ab2016-06-16 14:47:10 -0700585 copy_prop("system_squashfs_compressor", "squashfs_compressor")
586 copy_prop("system_squashfs_compressor_opt", "squashfs_compressor_opt")
587 copy_prop("system_squashfs_block_size", "squashfs_block_size")
588 copy_prop("system_base_fs_file", "base_fs_file")
Patrick Tjina1900842016-10-20 10:58:12 -0700589 copy_prop("system_extfs_inode_count", "extfs_inode_count")
Patrick Tjin3f5f9932018-03-23 11:36:43 -0700590 if not copy_prop("system_extfs_rsv_pct", "extfs_rsv_pct"):
591 d["extfs_rsv_pct"] = "0"
Yifan Hongbbcba1e2018-06-18 16:32:35 -0700592 copy_prop("system_reserved_size", "partition_reserved_size")
Daniel Norman72c626f2019-05-13 15:58:14 -0700593 copy_prop("system_selinux_fc", "selinux_fc")
Ying Wangbd93d422011-10-28 17:02:30 -0700594 elif mount_point == "data":
JP Abgrall5bfed5a2014-06-16 14:17:40 -0700595 # Copy the generic fs type first, override with specific one if available.
Ying Wang9f8e8db2011-11-04 11:37:01 -0700596 copy_prop("fs_type", "fs_type")
JP Abgrall5bfed5a2014-06-16 14:17:40 -0700597 copy_prop("userdata_fs_type", "fs_type")
Ying Wang9f8e8db2011-11-04 11:37:01 -0700598 copy_prop("userdata_size", "partition_size")
Tao Baoc72727a2017-12-07 10:33:00 -0800599 copy_prop("flash_logical_block_size", "flash_logical_block_size")
Connor O'Brien20f08c32017-01-05 16:48:14 -0800600 copy_prop("flash_erase_block_size", "flash_erase_block_size")
Daniel Norman72c626f2019-05-13 15:58:14 -0700601 copy_prop("userdata_selinux_fc", "selinux_fc")
Ying Wang9f8e8db2011-11-04 11:37:01 -0700602 elif mount_point == "cache":
603 copy_prop("cache_fs_type", "fs_type")
604 copy_prop("cache_size", "partition_size")
Daniel Norman72c626f2019-05-13 15:58:14 -0700605 copy_prop("cache_selinux_fc", "selinux_fc")
Ying Wanga0febe52013-03-20 11:02:05 -0700606 elif mount_point == "vendor":
Bowgo Tsai3e599ea2017-05-26 18:30:04 +0800607 copy_prop("avb_vendor_hashtree_enable", "avb_hashtree_enable")
608 copy_prop("avb_vendor_add_hashtree_footer_args",
609 "avb_add_hashtree_footer_args")
610 copy_prop("avb_vendor_key_path", "avb_key_path")
611 copy_prop("avb_vendor_algorithm", "avb_algorithm")
Ying Wanga0febe52013-03-20 11:02:05 -0700612 copy_prop("vendor_fs_type", "fs_type")
613 copy_prop("vendor_size", "partition_size")
Tao Bao332a96b2018-03-31 10:27:35 -0700614 if not copy_prop("vendor_journal_size", "journal_size"):
615 d["journal_size"] = "0"
Daniel Rosenbergf4eabc32014-07-10 15:42:38 -0700616 copy_prop("vendor_verity_block_device", "verity_block_device")
Jin Qianfde9f792018-01-22 13:15:46 -0800617 copy_prop("ext4_share_dup_blocks", "ext4_share_dup_blocks")
Patrick Tjine11aa502016-02-09 15:40:38 -0800618 copy_prop("vendor_squashfs_compressor", "squashfs_compressor")
619 copy_prop("vendor_squashfs_compressor_opt", "squashfs_compressor_opt")
Mohamad Ayyashdfec8152016-05-24 12:59:30 -0700620 copy_prop("vendor_squashfs_block_size", "squashfs_block_size")
Mohamad Ayyash1b6d3482016-06-15 15:53:07 -0700621 copy_prop("vendor_squashfs_disable_4k_align", "squashfs_disable_4k_align")
Mohamad Ayyashf8765552016-03-02 21:07:23 -0800622 copy_prop("vendor_base_fs_file", "base_fs_file")
Patrick Tjina1900842016-10-20 10:58:12 -0700623 copy_prop("vendor_extfs_inode_count", "extfs_inode_count")
Patrick Tjin3f5f9932018-03-23 11:36:43 -0700624 if not copy_prop("vendor_extfs_rsv_pct", "extfs_rsv_pct"):
625 d["extfs_rsv_pct"] = "0"
Yifan Hong749062d2018-06-19 16:23:16 -0700626 copy_prop("vendor_reserved_size", "partition_reserved_size")
Daniel Norman72c626f2019-05-13 15:58:14 -0700627 copy_prop("vendor_selinux_fc", "selinux_fc")
Jaekyun Seokb7735d82017-11-27 17:04:47 +0900628 elif mount_point == "product":
629 copy_prop("avb_product_hashtree_enable", "avb_hashtree_enable")
630 copy_prop("avb_product_add_hashtree_footer_args",
631 "avb_add_hashtree_footer_args")
632 copy_prop("avb_product_key_path", "avb_key_path")
633 copy_prop("avb_product_algorithm", "avb_algorithm")
634 copy_prop("product_fs_type", "fs_type")
635 copy_prop("product_size", "partition_size")
Tao Bao332a96b2018-03-31 10:27:35 -0700636 if not copy_prop("product_journal_size", "journal_size"):
637 d["journal_size"] = "0"
Jaekyun Seokb7735d82017-11-27 17:04:47 +0900638 copy_prop("product_verity_block_device", "verity_block_device")
Mark Salyzynf0cef8d2018-10-29 10:55:06 -0700639 copy_prop("ext4_share_dup_blocks", "ext4_share_dup_blocks")
Jaekyun Seokb7735d82017-11-27 17:04:47 +0900640 copy_prop("product_squashfs_compressor", "squashfs_compressor")
641 copy_prop("product_squashfs_compressor_opt", "squashfs_compressor_opt")
642 copy_prop("product_squashfs_block_size", "squashfs_block_size")
643 copy_prop("product_squashfs_disable_4k_align", "squashfs_disable_4k_align")
644 copy_prop("product_base_fs_file", "base_fs_file")
645 copy_prop("product_extfs_inode_count", "extfs_inode_count")
Patrick Tjin3f5f9932018-03-23 11:36:43 -0700646 if not copy_prop("product_extfs_rsv_pct", "extfs_rsv_pct"):
647 d["extfs_rsv_pct"] = "0"
Yifan Hong56a6c3b2018-07-20 15:19:34 -0700648 copy_prop("product_reserved_size", "partition_reserved_size")
Daniel Norman72c626f2019-05-13 15:58:14 -0700649 copy_prop("product_selinux_fc", "selinux_fc")
Justin Yun6151e3f2019-06-25 15:58:13 +0900650 elif mount_point == "system_ext":
651 copy_prop("avb_system_ext_hashtree_enable", "avb_hashtree_enable")
652 copy_prop("avb_system_ext_add_hashtree_footer_args",
Dario Freni5f681e12018-05-29 13:09:01 +0100653 "avb_add_hashtree_footer_args")
Justin Yun6151e3f2019-06-25 15:58:13 +0900654 copy_prop("avb_system_ext_key_path", "avb_key_path")
655 copy_prop("avb_system_ext_algorithm", "avb_algorithm")
656 copy_prop("system_ext_fs_type", "fs_type")
657 copy_prop("system_ext_size", "partition_size")
658 if not copy_prop("system_ext_journal_size", "journal_size"):
Dario Freni5f681e12018-05-29 13:09:01 +0100659 d["journal_size"] = "0"
Justin Yun6151e3f2019-06-25 15:58:13 +0900660 copy_prop("system_ext_verity_block_device", "verity_block_device")
Mark Salyzynf0cef8d2018-10-29 10:55:06 -0700661 copy_prop("ext4_share_dup_blocks", "ext4_share_dup_blocks")
Justin Yun6151e3f2019-06-25 15:58:13 +0900662 copy_prop("system_ext_squashfs_compressor", "squashfs_compressor")
663 copy_prop("system_ext_squashfs_compressor_opt",
Dario Freni5f681e12018-05-29 13:09:01 +0100664 "squashfs_compressor_opt")
Justin Yun6151e3f2019-06-25 15:58:13 +0900665 copy_prop("system_ext_squashfs_block_size", "squashfs_block_size")
666 copy_prop("system_ext_squashfs_disable_4k_align",
Dario Freni5f681e12018-05-29 13:09:01 +0100667 "squashfs_disable_4k_align")
Justin Yun6151e3f2019-06-25 15:58:13 +0900668 copy_prop("system_ext_base_fs_file", "base_fs_file")
669 copy_prop("system_ext_extfs_inode_count", "extfs_inode_count")
670 if not copy_prop("system_ext_extfs_rsv_pct", "extfs_rsv_pct"):
Dario Freni5f681e12018-05-29 13:09:01 +0100671 d["extfs_rsv_pct"] = "0"
Justin Yun6151e3f2019-06-25 15:58:13 +0900672 copy_prop("system_ext_reserved_size", "partition_reserved_size")
673 copy_prop("system_ext_selinux_fc", "selinux_fc")
Bowgo Tsaid624fa62017-11-14 23:42:30 +0800674 elif mount_point == "odm":
675 copy_prop("avb_odm_hashtree_enable", "avb_hashtree_enable")
676 copy_prop("avb_odm_add_hashtree_footer_args",
677 "avb_add_hashtree_footer_args")
678 copy_prop("avb_odm_key_path", "avb_key_path")
679 copy_prop("avb_odm_algorithm", "avb_algorithm")
680 copy_prop("odm_fs_type", "fs_type")
681 copy_prop("odm_size", "partition_size")
682 if not copy_prop("odm_journal_size", "journal_size"):
683 d["journal_size"] = "0"
684 copy_prop("odm_verity_block_device", "verity_block_device")
Mark Salyzynf0cef8d2018-10-29 10:55:06 -0700685 copy_prop("ext4_share_dup_blocks", "ext4_share_dup_blocks")
Bowgo Tsaid624fa62017-11-14 23:42:30 +0800686 copy_prop("odm_squashfs_compressor", "squashfs_compressor")
687 copy_prop("odm_squashfs_compressor_opt", "squashfs_compressor_opt")
688 copy_prop("odm_squashfs_block_size", "squashfs_block_size")
689 copy_prop("odm_squashfs_disable_4k_align", "squashfs_disable_4k_align")
690 copy_prop("odm_base_fs_file", "base_fs_file")
691 copy_prop("odm_extfs_inode_count", "extfs_inode_count")
692 if not copy_prop("odm_extfs_rsv_pct", "extfs_rsv_pct"):
693 d["extfs_rsv_pct"] = "0"
694 copy_prop("odm_reserved_size", "partition_reserved_size")
Daniel Norman72c626f2019-05-13 15:58:14 -0700695 copy_prop("odm_selinux_fc", "selinux_fc")
Ying Wangb8888432014-03-11 17:13:27 -0700696 elif mount_point == "oem":
697 copy_prop("fs_type", "fs_type")
698 copy_prop("oem_size", "partition_size")
Tao Bao332a96b2018-03-31 10:27:35 -0700699 if not copy_prop("oem_journal_size", "journal_size"):
700 d["journal_size"] = "0"
Patrick Tjina1900842016-10-20 10:58:12 -0700701 copy_prop("oem_extfs_inode_count", "extfs_inode_count")
Mark Salyzynf0cef8d2018-10-29 10:55:06 -0700702 copy_prop("ext4_share_dup_blocks", "ext4_share_dup_blocks")
Patrick Tjin3f5f9932018-03-23 11:36:43 -0700703 if not copy_prop("oem_extfs_rsv_pct", "extfs_rsv_pct"):
704 d["extfs_rsv_pct"] = "0"
Daniel Norman72c626f2019-05-13 15:58:14 -0700705 copy_prop("oem_selinux_fc", "selinux_fc")
David Zeuthen4014a9d2016-09-30 17:29:22 -0400706 d["partition_name"] = mount_point
Ying Wangbd93d422011-10-28 17:02:30 -0700707 return d
708
709
710def LoadGlobalDict(filename):
711 """Load "name=value" pairs from filename"""
712 d = {}
713 f = open(filename)
714 for line in f:
715 line = line.strip()
716 if not line or line.startswith("#"):
717 continue
718 k, v = line.split("=", 1)
719 d[k] = v
720 f.close()
721 return d
722
723
Yifan Hongbbcba1e2018-06-18 16:32:35 -0700724def GlobalDictFromImageProp(image_prop, mount_point):
725 d = {}
726 def copy_prop(src_p, dest_p):
727 if src_p in image_prop:
728 d[dest_p] = image_prop[src_p]
729 return True
730 return False
Tao Bao4251fe92018-07-23 13:05:00 -0700731
Yifan Hongbbcba1e2018-06-18 16:32:35 -0700732 if mount_point == "system":
Tao Bao35f4ebc2018-09-27 15:31:11 -0700733 copy_prop("partition_size", "system_size")
Yifan Hongbbcba1e2018-06-18 16:32:35 -0700734 elif mount_point == "system_other":
Bowgo Tsai867ab662019-01-29 13:30:18 +0800735 copy_prop("partition_size", "system_other_size")
Yifan Hong749062d2018-06-19 16:23:16 -0700736 elif mount_point == "vendor":
Tao Bao35f4ebc2018-09-27 15:31:11 -0700737 copy_prop("partition_size", "vendor_size")
Bowgo Tsaid624fa62017-11-14 23:42:30 +0800738 elif mount_point == "odm":
Tao Bao35f4ebc2018-09-27 15:31:11 -0700739 copy_prop("partition_size", "odm_size")
Yifan Hong56a6c3b2018-07-20 15:19:34 -0700740 elif mount_point == "product":
Tao Bao35f4ebc2018-09-27 15:31:11 -0700741 copy_prop("partition_size", "product_size")
Justin Yun6151e3f2019-06-25 15:58:13 +0900742 elif mount_point == "system_ext":
743 copy_prop("partition_size", "system_ext_size")
Yifan Hongbbcba1e2018-06-18 16:32:35 -0700744 return d
745
746
Ying Wangbd93d422011-10-28 17:02:30 -0700747def main(argv):
Yifan Hong8c3dce02019-04-09 17:03:57 +0000748 if len(argv) != 4:
Tao Baoc72727a2017-12-07 10:33:00 -0800749 print(__doc__)
Ying Wangbd93d422011-10-28 17:02:30 -0700750 sys.exit(1)
751
Tao Bao32fcdab2018-10-12 10:30:39 -0700752 common.InitLogging()
753
Ying Wangbd93d422011-10-28 17:02:30 -0700754 in_dir = argv[0]
755 glob_dict_file = argv[1]
756 out_file = argv[2]
Thierry Strudel74a81e62015-07-09 09:54:55 -0700757 target_out = argv[3]
Ying Wangbd93d422011-10-28 17:02:30 -0700758
759 glob_dict = LoadGlobalDict(glob_dict_file)
Ying Wangae61f502015-03-12 18:30:39 -0700760 if "mount_point" in glob_dict:
Mark Salyzyn780f5952018-10-19 13:44:36 -0700761 # The caller knows the mount point and provides a dictionary needed by
Tao Baoc7a6f1e2015-06-23 11:16:05 -0700762 # BuildImage().
Ying Wangae61f502015-03-12 18:30:39 -0700763 image_properties = glob_dict
Ying Wang9f8e8db2011-11-04 11:37:01 -0700764 else:
Ying Wangae61f502015-03-12 18:30:39 -0700765 image_filename = os.path.basename(out_file)
766 mount_point = ""
767 if image_filename == "system.img":
768 mount_point = "system"
Alex Light4e358ab2016-06-16 14:47:10 -0700769 elif image_filename == "system_other.img":
770 mount_point = "system_other"
Ying Wangae61f502015-03-12 18:30:39 -0700771 elif image_filename == "userdata.img":
772 mount_point = "data"
773 elif image_filename == "cache.img":
774 mount_point = "cache"
775 elif image_filename == "vendor.img":
776 mount_point = "vendor"
Bowgo Tsaid624fa62017-11-14 23:42:30 +0800777 elif image_filename == "odm.img":
778 mount_point = "odm"
Ying Wangae61f502015-03-12 18:30:39 -0700779 elif image_filename == "oem.img":
780 mount_point = "oem"
Jaekyun Seokb7735d82017-11-27 17:04:47 +0900781 elif image_filename == "product.img":
782 mount_point = "product"
Justin Yun6151e3f2019-06-25 15:58:13 +0900783 elif image_filename == "system_ext.img":
784 mount_point = "system_ext"
Ying Wangae61f502015-03-12 18:30:39 -0700785 else:
Tao Bao32fcdab2018-10-12 10:30:39 -0700786 logger.error("Unknown image file name %s", image_filename)
Tao Bao1c830bf2017-12-25 10:43:47 -0800787 sys.exit(1)
Ying Wangbd93d422011-10-28 17:02:30 -0700788
Ying Wangae61f502015-03-12 18:30:39 -0700789 image_properties = ImagePropFromGlobalDict(glob_dict, mount_point)
790
Tao Baoc6bd70a2018-09-27 16:58:00 -0700791 try:
792 BuildImage(in_dir, image_properties, out_file, target_out)
793 except:
Tao Bao32fcdab2018-10-12 10:30:39 -0700794 logger.error("Failed to build %s from %s", out_file, in_dir)
Tao Baoc6bd70a2018-09-27 16:58:00 -0700795 raise
Ying Wangbd93d422011-10-28 17:02:30 -0700796
Tao Bao32fcdab2018-10-12 10:30:39 -0700797
Ying Wangbd93d422011-10-28 17:02:30 -0700798if __name__ == '__main__':
Tao Bao1c830bf2017-12-25 10:43:47 -0800799 try:
800 main(sys.argv[1:])
801 finally:
802 common.Cleanup()