blob: e33b5815cb9f673c15bea08fa97cb3c4d5b2f4c4 [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
Inseob Kim9cda3972021-10-12 22:59:12 +090027import glob
Tao Bao32fcdab2018-10-12 10:30:39 -070028import logging
Ying Wangbd93d422011-10-28 17:02:30 -070029import os
Ying Wang69e9b4d2012-11-26 18:10:23 -080030import os.path
Tao Baoc7a6f1e2015-06-23 11:16:05 -070031import re
Geremy Condrafd6f7512013-06-16 17:26:08 -070032import shutil
Tao Baoc72727a2017-12-07 10:33:00 -080033import sys
34
35import common
Tao Bao71197512018-10-11 14:08:45 -070036import verity_utils
Ying Wangbd93d422011-10-28 17:02:30 -070037
Tao Bao32fcdab2018-10-12 10:30:39 -070038logger = logging.getLogger(__name__)
39
Baligh Uddin601ddea2015-06-09 15:48:14 -070040OPTIONS = common.OPTIONS
Tao Bao71197512018-10-11 14:08:45 -070041BLOCK_SIZE = common.BLOCK_SIZE
Yifan Hongbbcba1e2018-06-18 16:32:35 -070042BYTES_IN_MB = 1024 * 1024
Geremy Condrae8e982a2014-05-16 19:14:30 -070043
Tao Baoc72727a2017-12-07 10:33:00 -080044
Tao Baoc6bd70a2018-09-27 16:58:00 -070045class BuildImageError(Exception):
46 """An Exception raised during image building."""
47
48 def __init__(self, message):
49 Exception.__init__(self, message)
50
51
Yifan Hongbbcba1e2018-06-18 16:32:35 -070052def GetDiskUsage(path):
Tao Baoc6bd70a2018-09-27 16:58:00 -070053 """Returns the number of bytes that "path" occupies on host.
Yifan Hongbbcba1e2018-06-18 16:32:35 -070054
55 Args:
Mark Salyzyn780f5952018-10-19 13:44:36 -070056 path: The directory or file to calculate size on.
Tao Baoc6bd70a2018-09-27 16:58:00 -070057
Yifan Hongbbcba1e2018-06-18 16:32:35 -070058 Returns:
Mark Salyzyn780f5952018-10-19 13:44:36 -070059 The number of bytes based on a 1K block_size.
Yifan Hongbbcba1e2018-06-18 16:32:35 -070060 """
Chirayu Desai96a913e2020-03-27 03:49:31 +053061 cmd = ["du", "-b", "-k", "-s", path]
Tao Baof3fc62c2018-10-25 12:23:12 -070062 output = common.RunAndCheckOutput(cmd, verbose=False)
Mark Salyzyn780f5952018-10-19 13:44:36 -070063 return int(output.split()[0]) * 1024
64
65
66def GetInodeUsage(path):
67 """Returns the number of inodes that "path" occupies on host.
68
69 Args:
70 path: The directory or file to calculate inode number on.
71
72 Returns:
73 The number of inodes used.
Mark Salyzyn780f5952018-10-19 13:44:36 -070074 """
75 cmd = ["find", path, "-print"]
Tao Baof3fc62c2018-10-25 12:23:12 -070076 output = common.RunAndCheckOutput(cmd, verbose=False)
David Anderson203057c2021-03-31 20:01:41 -070077 # increase by > 6% as number of files and directories is not whole picture.
Mark Salyzync25b2bf2019-01-16 08:03:10 -080078 inodes = output.count('\n')
David Anderson203057c2021-03-31 20:01:41 -070079 spare_inodes = inodes * 6 // 100
Mark Salyzyn60fa99d2019-01-16 08:03:10 -080080 min_spare_inodes = 12
Mark Salyzync25b2bf2019-01-16 08:03:10 -080081 if spare_inodes < min_spare_inodes:
82 spare_inodes = min_spare_inodes
83 return inodes + spare_inodes
Mark Salyzyn780f5952018-10-19 13:44:36 -070084
85
Jaegeuk Kim13696542021-05-22 09:47:48 -070086def GetFilesystemCharacteristics(fs_type, image_path, sparse_image=True):
Mark Salyzyn6541d0a2019-01-10 14:30:51 -080087 """Returns various filesystem characteristics of "image_path".
Mark Salyzyn780f5952018-10-19 13:44:36 -070088
89 Args:
Mark Salyzyn6541d0a2019-01-10 14:30:51 -080090 image_path: The file to analyze.
91 sparse_image: Image is sparse
Mark Salyzyn780f5952018-10-19 13:44:36 -070092
93 Returns:
94 The characteristics dictionary.
Mark Salyzyn780f5952018-10-19 13:44:36 -070095 """
Mark Salyzyn6541d0a2019-01-10 14:30:51 -080096 unsparse_image_path = image_path
97 if sparse_image:
98 unsparse_image_path = UnsparseImage(image_path, replace=False)
Mark Salyzyn780f5952018-10-19 13:44:36 -070099
Jaegeuk Kim13696542021-05-22 09:47:48 -0700100 if fs_type.startswith("ext"):
101 cmd = ["tune2fs", "-l", unsparse_image_path]
102 elif fs_type.startswith("f2fs"):
103 cmd = ["fsck.f2fs", "-l", unsparse_image_path]
104
Mark Salyzyn780f5952018-10-19 13:44:36 -0700105 try:
106 output = common.RunAndCheckOutput(cmd, verbose=False)
Tao Baof3fc62c2018-10-25 12:23:12 -0700107 finally:
Mark Salyzyn6541d0a2019-01-10 14:30:51 -0800108 if sparse_image:
109 os.remove(unsparse_image_path)
Tao Baof3fc62c2018-10-25 12:23:12 -0700110 fs_dict = {}
Mark Salyzyn780f5952018-10-19 13:44:36 -0700111 for line in output.splitlines():
112 fields = line.split(":")
113 if len(fields) == 2:
114 fs_dict[fields[0].strip()] = fields[1].strip()
115 return fs_dict
Yifan Hongbbcba1e2018-06-18 16:32:35 -0700116
117
Geremy Condra6e8f53c2013-12-05 17:09:18 -0800118def UnsparseImage(sparse_image_path, replace=True):
Geremy Condrafd6f7512013-06-16 17:26:08 -0700119 img_dir = os.path.dirname(sparse_image_path)
120 unsparse_image_path = "unsparse_" + os.path.basename(sparse_image_path)
121 unsparse_image_path = os.path.join(img_dir, unsparse_image_path)
122 if os.path.exists(unsparse_image_path):
Geremy Condra6e8f53c2013-12-05 17:09:18 -0800123 if replace:
124 os.unlink(unsparse_image_path)
125 else:
Tao Baoc6bd70a2018-09-27 16:58:00 -0700126 return unsparse_image_path
Geremy Condrafd6f7512013-06-16 17:26:08 -0700127 inflate_command = ["simg2img", sparse_image_path, unsparse_image_path]
Tao Bao986ee862018-10-04 15:46:16 -0700128 try:
129 common.RunAndCheckOutput(inflate_command)
130 except:
Geremy Condrafd6f7512013-06-16 17:26:08 -0700131 os.remove(unsparse_image_path)
Tao Bao986ee862018-10-04 15:46:16 -0700132 raise
Tao Baoc6bd70a2018-09-27 16:58:00 -0700133 return unsparse_image_path
Geremy Condrafd6f7512013-06-16 17:26:08 -0700134
Tao Baoc72727a2017-12-07 10:33:00 -0800135
Mohamad Ayyashf8765552016-03-02 21:07:23 -0800136def ConvertBlockMapToBaseFs(block_map_file):
Tao Bao1c830bf2017-12-25 10:43:47 -0800137 base_fs_file = common.MakeTempFile(prefix="script_gen_", suffix=".base_fs")
Mohamad Ayyashf8765552016-03-02 21:07:23 -0800138 convert_command = ["blk_alloc_to_base_fs", block_map_file, base_fs_file]
Tao Bao986ee862018-10-04 15:46:16 -0700139 common.RunAndCheckOutput(convert_command)
Tao Baoc6bd70a2018-09-27 16:58:00 -0700140 return base_fs_file
Mohamad Ayyashf8765552016-03-02 21:07:23 -0800141
Tao Baod4349f22017-12-07 23:01:25 -0800142
Tao Baoc2606eb2018-07-20 14:44:46 -0700143def SetUpInDirAndFsConfig(origin_in, prop_dict):
144 """Returns the in_dir and fs_config that should be used for image building.
145
Tom Cherryd14b8952018-08-09 14:26:00 -0700146 When building system.img for all targets, it creates and returns a staged dir
147 that combines the contents of /system (i.e. in the given in_dir) and root.
Tao Baoc2606eb2018-07-20 14:44:46 -0700148
149 Args:
150 origin_in: Path to the input directory.
151 prop_dict: A property dict that contains info like partition size. Values
152 may be updated.
153
154 Returns:
155 A tuple of in_dir and fs_config that should be used to build the image.
156 """
157 fs_config = prop_dict.get("fs_config")
Tom Cherryd14b8952018-08-09 14:26:00 -0700158
159 if prop_dict["mount_point"] == "system_other":
160 prop_dict["mount_point"] = "system"
161 return origin_in, fs_config
162
163 if prop_dict["mount_point"] != "system":
Tao Baoc2606eb2018-07-20 14:44:46 -0700164 return origin_in, fs_config
165
Mark Salyzyn780f5952018-10-19 13:44:36 -0700166 if "first_pass" in prop_dict:
167 prop_dict["mount_point"] = "/"
168 return prop_dict["first_pass"]
169
Tao Baoc2606eb2018-07-20 14:44:46 -0700170 # Construct a staging directory of the root file system.
171 in_dir = common.MakeTempDir()
172 root_dir = prop_dict.get("root_dir")
173 if root_dir:
174 shutil.rmtree(in_dir)
175 shutil.copytree(root_dir, in_dir, symlinks=True)
176 in_dir_system = os.path.join(in_dir, "system")
177 shutil.rmtree(in_dir_system, ignore_errors=True)
178 shutil.copytree(origin_in, in_dir_system, symlinks=True)
179
180 # Change the mount point to "/".
181 prop_dict["mount_point"] = "/"
182 if fs_config:
183 # We need to merge the fs_config files of system and root.
184 merged_fs_config = common.MakeTempFile(
185 prefix="merged_fs_config", suffix=".txt")
186 with open(merged_fs_config, "w") as fw:
187 if "root_fs_config" in prop_dict:
188 with open(prop_dict["root_fs_config"]) as fr:
189 fw.writelines(fr.readlines())
190 with open(fs_config) as fr:
191 fw.writelines(fr.readlines())
192 fs_config = merged_fs_config
Mark Salyzyn780f5952018-10-19 13:44:36 -0700193 prop_dict["first_pass"] = (in_dir, fs_config)
Tao Baoc2606eb2018-07-20 14:44:46 -0700194 return in_dir, fs_config
195
196
Tao Baod4349f22017-12-07 23:01:25 -0800197def CheckHeadroom(ext4fs_output, prop_dict):
198 """Checks if there's enough headroom space available.
199
200 Headroom is the reserved space on system image (via PRODUCT_SYSTEM_HEADROOM),
201 which is useful for devices with low disk space that have system image
202 variation between builds. The 'partition_headroom' in prop_dict is the size
203 in bytes, while the numbers in 'ext4fs_output' are for 4K-blocks.
204
205 Args:
206 ext4fs_output: The output string from mke2fs command.
207 prop_dict: The property dict.
208
Tao Baod8a953d2018-01-02 21:19:27 -0800209 Raises:
210 AssertionError: On invalid input.
Tao Baoc6bd70a2018-09-27 16:58:00 -0700211 BuildImageError: On check failure.
Tao Baod4349f22017-12-07 23:01:25 -0800212 """
Tao Baod8a953d2018-01-02 21:19:27 -0800213 assert ext4fs_output is not None
214 assert prop_dict.get('fs_type', '').startswith('ext4')
215 assert 'partition_headroom' in prop_dict
216 assert 'mount_point' in prop_dict
217
Tao Baod4349f22017-12-07 23:01:25 -0800218 ext4fs_stats = re.compile(
219 r'Created filesystem with .* (?P<used_blocks>[0-9]+)/'
220 r'(?P<total_blocks>[0-9]+) blocks')
Tao Baoc72727a2017-12-07 10:33:00 -0800221 last_line = ext4fs_output.strip().split('\n')[-1]
222 m = ext4fs_stats.match(last_line)
Tao Baod4349f22017-12-07 23:01:25 -0800223 used_blocks = int(m.groupdict().get('used_blocks'))
224 total_blocks = int(m.groupdict().get('total_blocks'))
Mark Salyzyn780f5952018-10-19 13:44:36 -0700225 headroom_blocks = int(prop_dict['partition_headroom']) // BLOCK_SIZE
Tao Baod4349f22017-12-07 23:01:25 -0800226 adjusted_blocks = total_blocks - headroom_blocks
227 if used_blocks > adjusted_blocks:
Tao Baod8a953d2018-01-02 21:19:27 -0800228 mount_point = prop_dict["mount_point"]
Tao Baoc6bd70a2018-09-27 16:58:00 -0700229 raise BuildImageError(
230 "Error: Not enough room on {} (total: {} blocks, used: {} blocks, "
231 "headroom: {} blocks, available: {} blocks)".format(
232 mount_point, total_blocks, used_blocks, headroom_blocks,
233 adjusted_blocks))
Tao Baod4349f22017-12-07 23:01:25 -0800234
Huang Jianan65527272021-09-08 18:28:32 +0800235def CalculateSizeAndReserved(prop_dict, size):
236 fs_type = prop_dict.get("fs_type", "")
237 partition_headroom = int(prop_dict.get("partition_headroom", 0))
238 # If not specified, give us 16MB margin for GetDiskUsage error ...
239 reserved_size = int(prop_dict.get("partition_reserved_size", BYTES_IN_MB * 16))
240
241 if fs_type == "erofs":
242 reserved_size = int(prop_dict.get("partition_reserved_size", 0))
243 if reserved_size == 0:
244 # give .3% margin or a minimum size for AVB footer
245 return max(size * 1003 // 1000, 256 * 1024)
246
247 if fs_type.startswith("ext4") and partition_headroom > reserved_size:
248 reserved_size = partition_headroom
249
250 return size + reserved_size
Tao Baod4349f22017-12-07 23:01:25 -0800251
Mark Salyzyn3cd24602018-11-07 07:40:31 -0800252def BuildImageMkfs(in_dir, prop_dict, out_file, target_out, fs_config):
253 """Builds a pure image for the files under in_dir and writes it to out_file.
Tao Baoc2606eb2018-07-20 14:44:46 -0700254
Ying Wangbd93d422011-10-28 17:02:30 -0700255 Args:
Tao Baoc2606eb2018-07-20 14:44:46 -0700256 in_dir: Path to input directory.
257 prop_dict: A property dict that contains info like partition size. Values
258 will be updated with computed values.
259 out_file: The output image file.
260 target_out: Path to the TARGET_OUT directory as in Makefile. It actually
261 points to the /system directory under PRODUCT_OUT. fs_config (the one
262 under system/core/libcutils) reads device specific FS config files from
263 there.
Mark Salyzyn3cd24602018-11-07 07:40:31 -0800264 fs_config: The fs_config file that drives the prototype
Ying Wangbd93d422011-10-28 17:02:30 -0700265
Tao Baoc6bd70a2018-09-27 16:58:00 -0700266 Raises:
267 BuildImageError: On build image failures.
Ying Wangbd93d422011-10-28 17:02:30 -0700268 """
269 build_command = []
270 fs_type = prop_dict.get("fs_type", "")
David Anderson94ad5bb2022-03-04 10:57:58 -0800271 run_fsck = None
Daniel Rosenberg6cc2c812019-12-17 17:36:31 -0800272 needs_projid = prop_dict.get("needs_projid", 0)
273 needs_casefold = prop_dict.get("needs_casefold", 0)
Jaegeuk Kimed754fb2020-10-12 19:50:05 -0700274 needs_compress = prop_dict.get("needs_compress", 0)
Geremy Condrafd6f7512013-06-16 17:26:08 -0700275
David Anderson9e95a022021-08-31 21:32:45 -0700276 disable_sparse = "disable_sparse" in prop_dict
David Anderson94ad5bb2022-03-04 10:57:58 -0800277 manual_sparse = False
David Anderson9e95a022021-08-31 21:32:45 -0700278
Ying Wangbd93d422011-10-28 17:02:30 -0700279 if fs_type.startswith("ext"):
Adrien Schildknecht9a072cc2016-11-18 17:06:29 -0800280 build_command = [prop_dict["ext_mkuserimg"]]
David Anderson9e95a022021-08-31 21:32:45 -0700281 if "extfs_sparse_flag" in prop_dict and not disable_sparse:
Ying Wangbd93d422011-10-28 17:02:30 -0700282 build_command.append(prop_dict["extfs_sparse_flag"])
David Anderson94ad5bb2022-03-04 10:57:58 -0800283 run_e2fsck = RunE2fsck
Ying Wangbd93d422011-10-28 17:02:30 -0700284 build_command.extend([in_dir, out_file, fs_type,
285 prop_dict["mount_point"]])
Tao Bao35f4ebc2018-09-27 15:31:11 -0700286 build_command.append(prop_dict["image_size"])
Ying Wangf3b86352014-11-18 18:03:13 -0800287 if "journal_size" in prop_dict:
288 build_command.extend(["-j", prop_dict["journal_size"]])
Doug Zongker850b8072013-12-05 15:54:55 -0800289 if "timestamp" in prop_dict:
290 build_command.extend(["-T", str(prop_dict["timestamp"])])
Ying Wanga2292c92015-03-24 19:07:40 -0700291 if fs_config:
Doug Zongker82822822014-06-16 09:10:55 -0700292 build_command.extend(["-C", fs_config])
Thierry Strudel74a81e62015-07-09 09:54:55 -0700293 if target_out:
294 build_command.extend(["-D", target_out])
Ying Wanga2292c92015-03-24 19:07:40 -0700295 if "block_list" in prop_dict:
296 build_command.extend(["-B", prop_dict["block_list"]])
Mohamad Ayyashf8765552016-03-02 21:07:23 -0800297 if "base_fs_file" in prop_dict:
298 base_fs_file = ConvertBlockMapToBaseFs(prop_dict["base_fs_file"])
Mohamad Ayyashf8765552016-03-02 21:07:23 -0800299 build_command.extend(["-d", base_fs_file])
Christoffer Dall8ed01f32014-12-17 21:34:12 +0100300 build_command.extend(["-L", prop_dict["mount_point"]])
Patrick Tjina1900842016-10-20 10:58:12 -0700301 if "extfs_inode_count" in prop_dict:
302 build_command.extend(["-i", prop_dict["extfs_inode_count"]])
Patrick Tjin3f5f9932018-03-23 11:36:43 -0700303 if "extfs_rsv_pct" in prop_dict:
304 build_command.extend(["-M", prop_dict["extfs_rsv_pct"]])
Connor O'Brien20f08c32017-01-05 16:48:14 -0800305 if "flash_erase_block_size" in prop_dict:
306 build_command.extend(["-e", prop_dict["flash_erase_block_size"]])
307 if "flash_logical_block_size" in prop_dict:
308 build_command.extend(["-o", prop_dict["flash_logical_block_size"]])
Tao Baod86e3112017-09-22 15:45:33 -0700309 # Specify UUID and hash_seed if using mke2fs.
HÃ¥kan Kvist2e1f5272021-05-11 11:14:48 +0200310 if os.path.basename(prop_dict["ext_mkuserimg"]) == "mkuserimg_mke2fs":
Tao Baod86e3112017-09-22 15:45:33 -0700311 if "uuid" in prop_dict:
312 build_command.extend(["-U", prop_dict["uuid"]])
313 if "hash_seed" in prop_dict:
314 build_command.extend(["-S", prop_dict["hash_seed"]])
Tamas Petzc0a8c632020-02-03 15:41:02 +0100315 if prop_dict.get("ext4_share_dup_blocks") == "true":
Jin Qianfde9f792018-01-22 13:15:46 -0800316 build_command.append("-c")
Daniel Rosenberg6cc2c812019-12-17 17:36:31 -0800317 if (needs_projid):
318 build_command.extend(["--inode_size", "512"])
319 else:
320 build_command.extend(["--inode_size", "256"])
Ying Wanga2292c92015-03-24 19:07:40 -0700321 if "selinux_fc" in prop_dict:
Kenny Rootf32dc712012-04-08 10:42:34 -0700322 build_command.append(prop_dict["selinux_fc"])
Gao Xiang961041a2020-06-17 13:59:16 +0800323 elif fs_type.startswith("erofs"):
David Anderson94ad5bb2022-03-04 10:57:58 -0800324 build_command = ["mkfs.erofs"]
325
David Anderson40a821f2021-09-22 18:02:01 -0700326 compressor = None
327 if "erofs_default_compressor" in prop_dict:
328 compressor = prop_dict["erofs_default_compressor"]
329 if "erofs_compressor" in prop_dict:
330 compressor = prop_dict["erofs_compressor"]
331 if compressor:
332 build_command.extend(["-z", compressor])
David Anderson94ad5bb2022-03-04 10:57:58 -0800333
334 build_command.extend(["--mount-point", prop_dict["mount_point"]])
335 if target_out:
336 build_command.extend(["--product-out", target_out])
337 if fs_config:
338 build_command.extend(["--fs-config-file", fs_config])
339 if "selinux_fc" in prop_dict:
340 build_command.extend(["--file-contexts", prop_dict["selinux_fc"]])
David Andersond29e5372021-10-08 18:33:43 -0700341 if "timestamp" in prop_dict:
342 build_command.extend(["-T", str(prop_dict["timestamp"])])
343 if "uuid" in prop_dict:
344 build_command.extend(["-U", prop_dict["uuid"]])
345 if "block_list" in prop_dict:
David Anderson94ad5bb2022-03-04 10:57:58 -0800346 build_command.extend(["--block-list-file", prop_dict["block_list"]])
David Anderson64b351b2021-10-13 00:20:43 -0700347 if "erofs_pcluster_size" in prop_dict:
David Anderson94ad5bb2022-03-04 10:57:58 -0800348 build_command.extend(["-C", prop_dict["erofs_pcluster_size"]])
David Anderson64b351b2021-10-13 00:20:43 -0700349 if "erofs_share_dup_blocks" in prop_dict:
David Anderson94ad5bb2022-03-04 10:57:58 -0800350 build_command.extend(["--chunksize", "4096"])
351
352 build_command.extend([out_file, in_dir])
353 if "erofs_sparse_flag" in prop_dict and not disable_sparse:
354 manual_sparse = True
355
356 run_fsck = RunErofsFsck
Mohamad Ayyashb97746e2015-03-03 12:30:37 -0800357 elif fs_type.startswith("squash"):
358 build_command = ["mksquashfsimage.sh"]
359 build_command.extend([in_dir, out_file])
David Anderson9e95a022021-08-31 21:32:45 -0700360 if "squashfs_sparse_flag" in prop_dict and not disable_sparse:
Todd Poynorb2a555e2015-12-15 18:00:14 -0800361 build_command.extend([prop_dict["squashfs_sparse_flag"]])
Mohamad Ayyashb97746e2015-03-03 12:30:37 -0800362 build_command.extend(["-m", prop_dict["mount_point"]])
Thierry Strudel74a81e62015-07-09 09:54:55 -0700363 if target_out:
364 build_command.extend(["-d", target_out])
Mohamad Ayyash88378822016-04-07 22:10:51 -0700365 if fs_config:
366 build_command.extend(["-C", fs_config])
Ying Wanga2292c92015-03-24 19:07:40 -0700367 if "selinux_fc" in prop_dict:
Mohamad Ayyashb97746e2015-03-03 12:30:37 -0800368 build_command.extend(["-c", prop_dict["selinux_fc"]])
Mohamad Ayyashc3484f72016-06-13 09:46:58 -0700369 if "block_list" in prop_dict:
370 build_command.extend(["-B", prop_dict["block_list"]])
Ng Zhi An9446c1d2018-01-19 15:51:46 -0800371 if "squashfs_block_size" in prop_dict:
372 build_command.extend(["-b", prop_dict["squashfs_block_size"]])
Simon Wilsonf86e7ee2015-06-17 12:35:15 -0700373 if "squashfs_compressor" in prop_dict:
374 build_command.extend(["-z", prop_dict["squashfs_compressor"]])
375 if "squashfs_compressor_opt" in prop_dict:
376 build_command.extend(["-zo", prop_dict["squashfs_compressor_opt"]])
Tao Baoc72727a2017-12-07 10:33:00 -0800377 if prop_dict.get("squashfs_disable_4k_align") == "true":
Mohamad Ayyash1b6d3482016-06-15 15:53:07 -0700378 build_command.extend(["-a"])
JP Abgrall5bfed5a2014-06-16 14:17:40 -0700379 elif fs_type.startswith("f2fs"):
380 build_command = ["mkf2fsuserimg.sh"]
Tao Bao35f4ebc2018-09-27 15:31:11 -0700381 build_command.extend([out_file, prop_dict["image_size"]])
David Anderson9e95a022021-08-31 21:32:45 -0700382 if "f2fs_sparse_flag" in prop_dict and not disable_sparse:
Alistair Delva91238cc2019-10-16 10:53:41 -0700383 build_command.extend([prop_dict["f2fs_sparse_flag"]])
Jaegeuk Kim2ea1eba2017-11-28 19:21:28 -0800384 if fs_config:
385 build_command.extend(["-C", fs_config])
386 build_command.extend(["-f", in_dir])
387 if target_out:
388 build_command.extend(["-D", target_out])
389 if "selinux_fc" in prop_dict:
390 build_command.extend(["-s", prop_dict["selinux_fc"]])
391 build_command.extend(["-t", prop_dict["mount_point"]])
392 if "timestamp" in prop_dict:
393 build_command.extend(["-T", str(prop_dict["timestamp"])])
Jaegeuk Kim3dc47282021-06-13 08:54:01 -0700394 if "block_list" in prop_dict:
395 build_command.extend(["-B", prop_dict["block_list"]])
Jaegeuk Kim2ea1eba2017-11-28 19:21:28 -0800396 build_command.extend(["-L", prop_dict["mount_point"]])
Daniel Rosenberg6cc2c812019-12-17 17:36:31 -0800397 if (needs_projid):
398 build_command.append("--prjquota")
399 if (needs_casefold):
400 build_command.append("--casefold")
Jaegeuk Kim13696542021-05-22 09:47:48 -0700401 if (needs_compress or prop_dict.get("f2fs_compress") == "true"):
Jaegeuk Kimed754fb2020-10-12 19:50:05 -0700402 build_command.append("--compression")
Jaegeuk Kim3dc47282021-06-13 08:54:01 -0700403 if (prop_dict.get("mount_point") != "data"):
Jaegeuk Kim46e0ea22021-05-20 23:13:59 -0700404 build_command.append("--readonly")
Jaegeuk Kim3dc47282021-06-13 08:54:01 -0700405 if (prop_dict.get("f2fs_compress") == "true"):
Robin Hsu3e51f422020-11-04 09:29:09 +0800406 build_command.append("--sldc")
Jaegeuk Kim13696542021-05-22 09:47:48 -0700407 if (prop_dict.get("f2fs_sldc_flags") == None):
Robin Hsu3e51f422020-11-04 09:29:09 +0800408 build_command.append(str(0))
409 else:
Jaegeuk Kim13696542021-05-22 09:47:48 -0700410 sldc_flags_str = prop_dict.get("f2fs_sldc_flags")
Robin Hsu3e51f422020-11-04 09:29:09 +0800411 sldc_flags = sldc_flags_str.split()
412 build_command.append(str(len(sldc_flags)))
413 build_command.extend(sldc_flags)
Ying Wangbd93d422011-10-28 17:02:30 -0700414 else:
Tao Baoc6bd70a2018-09-27 16:58:00 -0700415 raise BuildImageError(
416 "Error: unknown filesystem type: {}".format(fs_type))
Ying Wangbd93d422011-10-28 17:02:30 -0700417
Tao Bao986ee862018-10-04 15:46:16 -0700418 try:
419 mkfs_output = common.RunAndCheckOutput(build_command)
420 except:
Tao Baoc6bd70a2018-09-27 16:58:00 -0700421 try:
422 du = GetDiskUsage(in_dir)
423 du_str = "{} bytes ({} MB)".format(du, du // BYTES_IN_MB)
Tao Bao986ee862018-10-04 15:46:16 -0700424 # Suppress any errors from GetDiskUsage() to avoid hiding the real errors
425 # from common.RunAndCheckOutput().
Tao Bao32fcdab2018-10-12 10:30:39 -0700426 except Exception: # pylint: disable=broad-except
427 logger.exception("Failed to compute disk usage with du")
Tao Baoc6bd70a2018-09-27 16:58:00 -0700428 du_str = "unknown"
Tao Bao4251fe92018-07-23 13:05:00 -0700429 print(
Mark Salyzyn3cd24602018-11-07 07:40:31 -0800430 "Out of space? Out of inodes? The tree size of {} is {}, "
431 "with reserved space of {} bytes ({} MB).".format(
Tao Baoc2606eb2018-07-20 14:44:46 -0700432 in_dir, du_str,
Tao Bao4251fe92018-07-23 13:05:00 -0700433 int(prop_dict.get("partition_reserved_size", 0)),
434 int(prop_dict.get("partition_reserved_size", 0)) // BYTES_IN_MB))
Huang Jiananf63abb12021-04-29 15:24:50 +0800435 if ("image_size" in prop_dict and "partition_size" in prop_dict):
436 print(
437 "The max image size for filesystem files is {} bytes ({} MB), "
438 "out of a total partition size of {} bytes ({} MB).".format(
439 int(prop_dict["image_size"]),
440 int(prop_dict["image_size"]) // BYTES_IN_MB,
441 int(prop_dict["partition_size"]),
442 int(prop_dict["partition_size"]) // BYTES_IN_MB))
Tao Bao986ee862018-10-04 15:46:16 -0700443 raise
Ying Wang69e9b4d2012-11-26 18:10:23 -0800444
David Anderson94ad5bb2022-03-04 10:57:58 -0800445 if run_fsck and prop_dict.get("skip_fsck") != "true":
446 run_fsck(out_file)
Mark Salyzyn3cd24602018-11-07 07:40:31 -0800447
David Anderson94ad5bb2022-03-04 10:57:58 -0800448 if manual_sparse:
449 temp_file = out_file + ".sparse"
450 img2simg_argv = ["img2simg", out_file, temp_file]
451 common.RunAndCheckOutput(img2simg_argv)
452 os.rename(temp_file, out_file)
Mark Salyzyn3cd24602018-11-07 07:40:31 -0800453
454 return mkfs_output
455
David Anderson94ad5bb2022-03-04 10:57:58 -0800456
457def RunE2fsck(out_file):
458 unsparse_image = UnsparseImage(out_file, replace=False)
459
460 # Run e2fsck on the inflated image file
461 e2fsck_command = ["e2fsck", "-f", "-n", unsparse_image]
462 try:
463 common.RunAndCheckOutput(e2fsck_command)
464 finally:
465 os.remove(unsparse_image)
466
467
468def RunErofsFsck(out_file):
469 fsck_command = ["fsck.erofs", "--extract", out_file]
470 try:
471 common.RunAndCheckOutput(fsck_command)
472 except:
473 print("Check failed for EROFS image {}".format(out_file))
474 raise
475
476
Mark Salyzyn3cd24602018-11-07 07:40:31 -0800477def BuildImage(in_dir, prop_dict, out_file, target_out=None):
478 """Builds an image for the files under in_dir and writes it to out_file.
479
480 Args:
481 in_dir: Path to input directory.
482 prop_dict: A property dict that contains info like partition size. Values
483 will be updated with computed values.
484 out_file: The output image file.
485 target_out: Path to the TARGET_OUT directory as in Makefile. It actually
486 points to the /system directory under PRODUCT_OUT. fs_config (the one
487 under system/core/libcutils) reads device specific FS config files from
488 there.
489
490 Raises:
491 BuildImageError: On build image failures.
492 """
493 in_dir, fs_config = SetUpInDirAndFsConfig(in_dir, prop_dict)
494
495 build_command = []
496 fs_type = prop_dict.get("fs_type", "")
497
498 fs_spans_partition = True
Huang Jianan62d926e2020-12-04 16:53:06 +0800499 if fs_type.startswith("squash") or fs_type.startswith("erofs"):
Mark Salyzyn3cd24602018-11-07 07:40:31 -0800500 fs_spans_partition = False
Jaegeuk Kim13696542021-05-22 09:47:48 -0700501 elif fs_type.startswith("f2fs") and prop_dict.get("f2fs_compress") == "true":
502 fs_spans_partition = False
Mark Salyzyn3cd24602018-11-07 07:40:31 -0800503
504 # Get a builder for creating an image that's to be verified by Verified Boot,
505 # or None if not applicable.
506 verity_image_builder = verity_utils.CreateVerityImageBuilder(prop_dict)
507
David Anderson9e95a022021-08-31 21:32:45 -0700508 disable_sparse = "disable_sparse" in prop_dict
Huang Jiananffa1d572021-09-08 18:11:22 +0800509 mkfs_output = None
Mark Salyzyn3cd24602018-11-07 07:40:31 -0800510 if (prop_dict.get("use_dynamic_partition_size") == "true" and
511 "partition_size" not in prop_dict):
512 # If partition_size is not defined, use output of `du' + reserved_size.
Huang Jianan35f015e2020-12-04 16:58:24 +0800513 # For compressed file system, it's better to use the compressed size to avoid wasting space.
514 if fs_type.startswith("erofs"):
Huang Jiananffa1d572021-09-08 18:11:22 +0800515 mkfs_output = BuildImageMkfs(in_dir, prop_dict, out_file, target_out, fs_config)
516 if "erofs_sparse_flag" in prop_dict and not disable_sparse:
517 image_path = UnsparseImage(out_file, replace=False)
518 size = GetDiskUsage(image_path)
519 os.remove(image_path)
520 else:
521 size = GetDiskUsage(out_file)
Huang Jianan35f015e2020-12-04 16:58:24 +0800522 else:
523 size = GetDiskUsage(in_dir)
Mark Salyzyn3cd24602018-11-07 07:40:31 -0800524 logger.info(
525 "The tree size of %s is %d MB.", in_dir, size // BYTES_IN_MB)
Huang Jianan65527272021-09-08 18:28:32 +0800526 size = CalculateSizeAndReserved(prop_dict, size)
Mark Salyzyn3cd24602018-11-07 07:40:31 -0800527 # Round this up to a multiple of 4K so that avbtool works
528 size = common.RoundUpTo4K(size)
529 if fs_type.startswith("ext"):
530 prop_dict["partition_size"] = str(size)
531 prop_dict["image_size"] = str(size)
532 if "extfs_inode_count" not in prop_dict:
533 prop_dict["extfs_inode_count"] = str(GetInodeUsage(in_dir))
534 logger.info(
535 "First Pass based on estimates of %d MB and %s inodes.",
536 size // BYTES_IN_MB, prop_dict["extfs_inode_count"])
537 BuildImageMkfs(in_dir, prop_dict, out_file, target_out, fs_config)
Mark Salyzyn6541d0a2019-01-10 14:30:51 -0800538 sparse_image = False
David Anderson9e95a022021-08-31 21:32:45 -0700539 if "extfs_sparse_flag" in prop_dict and not disable_sparse:
Mark Salyzyn6541d0a2019-01-10 14:30:51 -0800540 sparse_image = True
Jaegeuk Kim13696542021-05-22 09:47:48 -0700541 fs_dict = GetFilesystemCharacteristics(fs_type, out_file, sparse_image)
Mark Salyzyn3cd24602018-11-07 07:40:31 -0800542 os.remove(out_file)
543 block_size = int(fs_dict.get("Block size", "4096"))
544 free_size = int(fs_dict.get("Free blocks", "0")) * block_size
545 reserved_size = int(prop_dict.get("partition_reserved_size", 0))
546 partition_headroom = int(fs_dict.get("partition_headroom", 0))
547 if fs_type.startswith("ext4") and partition_headroom > reserved_size:
548 reserved_size = partition_headroom
549 if free_size <= reserved_size:
550 logger.info(
551 "Not worth reducing image %d <= %d.", free_size, reserved_size)
552 else:
553 size -= free_size
554 size += reserved_size
Mark Salyzyn60a716f2019-01-10 08:36:34 -0800555 if reserved_size == 0:
Mark Salyzync25b2bf2019-01-16 08:03:10 -0800556 # add .3% margin
557 size = size * 1003 // 1000
Mark Salyzyn60a716f2019-01-10 08:36:34 -0800558 # Use a minimum size, otherwise we will fail to calculate an AVB footer
559 # or fail to construct an ext4 image.
560 size = max(size, 256 * 1024)
Mark Salyzyn3cd24602018-11-07 07:40:31 -0800561 if block_size <= 4096:
562 size = common.RoundUpTo4K(size)
563 else:
564 size = ((size + block_size - 1) // block_size) * block_size
565 extfs_inode_count = prop_dict["extfs_inode_count"]
566 inodes = int(fs_dict.get("Inode count", extfs_inode_count))
567 inodes -= int(fs_dict.get("Free inodes", "0"))
Mark Salyzync25b2bf2019-01-16 08:03:10 -0800568 # add .2% margin or 1 inode, whichever is greater
569 spare_inodes = inodes * 2 // 1000
570 min_spare_inodes = 1
571 if spare_inodes < min_spare_inodes:
572 spare_inodes = min_spare_inodes
573 inodes += spare_inodes
Mark Salyzyn3cd24602018-11-07 07:40:31 -0800574 prop_dict["extfs_inode_count"] = str(inodes)
575 prop_dict["partition_size"] = str(size)
576 logger.info(
577 "Allocating %d Inodes for %s.", inodes, out_file)
Jaegeuk Kim13696542021-05-22 09:47:48 -0700578 elif fs_type.startswith("f2fs") and prop_dict.get("f2fs_compress") == "true":
579 prop_dict["partition_size"] = str(size)
580 prop_dict["image_size"] = str(size)
581 BuildImageMkfs(in_dir, prop_dict, out_file, target_out, fs_config)
582 sparse_image = False
David Anderson9e95a022021-08-31 21:32:45 -0700583 if "f2fs_sparse_flag" in prop_dict and not disable_sparse:
Jaegeuk Kim13696542021-05-22 09:47:48 -0700584 sparse_image = True
585 fs_dict = GetFilesystemCharacteristics(fs_type, out_file, sparse_image)
586 os.remove(out_file)
587 block_count = int(fs_dict.get("block_count", "0"))
588 log_blocksize = int(fs_dict.get("log_blocksize", "12"))
589 size = block_count << log_blocksize
590 prop_dict["partition_size"] = str(size)
Mark Salyzyn3cd24602018-11-07 07:40:31 -0800591 if verity_image_builder:
592 size = verity_image_builder.CalculateDynamicPartitionSize(size)
593 prop_dict["partition_size"] = str(size)
594 logger.info(
595 "Allocating %d MB for %s.", size // BYTES_IN_MB, out_file)
596
597 prop_dict["image_size"] = prop_dict["partition_size"]
598
599 # Adjust the image size to make room for the hashes if this is to be verified.
600 if verity_image_builder:
601 max_image_size = verity_image_builder.CalculateMaxImageSize()
602 prop_dict["image_size"] = str(max_image_size)
603
Huang Jiananffa1d572021-09-08 18:11:22 +0800604 if not mkfs_output:
605 mkfs_output = BuildImageMkfs(in_dir, prop_dict, out_file, target_out, fs_config)
Mark Salyzyn3cd24602018-11-07 07:40:31 -0800606
David Anderson009d6f82021-11-12 02:01:29 +0000607 # Update the image (eg filesystem size). This can be different eg if mkfs
608 # rounds the requested size down due to alignment.
609 prop_dict["image_size"] = common.sparse_img.GetImagePartitionSize(out_file)
610
Tao Baod4349f22017-12-07 23:01:25 -0800611 # Check if there's enough headroom space available for ext4 image.
Tao Bao79d52f82017-12-07 14:07:44 -0800612 if "partition_headroom" in prop_dict and fs_type.startswith("ext4"):
Tao Baoc6bd70a2018-09-27 16:58:00 -0700613 CheckHeadroom(mkfs_output, prop_dict)
Tao Baoc7a6f1e2015-06-23 11:16:05 -0700614
Tao Bao7549e5e2018-10-03 14:23:59 -0700615 if not fs_spans_partition and verity_image_builder:
616 verity_image_builder.PadSparseImage(out_file)
Mohamad Ayyashdd063522015-03-24 12:42:03 -0700617
Tao Baoc72727a2017-12-07 10:33:00 -0800618 # Create the verified image if this is to be verified.
Tao Bao7549e5e2018-10-03 14:23:59 -0700619 if verity_image_builder:
620 verity_image_builder.Build(out_file)
David Zeuthen4014a9d2016-09-30 17:29:22 -0400621
Ying Wangbd93d422011-10-28 17:02:30 -0700622def ImagePropFromGlobalDict(glob_dict, mount_point):
623 """Build an image property dictionary from the global dictionary.
624
625 Args:
626 glob_dict: the global dictionary from the build system.
627 mount_point: such as "system", "data" etc.
628 """
Doug Zongker1ad7ade2013-12-06 11:53:27 -0800629 d = {}
Tao Bao052ae352015-09-28 13:44:13 -0700630
Tao Bao822f5842015-09-30 16:01:14 -0700631 if "build.prop" in glob_dict:
Tianjie Xu0fde41e2020-05-09 05:24:18 +0000632 timestamp = glob_dict["build.prop"].GetProp("ro.build.date.utc")
633 if timestamp:
634 d["timestamp"] = timestamp
Ying Wang9f8e8db2011-11-04 11:37:01 -0700635
636 def copy_prop(src_p, dest_p):
Patrick Tjin3f5f9932018-03-23 11:36:43 -0700637 """Copy a property from the global dictionary.
638
639 Args:
640 src_p: The source property in the global dictionary.
641 dest_p: The destination property.
642 Returns:
643 True if property was found and copied, False otherwise.
644 """
Ying Wang9f8e8db2011-11-04 11:37:01 -0700645 if src_p in glob_dict:
646 d[dest_p] = str(glob_dict[src_p])
Patrick Tjin3f5f9932018-03-23 11:36:43 -0700647 return True
648 return False
Ying Wang9f8e8db2011-11-04 11:37:01 -0700649
Ying Wangbd93d422011-10-28 17:02:30 -0700650 common_props = (
Ying Wangbd93d422011-10-28 17:02:30 -0700651 "extfs_sparse_flag",
David Anderson40a821f2021-09-22 18:02:01 -0700652 "erofs_default_compressor",
David Anderson64b351b2021-10-13 00:20:43 -0700653 "erofs_pcluster_size",
654 "erofs_share_dup_blocks",
Gao Xiang961041a2020-06-17 13:59:16 +0800655 "erofs_sparse_flag",
Todd Poynorb2a555e2015-12-15 18:00:14 -0800656 "squashfs_sparse_flag",
Jaegeuk Kim13696542021-05-22 09:47:48 -0700657 "system_f2fs_compress",
Robin Hsu3e51f422020-11-04 09:29:09 +0800658 "system_f2fs_sldc_flags",
Alistair Delva91238cc2019-10-16 10:53:41 -0700659 "f2fs_sparse_flag",
Ying Wang6a42a252013-02-27 13:54:02 -0800660 "skip_fsck",
Adrien Schildknecht9a072cc2016-11-18 17:06:29 -0800661 "ext_mkuserimg",
Geremy Condrafd6f7512013-06-16 17:26:08 -0700662 "verity",
Geremy Condrafd6f7512013-06-16 17:26:08 -0700663 "verity_key",
Sami Tolvanenf99b5312015-05-20 07:30:57 +0100664 "verity_signer_cmd",
David Zeuthen4014a9d2016-09-30 17:29:22 -0400665 "verity_fec",
Bowgo Tsai6ceeb1a2017-10-11 16:21:48 +0800666 "verity_disable",
Bowgo Tsai3e599ea2017-05-26 18:30:04 +0800667 "avb_enable",
Tao Bao2b6dfd62017-09-27 17:17:43 -0700668 "avb_avbtool",
Yifan Hong2dae5722018-07-31 12:47:27 -0700669 "use_dynamic_partition_size",
Tao Bao2b6dfd62017-09-27 17:17:43 -0700670 )
Ying Wangbd93d422011-10-28 17:02:30 -0700671 for p in common_props:
Ying Wang9f8e8db2011-11-04 11:37:01 -0700672 copy_prop(p, p)
Ying Wangbd93d422011-10-28 17:02:30 -0700673
David Anderson271dab62021-10-11 17:31:26 -0700674 ro_mount_points = set([
675 "odm",
676 "odm_dlkm",
677 "oem",
678 "product",
679 "system",
Ramji Jiyani13a41372022-01-27 07:05:08 +0000680 "system_dlkm",
David Anderson271dab62021-10-11 17:31:26 -0700681 "system_ext",
682 "system_other",
683 "vendor",
684 "vendor_dlkm",
685 ])
David Andersonaac502f2021-09-23 15:48:29 -0700686
David Anderson271dab62021-10-11 17:31:26 -0700687 # Tuple layout: (readonly, specific prop, general prop)
688 fmt_props = (
689 # Generic first, then specific file type.
690 (False, "fs_type", "fs_type"),
691 (False, "{}_fs_type", "fs_type"),
692
693 # Ordering for these doesn't matter.
694 (False, "{}_selinux_fc", "selinux_fc"),
695 (False, "{}_size", "partition_size"),
696 (True, "avb_{}_add_hashtree_footer_args", "avb_add_hashtree_footer_args"),
697 (True, "avb_{}_algorithm", "avb_algorithm"),
698 (True, "avb_{}_hashtree_enable", "avb_hashtree_enable"),
699 (True, "avb_{}_key_path", "avb_key_path"),
700 (True, "avb_{}_salt", "avb_salt"),
701 (True, "ext4_share_dup_blocks", "ext4_share_dup_blocks"),
702 (True, "{}_base_fs_file", "base_fs_file"),
703 (True, "{}_disable_sparse", "disable_sparse"),
704 (True, "{}_erofs_compressor", "erofs_compressor"),
David Anderson64b351b2021-10-13 00:20:43 -0700705 (True, "{}_erofs_pcluster_size", "erofs_pcluster_size"),
706 (True, "{}_erofs_share_dup_blocks", "erofs_share_dup_blocks"),
David Anderson271dab62021-10-11 17:31:26 -0700707 (True, "{}_extfs_inode_count", "extfs_inode_count"),
708 (True, "{}_f2fs_compress", "f2fs_compress"),
709 (True, "{}_f2fs_sldc_flags", "f2fs_sldc_flags"),
710 (True, "{}_reserved_size", "partition_reserved_size"),
711 (True, "{}_squashfs_block_size", "squashfs_block_size"),
712 (True, "{}_squashfs_compressor", "squashfs_compressor"),
713 (True, "{}_squashfs_compressor_opt", "squashfs_compressor_opt"),
714 (True, "{}_squashfs_disable_4k_align", "squashfs_disable_4k_align"),
715 (True, "{}_verity_block_device", "verity_block_device"),
716 )
717
718 # Translate prefixed properties into generic ones.
719 if mount_point == "data":
720 prefix = "userdata"
721 else:
722 prefix = mount_point
723
724 for readonly, src_prop, dest_prop in fmt_props:
725 if readonly and mount_point not in ro_mount_points:
726 continue
727
728 if src_prop == "fs_type":
729 # This property is legacy and only used on a few partitions. b/202600377
730 allowed_partitions = set(["system", "system_other", "data", "oem"])
731 if mount_point not in allowed_partitions:
732 continue
733
Po Hu1c48b592022-02-18 09:10:22 +0000734 if (mount_point == "system_other") and (dest_prop != "partition_size"):
David Anderson271dab62021-10-11 17:31:26 -0700735 # Propagate system properties to system_other. They'll get overridden
736 # after as needed.
737 copy_prop(src_prop.format("system"), dest_prop)
738
739 copy_prop(src_prop.format(prefix), dest_prop)
740
741 # Set prefixed properties that need a default value.
742 if mount_point in ro_mount_points:
743 prop = "{}_journal_size".format(prefix)
744 if not copy_prop(prop, "journal_size"):
745 d["journal_size"] = "0"
746
747 prop = "{}_extfs_rsv_pct".format(prefix)
748 if not copy_prop(prop, "extfs_rsv_pct"):
749 d["extfs_rsv_pct"] = "0"
750
751 # Copy partition-specific properties.
Ying Wangbd93d422011-10-28 17:02:30 -0700752 d["mount_point"] = mount_point
753 if mount_point == "system":
Julius D'souza001c6762017-05-03 13:43:27 -0700754 copy_prop("system_headroom", "partition_headroom")
Tao Baof3282b42015-04-01 11:21:55 -0700755 copy_prop("system_root_image", "system_root_image")
Tao Bao8bfd3c72018-07-20 15:20:28 -0700756 copy_prop("root_dir", "root_dir")
757 copy_prop("root_fs_config", "root_fs_config")
Ying Wangbd93d422011-10-28 17:02:30 -0700758 elif mount_point == "data":
JP Abgrall5bfed5a2014-06-16 14:17:40 -0700759 # Copy the generic fs type first, override with specific one if available.
Tao Baoc72727a2017-12-07 10:33:00 -0800760 copy_prop("flash_logical_block_size", "flash_logical_block_size")
Connor O'Brien20f08c32017-01-05 16:48:14 -0800761 copy_prop("flash_erase_block_size", "flash_erase_block_size")
Daniel Rosenberg6cc2c812019-12-17 17:36:31 -0800762 copy_prop("needs_casefold", "needs_casefold")
763 copy_prop("needs_projid", "needs_projid")
Jaegeuk Kimed754fb2020-10-12 19:50:05 -0700764 copy_prop("needs_compress", "needs_compress")
David Zeuthen4014a9d2016-09-30 17:29:22 -0400765 d["partition_name"] = mount_point
Ying Wangbd93d422011-10-28 17:02:30 -0700766 return d
767
768
769def LoadGlobalDict(filename):
770 """Load "name=value" pairs from filename"""
771 d = {}
772 f = open(filename)
773 for line in f:
774 line = line.strip()
775 if not line or line.startswith("#"):
776 continue
777 k, v = line.split("=", 1)
778 d[k] = v
779 f.close()
780 return d
781
782
Yifan Hongbbcba1e2018-06-18 16:32:35 -0700783def GlobalDictFromImageProp(image_prop, mount_point):
784 d = {}
785 def copy_prop(src_p, dest_p):
786 if src_p in image_prop:
787 d[dest_p] = image_prop[src_p]
788 return True
789 return False
Tao Bao4251fe92018-07-23 13:05:00 -0700790
Yifan Hongbbcba1e2018-06-18 16:32:35 -0700791 if mount_point == "system":
Tao Bao35f4ebc2018-09-27 15:31:11 -0700792 copy_prop("partition_size", "system_size")
Yifan Hongbbcba1e2018-06-18 16:32:35 -0700793 elif mount_point == "system_other":
Bowgo Tsai867ab662019-01-29 13:30:18 +0800794 copy_prop("partition_size", "system_other_size")
Yifan Hong749062d2018-06-19 16:23:16 -0700795 elif mount_point == "vendor":
Tao Bao35f4ebc2018-09-27 15:31:11 -0700796 copy_prop("partition_size", "vendor_size")
Bowgo Tsaid624fa62017-11-14 23:42:30 +0800797 elif mount_point == "odm":
Tao Bao35f4ebc2018-09-27 15:31:11 -0700798 copy_prop("partition_size", "odm_size")
Yifan Hongcfb917a2020-05-07 14:58:20 -0700799 elif mount_point == "vendor_dlkm":
800 copy_prop("partition_size", "vendor_dlkm_size")
Yifan Hongf496f1b2020-07-15 16:52:59 -0700801 elif mount_point == "odm_dlkm":
802 copy_prop("partition_size", "odm_dlkm_size")
Ramji Jiyani13a41372022-01-27 07:05:08 +0000803 elif mount_point == "system_dlkm":
804 copy_prop("partition_size", "system_dlkm_size")
Yifan Hong56a6c3b2018-07-20 15:19:34 -0700805 elif mount_point == "product":
Tao Bao35f4ebc2018-09-27 15:31:11 -0700806 copy_prop("partition_size", "product_size")
Justin Yun6151e3f2019-06-25 15:58:13 +0900807 elif mount_point == "system_ext":
808 copy_prop("partition_size", "system_ext_size")
Yifan Hongbbcba1e2018-06-18 16:32:35 -0700809 return d
810
811
Ying Wangbd93d422011-10-28 17:02:30 -0700812def main(argv):
Yifan Hong8c3dce02019-04-09 17:03:57 +0000813 if len(argv) != 4:
Tao Baoc72727a2017-12-07 10:33:00 -0800814 print(__doc__)
Ying Wangbd93d422011-10-28 17:02:30 -0700815 sys.exit(1)
816
Tao Bao32fcdab2018-10-12 10:30:39 -0700817 common.InitLogging()
818
Ying Wangbd93d422011-10-28 17:02:30 -0700819 in_dir = argv[0]
820 glob_dict_file = argv[1]
821 out_file = argv[2]
Thierry Strudel74a81e62015-07-09 09:54:55 -0700822 target_out = argv[3]
Ying Wangbd93d422011-10-28 17:02:30 -0700823
824 glob_dict = LoadGlobalDict(glob_dict_file)
Ying Wangae61f502015-03-12 18:30:39 -0700825 if "mount_point" in glob_dict:
Mark Salyzyn780f5952018-10-19 13:44:36 -0700826 # The caller knows the mount point and provides a dictionary needed by
Tao Baoc7a6f1e2015-06-23 11:16:05 -0700827 # BuildImage().
Ying Wangae61f502015-03-12 18:30:39 -0700828 image_properties = glob_dict
Ying Wang9f8e8db2011-11-04 11:37:01 -0700829 else:
Ying Wangae61f502015-03-12 18:30:39 -0700830 image_filename = os.path.basename(out_file)
831 mount_point = ""
832 if image_filename == "system.img":
833 mount_point = "system"
Alex Light4e358ab2016-06-16 14:47:10 -0700834 elif image_filename == "system_other.img":
835 mount_point = "system_other"
Ying Wangae61f502015-03-12 18:30:39 -0700836 elif image_filename == "userdata.img":
837 mount_point = "data"
838 elif image_filename == "cache.img":
839 mount_point = "cache"
840 elif image_filename == "vendor.img":
841 mount_point = "vendor"
Bowgo Tsaid624fa62017-11-14 23:42:30 +0800842 elif image_filename == "odm.img":
843 mount_point = "odm"
Yifan Hongcfb917a2020-05-07 14:58:20 -0700844 elif image_filename == "vendor_dlkm.img":
845 mount_point = "vendor_dlkm"
Yifan Hongf496f1b2020-07-15 16:52:59 -0700846 elif image_filename == "odm_dlkm.img":
847 mount_point = "odm_dlkm"
Ramji Jiyani13a41372022-01-27 07:05:08 +0000848 elif image_filename == "system_dlkm.img":
849 mount_point = "system_dlkm"
Ying Wangae61f502015-03-12 18:30:39 -0700850 elif image_filename == "oem.img":
851 mount_point = "oem"
Jaekyun Seokb7735d82017-11-27 17:04:47 +0900852 elif image_filename == "product.img":
853 mount_point = "product"
Justin Yun6151e3f2019-06-25 15:58:13 +0900854 elif image_filename == "system_ext.img":
855 mount_point = "system_ext"
Ying Wangae61f502015-03-12 18:30:39 -0700856 else:
Tao Bao32fcdab2018-10-12 10:30:39 -0700857 logger.error("Unknown image file name %s", image_filename)
Tao Bao1c830bf2017-12-25 10:43:47 -0800858 sys.exit(1)
Ying Wangbd93d422011-10-28 17:02:30 -0700859
Ying Wangae61f502015-03-12 18:30:39 -0700860 image_properties = ImagePropFromGlobalDict(glob_dict, mount_point)
861
Tao Baoc6bd70a2018-09-27 16:58:00 -0700862 try:
863 BuildImage(in_dir, image_properties, out_file, target_out)
864 except:
Tao Bao32fcdab2018-10-12 10:30:39 -0700865 logger.error("Failed to build %s from %s", out_file, in_dir)
Tao Baoc6bd70a2018-09-27 16:58:00 -0700866 raise
Ying Wangbd93d422011-10-28 17:02:30 -0700867
Tao Bao32fcdab2018-10-12 10:30:39 -0700868
Ying Wangbd93d422011-10-28 17:02:30 -0700869if __name__ == '__main__':
Tao Bao1c830bf2017-12-25 10:43:47 -0800870 try:
871 main(sys.argv[1:])
872 finally:
873 common.Cleanup()