blob: 5e4130c7649d18664187effef460fb74a35782ac [file] [log] [blame]
Cole Faust152cdfa2023-07-26 14:33:51 -07001#!/usr/bin/env python3
Ying Wangbd93d422011-10-28 17:02:30 -07002#
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
Kelvin Zhangc819b292023-06-02 16:41:19 -070025import datetime
Tao Baoc72727a2017-12-07 10:33:00 -080026
Cole Faust152cdfa2023-07-26 14:33:51 -070027import argparse
Inseob Kim9cda3972021-10-12 22:59:12 +090028import glob
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
Kelvin Zhangc819b292023-06-02 16:41:19 -070033import shlex
Geremy Condrafd6f7512013-06-16 17:26:08 -070034import shutil
Tao Baoc72727a2017-12-07 10:33:00 -080035import sys
Kelvin Zhangc819b292023-06-02 16:41:19 -070036import uuid
Cole Faust152cdfa2023-07-26 14:33:51 -070037import tempfile
Tao Baoc72727a2017-12-07 10:33:00 -080038
39import common
Tao Bao71197512018-10-11 14:08:45 -070040import verity_utils
Ying Wangbd93d422011-10-28 17:02:30 -070041
Kelvin Zhangc819b292023-06-02 16:41:19 -070042
Tao Bao32fcdab2018-10-12 10:30:39 -070043logger = logging.getLogger(__name__)
44
Baligh Uddin601ddea2015-06-09 15:48:14 -070045OPTIONS = common.OPTIONS
Tao Bao71197512018-10-11 14:08:45 -070046BLOCK_SIZE = common.BLOCK_SIZE
Yifan Hongbbcba1e2018-06-18 16:32:35 -070047BYTES_IN_MB = 1024 * 1024
Geremy Condrae8e982a2014-05-16 19:14:30 -070048
Kelvin Zhangc819b292023-06-02 16:41:19 -070049# Use a fixed timestamp (01/01/2009 00:00:00 UTC) for files when packaging
50# images. (b/24377993, b/80600931)
51FIXED_FILE_TIMESTAMP = int((
52 datetime.datetime(2009, 1, 1, 0, 0, 0, 0, None) -
53 datetime.datetime.utcfromtimestamp(0)).total_seconds())
54
Tao Baoc72727a2017-12-07 10:33:00 -080055
Tao Baoc6bd70a2018-09-27 16:58:00 -070056class BuildImageError(Exception):
57 """An Exception raised during image building."""
58
59 def __init__(self, message):
60 Exception.__init__(self, message)
61
62
Yifan Hongbbcba1e2018-06-18 16:32:35 -070063def GetDiskUsage(path):
Tao Baoc6bd70a2018-09-27 16:58:00 -070064 """Returns the number of bytes that "path" occupies on host.
Yifan Hongbbcba1e2018-06-18 16:32:35 -070065
66 Args:
Mark Salyzyn780f5952018-10-19 13:44:36 -070067 path: The directory or file to calculate size on.
Tao Baoc6bd70a2018-09-27 16:58:00 -070068
Yifan Hongbbcba1e2018-06-18 16:32:35 -070069 Returns:
Mark Salyzyn780f5952018-10-19 13:44:36 -070070 The number of bytes based on a 1K block_size.
Yifan Hongbbcba1e2018-06-18 16:32:35 -070071 """
Chirayu Desai96a913e2020-03-27 03:49:31 +053072 cmd = ["du", "-b", "-k", "-s", path]
Tao Baof3fc62c2018-10-25 12:23:12 -070073 output = common.RunAndCheckOutput(cmd, verbose=False)
Mark Salyzyn780f5952018-10-19 13:44:36 -070074 return int(output.split()[0]) * 1024
75
76
77def GetInodeUsage(path):
78 """Returns the number of inodes that "path" occupies on host.
79
80 Args:
81 path: The directory or file to calculate inode number on.
82
83 Returns:
84 The number of inodes used.
Mark Salyzyn780f5952018-10-19 13:44:36 -070085 """
86 cmd = ["find", path, "-print"]
Tao Baof3fc62c2018-10-25 12:23:12 -070087 output = common.RunAndCheckOutput(cmd, verbose=False)
David Anderson203057c2021-03-31 20:01:41 -070088 # increase by > 6% as number of files and directories is not whole picture.
Mark Salyzync25b2bf2019-01-16 08:03:10 -080089 inodes = output.count('\n')
David Anderson203057c2021-03-31 20:01:41 -070090 spare_inodes = inodes * 6 // 100
Mark Salyzyn60fa99d2019-01-16 08:03:10 -080091 min_spare_inodes = 12
Mark Salyzync25b2bf2019-01-16 08:03:10 -080092 if spare_inodes < min_spare_inodes:
93 spare_inodes = min_spare_inodes
94 return inodes + spare_inodes
Mark Salyzyn780f5952018-10-19 13:44:36 -070095
96
Jaegeuk Kim13696542021-05-22 09:47:48 -070097def GetFilesystemCharacteristics(fs_type, image_path, sparse_image=True):
Mark Salyzyn6541d0a2019-01-10 14:30:51 -080098 """Returns various filesystem characteristics of "image_path".
Mark Salyzyn780f5952018-10-19 13:44:36 -070099
100 Args:
Mark Salyzyn6541d0a2019-01-10 14:30:51 -0800101 image_path: The file to analyze.
102 sparse_image: Image is sparse
Mark Salyzyn780f5952018-10-19 13:44:36 -0700103
104 Returns:
105 The characteristics dictionary.
Mark Salyzyn780f5952018-10-19 13:44:36 -0700106 """
Mark Salyzyn6541d0a2019-01-10 14:30:51 -0800107 unsparse_image_path = image_path
108 if sparse_image:
109 unsparse_image_path = UnsparseImage(image_path, replace=False)
Mark Salyzyn780f5952018-10-19 13:44:36 -0700110
Jaegeuk Kim13696542021-05-22 09:47:48 -0700111 if fs_type.startswith("ext"):
112 cmd = ["tune2fs", "-l", unsparse_image_path]
113 elif fs_type.startswith("f2fs"):
114 cmd = ["fsck.f2fs", "-l", unsparse_image_path]
115
Mark Salyzyn780f5952018-10-19 13:44:36 -0700116 try:
117 output = common.RunAndCheckOutput(cmd, verbose=False)
Tao Baof3fc62c2018-10-25 12:23:12 -0700118 finally:
Mark Salyzyn6541d0a2019-01-10 14:30:51 -0800119 if sparse_image:
120 os.remove(unsparse_image_path)
Tao Baof3fc62c2018-10-25 12:23:12 -0700121 fs_dict = {}
Mark Salyzyn780f5952018-10-19 13:44:36 -0700122 for line in output.splitlines():
123 fields = line.split(":")
124 if len(fields) == 2:
125 fs_dict[fields[0].strip()] = fields[1].strip()
126 return fs_dict
Yifan Hongbbcba1e2018-06-18 16:32:35 -0700127
128
Geremy Condra6e8f53c2013-12-05 17:09:18 -0800129def UnsparseImage(sparse_image_path, replace=True):
Geremy Condrafd6f7512013-06-16 17:26:08 -0700130 img_dir = os.path.dirname(sparse_image_path)
131 unsparse_image_path = "unsparse_" + os.path.basename(sparse_image_path)
132 unsparse_image_path = os.path.join(img_dir, unsparse_image_path)
133 if os.path.exists(unsparse_image_path):
Geremy Condra6e8f53c2013-12-05 17:09:18 -0800134 if replace:
135 os.unlink(unsparse_image_path)
136 else:
Tao Baoc6bd70a2018-09-27 16:58:00 -0700137 return unsparse_image_path
Geremy Condrafd6f7512013-06-16 17:26:08 -0700138 inflate_command = ["simg2img", sparse_image_path, unsparse_image_path]
Tao Bao986ee862018-10-04 15:46:16 -0700139 try:
140 common.RunAndCheckOutput(inflate_command)
141 except:
Geremy Condrafd6f7512013-06-16 17:26:08 -0700142 os.remove(unsparse_image_path)
Tao Bao986ee862018-10-04 15:46:16 -0700143 raise
Tao Baoc6bd70a2018-09-27 16:58:00 -0700144 return unsparse_image_path
Geremy Condrafd6f7512013-06-16 17:26:08 -0700145
Tao Baoc72727a2017-12-07 10:33:00 -0800146
Mohamad Ayyashf8765552016-03-02 21:07:23 -0800147def ConvertBlockMapToBaseFs(block_map_file):
Tao Bao1c830bf2017-12-25 10:43:47 -0800148 base_fs_file = common.MakeTempFile(prefix="script_gen_", suffix=".base_fs")
Mohamad Ayyashf8765552016-03-02 21:07:23 -0800149 convert_command = ["blk_alloc_to_base_fs", block_map_file, base_fs_file]
Tao Bao986ee862018-10-04 15:46:16 -0700150 common.RunAndCheckOutput(convert_command)
Tao Baoc6bd70a2018-09-27 16:58:00 -0700151 return base_fs_file
Mohamad Ayyashf8765552016-03-02 21:07:23 -0800152
Tao Baod4349f22017-12-07 23:01:25 -0800153
Tao Baoc2606eb2018-07-20 14:44:46 -0700154def SetUpInDirAndFsConfig(origin_in, prop_dict):
155 """Returns the in_dir and fs_config that should be used for image building.
156
Tom Cherryd14b8952018-08-09 14:26:00 -0700157 When building system.img for all targets, it creates and returns a staged dir
158 that combines the contents of /system (i.e. in the given in_dir) and root.
Tao Baoc2606eb2018-07-20 14:44:46 -0700159
160 Args:
161 origin_in: Path to the input directory.
162 prop_dict: A property dict that contains info like partition size. Values
163 may be updated.
164
165 Returns:
166 A tuple of in_dir and fs_config that should be used to build the image.
167 """
168 fs_config = prop_dict.get("fs_config")
Tom Cherryd14b8952018-08-09 14:26:00 -0700169
170 if prop_dict["mount_point"] == "system_other":
171 prop_dict["mount_point"] = "system"
172 return origin_in, fs_config
173
174 if prop_dict["mount_point"] != "system":
Tao Baoc2606eb2018-07-20 14:44:46 -0700175 return origin_in, fs_config
176
Mark Salyzyn780f5952018-10-19 13:44:36 -0700177 if "first_pass" in prop_dict:
178 prop_dict["mount_point"] = "/"
179 return prop_dict["first_pass"]
180
Tao Baoc2606eb2018-07-20 14:44:46 -0700181 # Construct a staging directory of the root file system.
182 in_dir = common.MakeTempDir()
183 root_dir = prop_dict.get("root_dir")
184 if root_dir:
185 shutil.rmtree(in_dir)
186 shutil.copytree(root_dir, in_dir, symlinks=True)
187 in_dir_system = os.path.join(in_dir, "system")
188 shutil.rmtree(in_dir_system, ignore_errors=True)
189 shutil.copytree(origin_in, in_dir_system, symlinks=True)
190
191 # Change the mount point to "/".
192 prop_dict["mount_point"] = "/"
193 if fs_config:
194 # We need to merge the fs_config files of system and root.
195 merged_fs_config = common.MakeTempFile(
196 prefix="merged_fs_config", suffix=".txt")
197 with open(merged_fs_config, "w") as fw:
198 if "root_fs_config" in prop_dict:
199 with open(prop_dict["root_fs_config"]) as fr:
200 fw.writelines(fr.readlines())
201 with open(fs_config) as fr:
202 fw.writelines(fr.readlines())
203 fs_config = merged_fs_config
Mark Salyzyn780f5952018-10-19 13:44:36 -0700204 prop_dict["first_pass"] = (in_dir, fs_config)
Tao Baoc2606eb2018-07-20 14:44:46 -0700205 return in_dir, fs_config
206
207
Tao Baod4349f22017-12-07 23:01:25 -0800208def CheckHeadroom(ext4fs_output, prop_dict):
209 """Checks if there's enough headroom space available.
210
211 Headroom is the reserved space on system image (via PRODUCT_SYSTEM_HEADROOM),
212 which is useful for devices with low disk space that have system image
213 variation between builds. The 'partition_headroom' in prop_dict is the size
214 in bytes, while the numbers in 'ext4fs_output' are for 4K-blocks.
215
216 Args:
217 ext4fs_output: The output string from mke2fs command.
218 prop_dict: The property dict.
219
Tao Baod8a953d2018-01-02 21:19:27 -0800220 Raises:
221 AssertionError: On invalid input.
Tao Baoc6bd70a2018-09-27 16:58:00 -0700222 BuildImageError: On check failure.
Tao Baod4349f22017-12-07 23:01:25 -0800223 """
Tao Baod8a953d2018-01-02 21:19:27 -0800224 assert ext4fs_output is not None
225 assert prop_dict.get('fs_type', '').startswith('ext4')
226 assert 'partition_headroom' in prop_dict
227 assert 'mount_point' in prop_dict
228
Tao Baod4349f22017-12-07 23:01:25 -0800229 ext4fs_stats = re.compile(
230 r'Created filesystem with .* (?P<used_blocks>[0-9]+)/'
231 r'(?P<total_blocks>[0-9]+) blocks')
Tao Baoc72727a2017-12-07 10:33:00 -0800232 last_line = ext4fs_output.strip().split('\n')[-1]
233 m = ext4fs_stats.match(last_line)
Tao Baod4349f22017-12-07 23:01:25 -0800234 used_blocks = int(m.groupdict().get('used_blocks'))
235 total_blocks = int(m.groupdict().get('total_blocks'))
Mark Salyzyn780f5952018-10-19 13:44:36 -0700236 headroom_blocks = int(prop_dict['partition_headroom']) // BLOCK_SIZE
Tao Baod4349f22017-12-07 23:01:25 -0800237 adjusted_blocks = total_blocks - headroom_blocks
238 if used_blocks > adjusted_blocks:
Tao Baod8a953d2018-01-02 21:19:27 -0800239 mount_point = prop_dict["mount_point"]
Tao Baoc6bd70a2018-09-27 16:58:00 -0700240 raise BuildImageError(
241 "Error: Not enough room on {} (total: {} blocks, used: {} blocks, "
242 "headroom: {} blocks, available: {} blocks)".format(
243 mount_point, total_blocks, used_blocks, headroom_blocks,
244 adjusted_blocks))
Tao Baod4349f22017-12-07 23:01:25 -0800245
Kelvin Zhang37bc3042022-12-15 10:31:34 -0800246
Huang Jianan65527272021-09-08 18:28:32 +0800247def CalculateSizeAndReserved(prop_dict, size):
248 fs_type = prop_dict.get("fs_type", "")
249 partition_headroom = int(prop_dict.get("partition_headroom", 0))
250 # If not specified, give us 16MB margin for GetDiskUsage error ...
Kelvin Zhang37bc3042022-12-15 10:31:34 -0800251 reserved_size = int(prop_dict.get(
252 "partition_reserved_size", BYTES_IN_MB * 16))
Huang Jianan65527272021-09-08 18:28:32 +0800253
254 if fs_type == "erofs":
255 reserved_size = int(prop_dict.get("partition_reserved_size", 0))
256 if reserved_size == 0:
257 # give .3% margin or a minimum size for AVB footer
258 return max(size * 1003 // 1000, 256 * 1024)
259
260 if fs_type.startswith("ext4") and partition_headroom > reserved_size:
261 reserved_size = partition_headroom
262
263 return size + reserved_size
Tao Baod4349f22017-12-07 23:01:25 -0800264
Kelvin Zhang37bc3042022-12-15 10:31:34 -0800265
Mark Salyzyn3cd24602018-11-07 07:40:31 -0800266def BuildImageMkfs(in_dir, prop_dict, out_file, target_out, fs_config):
267 """Builds a pure image for the files under in_dir and writes it to out_file.
Tao Baoc2606eb2018-07-20 14:44:46 -0700268
Ying Wangbd93d422011-10-28 17:02:30 -0700269 Args:
Tao Baoc2606eb2018-07-20 14:44:46 -0700270 in_dir: Path to input directory.
271 prop_dict: A property dict that contains info like partition size. Values
272 will be updated with computed values.
273 out_file: The output image file.
274 target_out: Path to the TARGET_OUT directory as in Makefile. It actually
275 points to the /system directory under PRODUCT_OUT. fs_config (the one
276 under system/core/libcutils) reads device specific FS config files from
277 there.
Mark Salyzyn3cd24602018-11-07 07:40:31 -0800278 fs_config: The fs_config file that drives the prototype
Ying Wangbd93d422011-10-28 17:02:30 -0700279
Tao Baoc6bd70a2018-09-27 16:58:00 -0700280 Raises:
281 BuildImageError: On build image failures.
Ying Wangbd93d422011-10-28 17:02:30 -0700282 """
283 build_command = []
284 fs_type = prop_dict.get("fs_type", "")
David Anderson94ad5bb2022-03-04 10:57:58 -0800285 run_fsck = None
Daniel Rosenberg6cc2c812019-12-17 17:36:31 -0800286 needs_projid = prop_dict.get("needs_projid", 0)
287 needs_casefold = prop_dict.get("needs_casefold", 0)
Jaegeuk Kimed754fb2020-10-12 19:50:05 -0700288 needs_compress = prop_dict.get("needs_compress", 0)
Geremy Condrafd6f7512013-06-16 17:26:08 -0700289
David Anderson9e95a022021-08-31 21:32:45 -0700290 disable_sparse = "disable_sparse" in prop_dict
David Anderson94ad5bb2022-03-04 10:57:58 -0800291 manual_sparse = False
David Anderson9e95a022021-08-31 21:32:45 -0700292
Ying Wangbd93d422011-10-28 17:02:30 -0700293 if fs_type.startswith("ext"):
Adrien Schildknecht9a072cc2016-11-18 17:06:29 -0800294 build_command = [prop_dict["ext_mkuserimg"]]
David Anderson9e95a022021-08-31 21:32:45 -0700295 if "extfs_sparse_flag" in prop_dict and not disable_sparse:
Ying Wangbd93d422011-10-28 17:02:30 -0700296 build_command.append(prop_dict["extfs_sparse_flag"])
David Anderson94ad5bb2022-03-04 10:57:58 -0800297 run_e2fsck = RunE2fsck
Ying Wangbd93d422011-10-28 17:02:30 -0700298 build_command.extend([in_dir, out_file, fs_type,
299 prop_dict["mount_point"]])
Tao Bao35f4ebc2018-09-27 15:31:11 -0700300 build_command.append(prop_dict["image_size"])
Ying Wangf3b86352014-11-18 18:03:13 -0800301 if "journal_size" in prop_dict:
302 build_command.extend(["-j", prop_dict["journal_size"]])
Doug Zongker850b8072013-12-05 15:54:55 -0800303 if "timestamp" in prop_dict:
304 build_command.extend(["-T", str(prop_dict["timestamp"])])
Ying Wanga2292c92015-03-24 19:07:40 -0700305 if fs_config:
Doug Zongker82822822014-06-16 09:10:55 -0700306 build_command.extend(["-C", fs_config])
Thierry Strudel74a81e62015-07-09 09:54:55 -0700307 if target_out:
308 build_command.extend(["-D", target_out])
Ying Wanga2292c92015-03-24 19:07:40 -0700309 if "block_list" in prop_dict:
310 build_command.extend(["-B", prop_dict["block_list"]])
Mohamad Ayyashf8765552016-03-02 21:07:23 -0800311 if "base_fs_file" in prop_dict:
312 base_fs_file = ConvertBlockMapToBaseFs(prop_dict["base_fs_file"])
Mohamad Ayyashf8765552016-03-02 21:07:23 -0800313 build_command.extend(["-d", base_fs_file])
Christoffer Dall8ed01f32014-12-17 21:34:12 +0100314 build_command.extend(["-L", prop_dict["mount_point"]])
Patrick Tjina1900842016-10-20 10:58:12 -0700315 if "extfs_inode_count" in prop_dict:
316 build_command.extend(["-i", prop_dict["extfs_inode_count"]])
Patrick Tjin3f5f9932018-03-23 11:36:43 -0700317 if "extfs_rsv_pct" in prop_dict:
318 build_command.extend(["-M", prop_dict["extfs_rsv_pct"]])
Connor O'Brien20f08c32017-01-05 16:48:14 -0800319 if "flash_erase_block_size" in prop_dict:
320 build_command.extend(["-e", prop_dict["flash_erase_block_size"]])
321 if "flash_logical_block_size" in prop_dict:
322 build_command.extend(["-o", prop_dict["flash_logical_block_size"]])
Tao Baod86e3112017-09-22 15:45:33 -0700323 # Specify UUID and hash_seed if using mke2fs.
HÃ¥kan Kvist2e1f5272021-05-11 11:14:48 +0200324 if os.path.basename(prop_dict["ext_mkuserimg"]) == "mkuserimg_mke2fs":
Tao Baod86e3112017-09-22 15:45:33 -0700325 if "uuid" in prop_dict:
326 build_command.extend(["-U", prop_dict["uuid"]])
327 if "hash_seed" in prop_dict:
328 build_command.extend(["-S", prop_dict["hash_seed"]])
Tamas Petzc0a8c632020-02-03 15:41:02 +0100329 if prop_dict.get("ext4_share_dup_blocks") == "true":
Jin Qianfde9f792018-01-22 13:15:46 -0800330 build_command.append("-c")
Daniel Rosenberg6cc2c812019-12-17 17:36:31 -0800331 if (needs_projid):
332 build_command.extend(["--inode_size", "512"])
333 else:
334 build_command.extend(["--inode_size", "256"])
Ying Wanga2292c92015-03-24 19:07:40 -0700335 if "selinux_fc" in prop_dict:
Kenny Rootf32dc712012-04-08 10:42:34 -0700336 build_command.append(prop_dict["selinux_fc"])
Gao Xiang961041a2020-06-17 13:59:16 +0800337 elif fs_type.startswith("erofs"):
David Anderson94ad5bb2022-03-04 10:57:58 -0800338 build_command = ["mkfs.erofs"]
339
David Anderson40a821f2021-09-22 18:02:01 -0700340 compressor = None
341 if "erofs_default_compressor" in prop_dict:
342 compressor = prop_dict["erofs_default_compressor"]
343 if "erofs_compressor" in prop_dict:
344 compressor = prop_dict["erofs_compressor"]
David Andersonf3c81d72022-06-27 23:18:46 +0000345 if compressor and compressor != "none":
David Anderson40a821f2021-09-22 18:02:01 -0700346 build_command.extend(["-z", compressor])
David Anderson94ad5bb2022-03-04 10:57:58 -0800347
Dmitrii Merkurev8ab66032022-05-17 23:10:37 +0000348 compress_hints = None
349 if "erofs_default_compress_hints" in prop_dict:
350 compress_hints = prop_dict["erofs_default_compress_hints"]
351 if "erofs_compress_hints" in prop_dict:
352 compress_hints = prop_dict["erofs_compress_hints"]
353 if compress_hints:
354 build_command.extend(["--compress-hints", compress_hints])
355
David Anderson94ad5bb2022-03-04 10:57:58 -0800356 build_command.extend(["--mount-point", prop_dict["mount_point"]])
357 if target_out:
358 build_command.extend(["--product-out", target_out])
359 if fs_config:
360 build_command.extend(["--fs-config-file", fs_config])
361 if "selinux_fc" in prop_dict:
362 build_command.extend(["--file-contexts", prop_dict["selinux_fc"]])
David Andersond29e5372021-10-08 18:33:43 -0700363 if "timestamp" in prop_dict:
364 build_command.extend(["-T", str(prop_dict["timestamp"])])
365 if "uuid" in prop_dict:
366 build_command.extend(["-U", prop_dict["uuid"]])
367 if "block_list" in prop_dict:
David Anderson94ad5bb2022-03-04 10:57:58 -0800368 build_command.extend(["--block-list-file", prop_dict["block_list"]])
David Anderson64b351b2021-10-13 00:20:43 -0700369 if "erofs_pcluster_size" in prop_dict:
David Anderson94ad5bb2022-03-04 10:57:58 -0800370 build_command.extend(["-C", prop_dict["erofs_pcluster_size"]])
David Anderson64b351b2021-10-13 00:20:43 -0700371 if "erofs_share_dup_blocks" in prop_dict:
David Anderson94ad5bb2022-03-04 10:57:58 -0800372 build_command.extend(["--chunksize", "4096"])
David Andersonf54665f2022-03-04 14:42:18 -0800373 if "erofs_use_legacy_compression" in prop_dict:
374 build_command.extend(["-E", "legacy-compress"])
David Anderson94ad5bb2022-03-04 10:57:58 -0800375
376 build_command.extend([out_file, in_dir])
377 if "erofs_sparse_flag" in prop_dict and not disable_sparse:
378 manual_sparse = True
379
380 run_fsck = RunErofsFsck
Mohamad Ayyashb97746e2015-03-03 12:30:37 -0800381 elif fs_type.startswith("squash"):
Cole Faustb0002082022-09-05 18:34:56 -0700382 build_command = ["mksquashfsimage"]
Mohamad Ayyashb97746e2015-03-03 12:30:37 -0800383 build_command.extend([in_dir, out_file])
David Anderson9e95a022021-08-31 21:32:45 -0700384 if "squashfs_sparse_flag" in prop_dict and not disable_sparse:
Todd Poynorb2a555e2015-12-15 18:00:14 -0800385 build_command.extend([prop_dict["squashfs_sparse_flag"]])
Mohamad Ayyashb97746e2015-03-03 12:30:37 -0800386 build_command.extend(["-m", prop_dict["mount_point"]])
Thierry Strudel74a81e62015-07-09 09:54:55 -0700387 if target_out:
388 build_command.extend(["-d", target_out])
Mohamad Ayyash88378822016-04-07 22:10:51 -0700389 if fs_config:
390 build_command.extend(["-C", fs_config])
Ying Wanga2292c92015-03-24 19:07:40 -0700391 if "selinux_fc" in prop_dict:
Mohamad Ayyashb97746e2015-03-03 12:30:37 -0800392 build_command.extend(["-c", prop_dict["selinux_fc"]])
Mohamad Ayyashc3484f72016-06-13 09:46:58 -0700393 if "block_list" in prop_dict:
394 build_command.extend(["-B", prop_dict["block_list"]])
Ng Zhi An9446c1d2018-01-19 15:51:46 -0800395 if "squashfs_block_size" in prop_dict:
396 build_command.extend(["-b", prop_dict["squashfs_block_size"]])
Simon Wilsonf86e7ee2015-06-17 12:35:15 -0700397 if "squashfs_compressor" in prop_dict:
398 build_command.extend(["-z", prop_dict["squashfs_compressor"]])
399 if "squashfs_compressor_opt" in prop_dict:
400 build_command.extend(["-zo", prop_dict["squashfs_compressor_opt"]])
Tao Baoc72727a2017-12-07 10:33:00 -0800401 if prop_dict.get("squashfs_disable_4k_align") == "true":
Mohamad Ayyash1b6d3482016-06-15 15:53:07 -0700402 build_command.extend(["-a"])
JP Abgrall5bfed5a2014-06-16 14:17:40 -0700403 elif fs_type.startswith("f2fs"):
Cole Faustb0002082022-09-05 18:34:56 -0700404 build_command = ["mkf2fsuserimg"]
Tao Bao35f4ebc2018-09-27 15:31:11 -0700405 build_command.extend([out_file, prop_dict["image_size"]])
David Anderson9e95a022021-08-31 21:32:45 -0700406 if "f2fs_sparse_flag" in prop_dict and not disable_sparse:
Alistair Delva91238cc2019-10-16 10:53:41 -0700407 build_command.extend([prop_dict["f2fs_sparse_flag"]])
Jaegeuk Kim2ea1eba2017-11-28 19:21:28 -0800408 if fs_config:
409 build_command.extend(["-C", fs_config])
410 build_command.extend(["-f", in_dir])
411 if target_out:
412 build_command.extend(["-D", target_out])
413 if "selinux_fc" in prop_dict:
414 build_command.extend(["-s", prop_dict["selinux_fc"]])
415 build_command.extend(["-t", prop_dict["mount_point"]])
416 if "timestamp" in prop_dict:
417 build_command.extend(["-T", str(prop_dict["timestamp"])])
Jaegeuk Kim3dc47282021-06-13 08:54:01 -0700418 if "block_list" in prop_dict:
419 build_command.extend(["-B", prop_dict["block_list"]])
Jaegeuk Kim2ea1eba2017-11-28 19:21:28 -0800420 build_command.extend(["-L", prop_dict["mount_point"]])
Daniel Rosenberg6cc2c812019-12-17 17:36:31 -0800421 if (needs_projid):
422 build_command.append("--prjquota")
423 if (needs_casefold):
424 build_command.append("--casefold")
Jaegeuk Kim13696542021-05-22 09:47:48 -0700425 if (needs_compress or prop_dict.get("f2fs_compress") == "true"):
Jaegeuk Kimed754fb2020-10-12 19:50:05 -0700426 build_command.append("--compression")
Jaegeuk Kim551a2e62022-10-27 09:46:03 -0700427 if "ro_mount_point" in prop_dict:
Jaegeuk Kim46e0ea22021-05-20 23:13:59 -0700428 build_command.append("--readonly")
Jaegeuk Kim3dc47282021-06-13 08:54:01 -0700429 if (prop_dict.get("f2fs_compress") == "true"):
Robin Hsu3e51f422020-11-04 09:29:09 +0800430 build_command.append("--sldc")
Jaegeuk Kim13696542021-05-22 09:47:48 -0700431 if (prop_dict.get("f2fs_sldc_flags") == None):
Robin Hsu3e51f422020-11-04 09:29:09 +0800432 build_command.append(str(0))
433 else:
Jaegeuk Kim13696542021-05-22 09:47:48 -0700434 sldc_flags_str = prop_dict.get("f2fs_sldc_flags")
Robin Hsu3e51f422020-11-04 09:29:09 +0800435 sldc_flags = sldc_flags_str.split()
436 build_command.append(str(len(sldc_flags)))
437 build_command.extend(sldc_flags)
Ying Wangbd93d422011-10-28 17:02:30 -0700438 else:
Tao Baoc6bd70a2018-09-27 16:58:00 -0700439 raise BuildImageError(
440 "Error: unknown filesystem type: {}".format(fs_type))
Ying Wangbd93d422011-10-28 17:02:30 -0700441
Tao Bao986ee862018-10-04 15:46:16 -0700442 try:
443 mkfs_output = common.RunAndCheckOutput(build_command)
444 except:
Tao Baoc6bd70a2018-09-27 16:58:00 -0700445 try:
446 du = GetDiskUsage(in_dir)
447 du_str = "{} bytes ({} MB)".format(du, du // BYTES_IN_MB)
Tao Bao986ee862018-10-04 15:46:16 -0700448 # Suppress any errors from GetDiskUsage() to avoid hiding the real errors
449 # from common.RunAndCheckOutput().
Tao Bao32fcdab2018-10-12 10:30:39 -0700450 except Exception: # pylint: disable=broad-except
451 logger.exception("Failed to compute disk usage with du")
Tao Baoc6bd70a2018-09-27 16:58:00 -0700452 du_str = "unknown"
Tao Bao4251fe92018-07-23 13:05:00 -0700453 print(
Mark Salyzyn3cd24602018-11-07 07:40:31 -0800454 "Out of space? Out of inodes? The tree size of {} is {}, "
455 "with reserved space of {} bytes ({} MB).".format(
Tao Baoc2606eb2018-07-20 14:44:46 -0700456 in_dir, du_str,
Tao Bao4251fe92018-07-23 13:05:00 -0700457 int(prop_dict.get("partition_reserved_size", 0)),
458 int(prop_dict.get("partition_reserved_size", 0)) // BYTES_IN_MB))
Huang Jiananf63abb12021-04-29 15:24:50 +0800459 if ("image_size" in prop_dict and "partition_size" in prop_dict):
460 print(
461 "The max image size for filesystem files is {} bytes ({} MB), "
462 "out of a total partition size of {} bytes ({} MB).".format(
463 int(prop_dict["image_size"]),
464 int(prop_dict["image_size"]) // BYTES_IN_MB,
465 int(prop_dict["partition_size"]),
466 int(prop_dict["partition_size"]) // BYTES_IN_MB))
Tao Bao986ee862018-10-04 15:46:16 -0700467 raise
Ying Wang69e9b4d2012-11-26 18:10:23 -0800468
David Anderson94ad5bb2022-03-04 10:57:58 -0800469 if run_fsck and prop_dict.get("skip_fsck") != "true":
470 run_fsck(out_file)
Mark Salyzyn3cd24602018-11-07 07:40:31 -0800471
David Anderson94ad5bb2022-03-04 10:57:58 -0800472 if manual_sparse:
473 temp_file = out_file + ".sparse"
474 img2simg_argv = ["img2simg", out_file, temp_file]
475 common.RunAndCheckOutput(img2simg_argv)
476 os.rename(temp_file, out_file)
Mark Salyzyn3cd24602018-11-07 07:40:31 -0800477
478 return mkfs_output
479
David Anderson94ad5bb2022-03-04 10:57:58 -0800480
481def RunE2fsck(out_file):
482 unsparse_image = UnsparseImage(out_file, replace=False)
483
484 # Run e2fsck on the inflated image file
485 e2fsck_command = ["e2fsck", "-f", "-n", unsparse_image]
486 try:
487 common.RunAndCheckOutput(e2fsck_command)
488 finally:
489 os.remove(unsparse_image)
490
491
492def RunErofsFsck(out_file):
493 fsck_command = ["fsck.erofs", "--extract", out_file]
494 try:
495 common.RunAndCheckOutput(fsck_command)
496 except:
497 print("Check failed for EROFS image {}".format(out_file))
498 raise
499
500
Kelvin Zhangc819b292023-06-02 16:41:19 -0700501def SetUUIDIfNotExist(image_props):
502
503 # Use repeatable ext4 FS UUID and hash_seed UUID (based on partition name and
504 # build fingerprint). Also use the legacy build id, because the vbmeta digest
505 # isn't available at this point.
506 what = image_props["mount_point"]
507 fingerprint = image_props.get("fingerprint", "")
508 uuid_seed = what + "-" + fingerprint
509 logger.info("Using fingerprint %s for partition %s", fingerprint, what)
510 image_props["uuid"] = str(uuid.uuid5(uuid.NAMESPACE_URL, uuid_seed))
511 hash_seed = "hash_seed-" + uuid_seed
512 image_props["hash_seed"] = str(uuid.uuid5(uuid.NAMESPACE_URL, hash_seed))
513
514
Mark Salyzyn3cd24602018-11-07 07:40:31 -0800515def BuildImage(in_dir, prop_dict, out_file, target_out=None):
516 """Builds an image for the files under in_dir and writes it to out_file.
517
518 Args:
519 in_dir: Path to input directory.
520 prop_dict: A property dict that contains info like partition size. Values
521 will be updated with computed values.
522 out_file: The output image file.
523 target_out: Path to the TARGET_OUT directory as in Makefile. It actually
524 points to the /system directory under PRODUCT_OUT. fs_config (the one
525 under system/core/libcutils) reads device specific FS config files from
526 there.
527
528 Raises:
529 BuildImageError: On build image failures.
530 """
531 in_dir, fs_config = SetUpInDirAndFsConfig(in_dir, prop_dict)
Kelvin Zhangc819b292023-06-02 16:41:19 -0700532 SetUUIDIfNotExist(prop_dict)
Mark Salyzyn3cd24602018-11-07 07:40:31 -0800533
534 build_command = []
535 fs_type = prop_dict.get("fs_type", "")
536
537 fs_spans_partition = True
Huang Jianan62d926e2020-12-04 16:53:06 +0800538 if fs_type.startswith("squash") or fs_type.startswith("erofs"):
Mark Salyzyn3cd24602018-11-07 07:40:31 -0800539 fs_spans_partition = False
Jaegeuk Kim13696542021-05-22 09:47:48 -0700540 elif fs_type.startswith("f2fs") and prop_dict.get("f2fs_compress") == "true":
541 fs_spans_partition = False
Mark Salyzyn3cd24602018-11-07 07:40:31 -0800542
543 # Get a builder for creating an image that's to be verified by Verified Boot,
544 # or None if not applicable.
545 verity_image_builder = verity_utils.CreateVerityImageBuilder(prop_dict)
546
David Anderson9e95a022021-08-31 21:32:45 -0700547 disable_sparse = "disable_sparse" in prop_dict
Huang Jiananffa1d572021-09-08 18:11:22 +0800548 mkfs_output = None
Mark Salyzyn3cd24602018-11-07 07:40:31 -0800549 if (prop_dict.get("use_dynamic_partition_size") == "true" and
Kelvin Zhang37bc3042022-12-15 10:31:34 -0800550 "partition_size" not in prop_dict):
Mark Salyzyn3cd24602018-11-07 07:40:31 -0800551 # If partition_size is not defined, use output of `du' + reserved_size.
Huang Jianan35f015e2020-12-04 16:58:24 +0800552 # For compressed file system, it's better to use the compressed size to avoid wasting space.
553 if fs_type.startswith("erofs"):
Kelvin Zhang37bc3042022-12-15 10:31:34 -0800554 mkfs_output = BuildImageMkfs(
555 in_dir, prop_dict, out_file, target_out, fs_config)
Huang Jiananffa1d572021-09-08 18:11:22 +0800556 if "erofs_sparse_flag" in prop_dict and not disable_sparse:
557 image_path = UnsparseImage(out_file, replace=False)
558 size = GetDiskUsage(image_path)
559 os.remove(image_path)
560 else:
561 size = GetDiskUsage(out_file)
Huang Jianan35f015e2020-12-04 16:58:24 +0800562 else:
563 size = GetDiskUsage(in_dir)
Mark Salyzyn3cd24602018-11-07 07:40:31 -0800564 logger.info(
565 "The tree size of %s is %d MB.", in_dir, size // BYTES_IN_MB)
Huang Jianan65527272021-09-08 18:28:32 +0800566 size = CalculateSizeAndReserved(prop_dict, size)
Mark Salyzyn3cd24602018-11-07 07:40:31 -0800567 # Round this up to a multiple of 4K so that avbtool works
568 size = common.RoundUpTo4K(size)
569 if fs_type.startswith("ext"):
570 prop_dict["partition_size"] = str(size)
571 prop_dict["image_size"] = str(size)
572 if "extfs_inode_count" not in prop_dict:
573 prop_dict["extfs_inode_count"] = str(GetInodeUsage(in_dir))
574 logger.info(
575 "First Pass based on estimates of %d MB and %s inodes.",
576 size // BYTES_IN_MB, prop_dict["extfs_inode_count"])
577 BuildImageMkfs(in_dir, prop_dict, out_file, target_out, fs_config)
Mark Salyzyn6541d0a2019-01-10 14:30:51 -0800578 sparse_image = False
David Anderson9e95a022021-08-31 21:32:45 -0700579 if "extfs_sparse_flag" in prop_dict and not disable_sparse:
Mark Salyzyn6541d0a2019-01-10 14:30:51 -0800580 sparse_image = True
Jaegeuk Kim13696542021-05-22 09:47:48 -0700581 fs_dict = GetFilesystemCharacteristics(fs_type, out_file, sparse_image)
Mark Salyzyn3cd24602018-11-07 07:40:31 -0800582 os.remove(out_file)
583 block_size = int(fs_dict.get("Block size", "4096"))
584 free_size = int(fs_dict.get("Free blocks", "0")) * block_size
585 reserved_size = int(prop_dict.get("partition_reserved_size", 0))
586 partition_headroom = int(fs_dict.get("partition_headroom", 0))
587 if fs_type.startswith("ext4") and partition_headroom > reserved_size:
588 reserved_size = partition_headroom
589 if free_size <= reserved_size:
590 logger.info(
591 "Not worth reducing image %d <= %d.", free_size, reserved_size)
592 else:
593 size -= free_size
594 size += reserved_size
Mark Salyzyn60a716f2019-01-10 08:36:34 -0800595 if reserved_size == 0:
Mark Salyzync25b2bf2019-01-16 08:03:10 -0800596 # add .3% margin
597 size = size * 1003 // 1000
Mark Salyzyn60a716f2019-01-10 08:36:34 -0800598 # Use a minimum size, otherwise we will fail to calculate an AVB footer
599 # or fail to construct an ext4 image.
600 size = max(size, 256 * 1024)
Mark Salyzyn3cd24602018-11-07 07:40:31 -0800601 if block_size <= 4096:
602 size = common.RoundUpTo4K(size)
603 else:
604 size = ((size + block_size - 1) // block_size) * block_size
605 extfs_inode_count = prop_dict["extfs_inode_count"]
606 inodes = int(fs_dict.get("Inode count", extfs_inode_count))
607 inodes -= int(fs_dict.get("Free inodes", "0"))
Mark Salyzync25b2bf2019-01-16 08:03:10 -0800608 # add .2% margin or 1 inode, whichever is greater
609 spare_inodes = inodes * 2 // 1000
610 min_spare_inodes = 1
611 if spare_inodes < min_spare_inodes:
612 spare_inodes = min_spare_inodes
613 inodes += spare_inodes
Mark Salyzyn3cd24602018-11-07 07:40:31 -0800614 prop_dict["extfs_inode_count"] = str(inodes)
615 prop_dict["partition_size"] = str(size)
616 logger.info(
617 "Allocating %d Inodes for %s.", inodes, out_file)
Jaegeuk Kim13696542021-05-22 09:47:48 -0700618 elif fs_type.startswith("f2fs") and prop_dict.get("f2fs_compress") == "true":
619 prop_dict["partition_size"] = str(size)
620 prop_dict["image_size"] = str(size)
621 BuildImageMkfs(in_dir, prop_dict, out_file, target_out, fs_config)
622 sparse_image = False
David Anderson9e95a022021-08-31 21:32:45 -0700623 if "f2fs_sparse_flag" in prop_dict and not disable_sparse:
Jaegeuk Kim13696542021-05-22 09:47:48 -0700624 sparse_image = True
625 fs_dict = GetFilesystemCharacteristics(fs_type, out_file, sparse_image)
626 os.remove(out_file)
627 block_count = int(fs_dict.get("block_count", "0"))
628 log_blocksize = int(fs_dict.get("log_blocksize", "12"))
629 size = block_count << log_blocksize
630 prop_dict["partition_size"] = str(size)
Mark Salyzyn3cd24602018-11-07 07:40:31 -0800631 if verity_image_builder:
632 size = verity_image_builder.CalculateDynamicPartitionSize(size)
633 prop_dict["partition_size"] = str(size)
634 logger.info(
635 "Allocating %d MB for %s.", size // BYTES_IN_MB, out_file)
636
637 prop_dict["image_size"] = prop_dict["partition_size"]
638
639 # Adjust the image size to make room for the hashes if this is to be verified.
640 if verity_image_builder:
641 max_image_size = verity_image_builder.CalculateMaxImageSize()
642 prop_dict["image_size"] = str(max_image_size)
643
Huang Jiananffa1d572021-09-08 18:11:22 +0800644 if not mkfs_output:
Kelvin Zhang37bc3042022-12-15 10:31:34 -0800645 mkfs_output = BuildImageMkfs(
646 in_dir, prop_dict, out_file, target_out, fs_config)
Mark Salyzyn3cd24602018-11-07 07:40:31 -0800647
David Anderson009d6f82021-11-12 02:01:29 +0000648 # Update the image (eg filesystem size). This can be different eg if mkfs
649 # rounds the requested size down due to alignment.
650 prop_dict["image_size"] = common.sparse_img.GetImagePartitionSize(out_file)
651
Tao Baod4349f22017-12-07 23:01:25 -0800652 # Check if there's enough headroom space available for ext4 image.
Tao Bao79d52f82017-12-07 14:07:44 -0800653 if "partition_headroom" in prop_dict and fs_type.startswith("ext4"):
Tao Baoc6bd70a2018-09-27 16:58:00 -0700654 CheckHeadroom(mkfs_output, prop_dict)
Tao Baoc7a6f1e2015-06-23 11:16:05 -0700655
Tao Bao7549e5e2018-10-03 14:23:59 -0700656 if not fs_spans_partition and verity_image_builder:
657 verity_image_builder.PadSparseImage(out_file)
Mohamad Ayyashdd063522015-03-24 12:42:03 -0700658
Tao Baoc72727a2017-12-07 10:33:00 -0800659 # Create the verified image if this is to be verified.
Tao Bao7549e5e2018-10-03 14:23:59 -0700660 if verity_image_builder:
661 verity_image_builder.Build(out_file)
David Zeuthen4014a9d2016-09-30 17:29:22 -0400662
Kelvin Zhang37bc3042022-12-15 10:31:34 -0800663
Kelvin Zhangc819b292023-06-02 16:41:19 -0700664def TryParseFingerprint(glob_dict: dict):
665 for (key, val) in glob_dict.items():
666 if not key.endswith("_add_hashtree_footer_args") and not key.endswith("_add_hash_footer_args"):
667 continue
668 for arg in shlex.split(val):
669 m = re.match(r"^com\.android\.build\.\w+\.fingerprint:", arg)
670 if m is None:
671 continue
672 fingerprint = arg[len(m.group()):]
673 glob_dict["fingerprint"] = fingerprint
674 return
675
676
Ying Wangbd93d422011-10-28 17:02:30 -0700677def ImagePropFromGlobalDict(glob_dict, mount_point):
678 """Build an image property dictionary from the global dictionary.
679
680 Args:
681 glob_dict: the global dictionary from the build system.
682 mount_point: such as "system", "data" etc.
683 """
Doug Zongker1ad7ade2013-12-06 11:53:27 -0800684 d = {}
Kelvin Zhangc819b292023-06-02 16:41:19 -0700685 TryParseFingerprint(glob_dict)
Tao Bao052ae352015-09-28 13:44:13 -0700686
Justin Yun22ce9472023-07-15 15:35:07 +0900687 # Set fixed timestamp for building the OTA package.
688 if "use_fixed_timestamp" in glob_dict:
689 d["timestamp"] = FIXED_FILE_TIMESTAMP
Tao Bao822f5842015-09-30 16:01:14 -0700690 if "build.prop" in glob_dict:
Tianjie Xu0fde41e2020-05-09 05:24:18 +0000691 timestamp = glob_dict["build.prop"].GetProp("ro.build.date.utc")
692 if timestamp:
693 d["timestamp"] = timestamp
Ying Wang9f8e8db2011-11-04 11:37:01 -0700694
695 def copy_prop(src_p, dest_p):
Patrick Tjin3f5f9932018-03-23 11:36:43 -0700696 """Copy a property from the global dictionary.
697
698 Args:
699 src_p: The source property in the global dictionary.
700 dest_p: The destination property.
701 Returns:
702 True if property was found and copied, False otherwise.
703 """
Ying Wang9f8e8db2011-11-04 11:37:01 -0700704 if src_p in glob_dict:
705 d[dest_p] = str(glob_dict[src_p])
Patrick Tjin3f5f9932018-03-23 11:36:43 -0700706 return True
707 return False
Ying Wang9f8e8db2011-11-04 11:37:01 -0700708
Ying Wangbd93d422011-10-28 17:02:30 -0700709 common_props = (
Ying Wangbd93d422011-10-28 17:02:30 -0700710 "extfs_sparse_flag",
David Anderson40a821f2021-09-22 18:02:01 -0700711 "erofs_default_compressor",
Dmitrii Merkurev8ab66032022-05-17 23:10:37 +0000712 "erofs_default_compress_hints",
David Anderson64b351b2021-10-13 00:20:43 -0700713 "erofs_pcluster_size",
714 "erofs_share_dup_blocks",
Gao Xiang961041a2020-06-17 13:59:16 +0800715 "erofs_sparse_flag",
David Andersonf54665f2022-03-04 14:42:18 -0800716 "erofs_use_legacy_compression",
Todd Poynorb2a555e2015-12-15 18:00:14 -0800717 "squashfs_sparse_flag",
Jaegeuk Kim13696542021-05-22 09:47:48 -0700718 "system_f2fs_compress",
Robin Hsu3e51f422020-11-04 09:29:09 +0800719 "system_f2fs_sldc_flags",
Alistair Delva91238cc2019-10-16 10:53:41 -0700720 "f2fs_sparse_flag",
Ying Wang6a42a252013-02-27 13:54:02 -0800721 "skip_fsck",
Adrien Schildknecht9a072cc2016-11-18 17:06:29 -0800722 "ext_mkuserimg",
Bowgo Tsai3e599ea2017-05-26 18:30:04 +0800723 "avb_enable",
Tao Bao2b6dfd62017-09-27 17:17:43 -0700724 "avb_avbtool",
Yifan Hong2dae5722018-07-31 12:47:27 -0700725 "use_dynamic_partition_size",
Kelvin Zhangc819b292023-06-02 16:41:19 -0700726 "fingerprint",
Tao Bao2b6dfd62017-09-27 17:17:43 -0700727 )
Ying Wangbd93d422011-10-28 17:02:30 -0700728 for p in common_props:
Ying Wang9f8e8db2011-11-04 11:37:01 -0700729 copy_prop(p, p)
Ying Wangbd93d422011-10-28 17:02:30 -0700730
David Anderson271dab62021-10-11 17:31:26 -0700731 ro_mount_points = set([
732 "odm",
733 "odm_dlkm",
734 "oem",
735 "product",
736 "system",
Ramji Jiyani13a41372022-01-27 07:05:08 +0000737 "system_dlkm",
David Anderson271dab62021-10-11 17:31:26 -0700738 "system_ext",
739 "system_other",
740 "vendor",
741 "vendor_dlkm",
742 ])
David Andersonaac502f2021-09-23 15:48:29 -0700743
David Anderson271dab62021-10-11 17:31:26 -0700744 # Tuple layout: (readonly, specific prop, general prop)
745 fmt_props = (
746 # Generic first, then specific file type.
747 (False, "fs_type", "fs_type"),
748 (False, "{}_fs_type", "fs_type"),
749
750 # Ordering for these doesn't matter.
751 (False, "{}_selinux_fc", "selinux_fc"),
752 (False, "{}_size", "partition_size"),
753 (True, "avb_{}_add_hashtree_footer_args", "avb_add_hashtree_footer_args"),
754 (True, "avb_{}_algorithm", "avb_algorithm"),
755 (True, "avb_{}_hashtree_enable", "avb_hashtree_enable"),
756 (True, "avb_{}_key_path", "avb_key_path"),
757 (True, "avb_{}_salt", "avb_salt"),
David Andersonf54665f2022-03-04 14:42:18 -0800758 (True, "erofs_use_legacy_compression", "erofs_use_legacy_compression"),
David Anderson271dab62021-10-11 17:31:26 -0700759 (True, "ext4_share_dup_blocks", "ext4_share_dup_blocks"),
760 (True, "{}_base_fs_file", "base_fs_file"),
761 (True, "{}_disable_sparse", "disable_sparse"),
762 (True, "{}_erofs_compressor", "erofs_compressor"),
Dmitrii Merkurev8ab66032022-05-17 23:10:37 +0000763 (True, "{}_erofs_compress_hints", "erofs_compress_hints"),
David Anderson64b351b2021-10-13 00:20:43 -0700764 (True, "{}_erofs_pcluster_size", "erofs_pcluster_size"),
765 (True, "{}_erofs_share_dup_blocks", "erofs_share_dup_blocks"),
David Anderson271dab62021-10-11 17:31:26 -0700766 (True, "{}_extfs_inode_count", "extfs_inode_count"),
767 (True, "{}_f2fs_compress", "f2fs_compress"),
768 (True, "{}_f2fs_sldc_flags", "f2fs_sldc_flags"),
769 (True, "{}_reserved_size", "partition_reserved_size"),
770 (True, "{}_squashfs_block_size", "squashfs_block_size"),
771 (True, "{}_squashfs_compressor", "squashfs_compressor"),
772 (True, "{}_squashfs_compressor_opt", "squashfs_compressor_opt"),
773 (True, "{}_squashfs_disable_4k_align", "squashfs_disable_4k_align"),
774 (True, "{}_verity_block_device", "verity_block_device"),
775 )
776
777 # Translate prefixed properties into generic ones.
778 if mount_point == "data":
779 prefix = "userdata"
780 else:
781 prefix = mount_point
782
783 for readonly, src_prop, dest_prop in fmt_props:
784 if readonly and mount_point not in ro_mount_points:
785 continue
786
787 if src_prop == "fs_type":
788 # This property is legacy and only used on a few partitions. b/202600377
789 allowed_partitions = set(["system", "system_other", "data", "oem"])
790 if mount_point not in allowed_partitions:
Kelvin Zhang37bc3042022-12-15 10:31:34 -0800791 continue
David Anderson271dab62021-10-11 17:31:26 -0700792
Po Hu1c48b592022-02-18 09:10:22 +0000793 if (mount_point == "system_other") and (dest_prop != "partition_size"):
David Anderson271dab62021-10-11 17:31:26 -0700794 # Propagate system properties to system_other. They'll get overridden
795 # after as needed.
796 copy_prop(src_prop.format("system"), dest_prop)
797
798 copy_prop(src_prop.format(prefix), dest_prop)
799
800 # Set prefixed properties that need a default value.
801 if mount_point in ro_mount_points:
802 prop = "{}_journal_size".format(prefix)
803 if not copy_prop(prop, "journal_size"):
804 d["journal_size"] = "0"
805
806 prop = "{}_extfs_rsv_pct".format(prefix)
807 if not copy_prop(prop, "extfs_rsv_pct"):
808 d["extfs_rsv_pct"] = "0"
809
Jaegeuk Kim551a2e62022-10-27 09:46:03 -0700810 d["ro_mount_point"] = "1"
811
David Anderson271dab62021-10-11 17:31:26 -0700812 # Copy partition-specific properties.
Ying Wangbd93d422011-10-28 17:02:30 -0700813 d["mount_point"] = mount_point
814 if mount_point == "system":
Julius D'souza001c6762017-05-03 13:43:27 -0700815 copy_prop("system_headroom", "partition_headroom")
Tao Baof3282b42015-04-01 11:21:55 -0700816 copy_prop("system_root_image", "system_root_image")
Tao Bao8bfd3c72018-07-20 15:20:28 -0700817 copy_prop("root_dir", "root_dir")
818 copy_prop("root_fs_config", "root_fs_config")
Ying Wangbd93d422011-10-28 17:02:30 -0700819 elif mount_point == "data":
JP Abgrall5bfed5a2014-06-16 14:17:40 -0700820 # Copy the generic fs type first, override with specific one if available.
Tao Baoc72727a2017-12-07 10:33:00 -0800821 copy_prop("flash_logical_block_size", "flash_logical_block_size")
Connor O'Brien20f08c32017-01-05 16:48:14 -0800822 copy_prop("flash_erase_block_size", "flash_erase_block_size")
Daniel Rosenberg6cc2c812019-12-17 17:36:31 -0800823 copy_prop("needs_casefold", "needs_casefold")
824 copy_prop("needs_projid", "needs_projid")
Jaegeuk Kimed754fb2020-10-12 19:50:05 -0700825 copy_prop("needs_compress", "needs_compress")
David Zeuthen4014a9d2016-09-30 17:29:22 -0400826 d["partition_name"] = mount_point
Ying Wangbd93d422011-10-28 17:02:30 -0700827 return d
828
829
830def LoadGlobalDict(filename):
831 """Load "name=value" pairs from filename"""
832 d = {}
833 f = open(filename)
834 for line in f:
835 line = line.strip()
836 if not line or line.startswith("#"):
837 continue
838 k, v = line.split("=", 1)
839 d[k] = v
840 f.close()
841 return d
842
843
Yifan Hongbbcba1e2018-06-18 16:32:35 -0700844def GlobalDictFromImageProp(image_prop, mount_point):
845 d = {}
Kelvin Zhang37bc3042022-12-15 10:31:34 -0800846
Yifan Hongbbcba1e2018-06-18 16:32:35 -0700847 def copy_prop(src_p, dest_p):
848 if src_p in image_prop:
849 d[dest_p] = image_prop[src_p]
850 return True
851 return False
Tao Bao4251fe92018-07-23 13:05:00 -0700852
Yifan Hongbbcba1e2018-06-18 16:32:35 -0700853 if mount_point == "system":
Tao Bao35f4ebc2018-09-27 15:31:11 -0700854 copy_prop("partition_size", "system_size")
Yifan Hongbbcba1e2018-06-18 16:32:35 -0700855 elif mount_point == "system_other":
Bowgo Tsai867ab662019-01-29 13:30:18 +0800856 copy_prop("partition_size", "system_other_size")
Yifan Hong749062d2018-06-19 16:23:16 -0700857 elif mount_point == "vendor":
Tao Bao35f4ebc2018-09-27 15:31:11 -0700858 copy_prop("partition_size", "vendor_size")
Bowgo Tsaid624fa62017-11-14 23:42:30 +0800859 elif mount_point == "odm":
Tao Bao35f4ebc2018-09-27 15:31:11 -0700860 copy_prop("partition_size", "odm_size")
Yifan Hongcfb917a2020-05-07 14:58:20 -0700861 elif mount_point == "vendor_dlkm":
862 copy_prop("partition_size", "vendor_dlkm_size")
Yifan Hongf496f1b2020-07-15 16:52:59 -0700863 elif mount_point == "odm_dlkm":
864 copy_prop("partition_size", "odm_dlkm_size")
Ramji Jiyani13a41372022-01-27 07:05:08 +0000865 elif mount_point == "system_dlkm":
866 copy_prop("partition_size", "system_dlkm_size")
Yifan Hong56a6c3b2018-07-20 15:19:34 -0700867 elif mount_point == "product":
Tao Bao35f4ebc2018-09-27 15:31:11 -0700868 copy_prop("partition_size", "product_size")
Justin Yun6151e3f2019-06-25 15:58:13 +0900869 elif mount_point == "system_ext":
870 copy_prop("partition_size", "system_ext_size")
Yifan Hongbbcba1e2018-06-18 16:32:35 -0700871 return d
872
873
Kelvin Zhang37bc3042022-12-15 10:31:34 -0800874def BuildVBMeta(in_dir, glob_dict, output_path):
875 """Creates a VBMeta image.
876
877 It generates the requested VBMeta image. The requested image could be for
878 top-level or chained VBMeta image, which is determined based on the name.
879
880 Args:
881 output_path: Path to generated vbmeta.img
882 partitions: A dict that's keyed by partition names with image paths as
883 values. Only valid partition names are accepted, as partitions listed
884 in common.AVB_PARTITIONS and custom partitions listed in
885 OPTIONS.info_dict.get("avb_custom_images_partition_list")
886 name: Name of the VBMeta partition, e.g. 'vbmeta', 'vbmeta_system'.
887 needed_partitions: Partitions whose descriptors should be included into the
888 generated VBMeta image.
889
890 Returns:
891 Path to the created image.
892
893 Raises:
894 AssertionError: On invalid input args.
895 """
896 vbmeta_partitions = common.AVB_PARTITIONS[:]
897 name = os.path.basename(output_path).rstrip(".img")
898 vbmeta_system = glob_dict.get("avb_vbmeta_system", "").strip()
899 vbmeta_vendor = glob_dict.get("avb_vbmeta_vendor", "").strip()
900 if "vbmeta_system" in name:
901 vbmeta_partitions = vbmeta_system.split()
902 elif "vbmeta_vendor" in name:
903 vbmeta_partitions = vbmeta_vendor.split()
904 else:
905 if vbmeta_system:
906 vbmeta_partitions = [
907 item for item in vbmeta_partitions
908 if item not in vbmeta_system.split()]
909 vbmeta_partitions.append("vbmeta_system")
910
911 if vbmeta_vendor:
912 vbmeta_partitions = [
913 item for item in vbmeta_partitions
914 if item not in vbmeta_vendor.split()]
915 vbmeta_partitions.append("vbmeta_vendor")
916
Kelvin Zhang37bc3042022-12-15 10:31:34 -0800917 partitions = {part: os.path.join(in_dir, part + ".img")
918 for part in vbmeta_partitions}
Kelvin Zhangc819b292023-06-02 16:41:19 -0700919 partitions = {part: path for (part, path) in partitions.items() if os.path.exists(path)}
Kelvin Zhang37bc3042022-12-15 10:31:34 -0800920 common.BuildVBMeta(output_path, partitions, name, vbmeta_partitions)
921
922
Cole Faust152cdfa2023-07-26 14:33:51 -0700923def BuildImageOrVBMeta(input_directory, target_out, glob_dict, image_properties, out_file):
924 try:
925 if "vbmeta" in os.path.basename(out_file):
926 OPTIONS.info_dict = glob_dict
927 BuildVBMeta(input_directory, glob_dict, out_file)
928 else:
929 BuildImage(input_directory, image_properties, out_file, target_out)
930 except:
931 logger.error("Failed to build %s from %s", out_file, input_directory)
932 raise
Firman Prayogadf217062023-09-08 01:24:39 +0000933
Cole Faust152cdfa2023-07-26 14:33:51 -0700934
935def CopyInputDirectory(src, dst, filter_file):
936 with open(filter_file, 'r') as f:
937 for line in f:
938 line = line.strip()
939 if not line:
940 return
941 if line != os.path.normpath(line):
942 sys.exit(f"{line}: not normalized")
943 if line.startswith("../") or line.startswith('/'):
944 sys.exit(f"{line}: escapes staging directory by starting with ../ or /")
945 full_src = os.path.join(src, line)
946 full_dst = os.path.join(dst, line)
947 if os.path.isdir(full_src):
948 os.makedirs(full_dst, exist_ok=True)
949 else:
950 os.makedirs(os.path.dirname(full_dst), exist_ok=True)
951 os.link(full_src, full_dst, follow_symlinks=False)
952
953
954def main(argv):
955 parser = argparse.ArgumentParser(
956 description="Builds output_image from the given input_directory and properties_file, and "
957 "writes the image to target_output_directory.")
958 parser.add_argument("--input-directory-filter-file",
959 help="the path to a file that contains a list of all files in the input_directory. If this "
960 "option is provided, all files under the input_directory that are not listed in this file will "
961 "be deleted before building the image. This is to work around the fact that building a module "
962 "will install in by default, so there could be files in the input_directory that are not "
963 "actually supposed to be part of the partition. The paths in this file must be relative to "
964 "input_directory.")
965 parser.add_argument("input_directory",
966 help="the staging directory to be converted to an image file")
967 parser.add_argument("properties_file",
968 help="a file containing the 'global dictionary' of properties that affect how the image is "
969 "built")
970 parser.add_argument("out_file",
971 help="the output file to write")
972 parser.add_argument("target_out",
973 help="the path to $(TARGET_OUT). Certain tools will use this to look through multiple staging "
974 "directories for fs config files.")
975 args = parser.parse_args()
Ying Wangbd93d422011-10-28 17:02:30 -0700976
Tao Bao32fcdab2018-10-12 10:30:39 -0700977 common.InitLogging()
978
Cole Faust152cdfa2023-07-26 14:33:51 -0700979 glob_dict = LoadGlobalDict(args.properties_file)
Ying Wangae61f502015-03-12 18:30:39 -0700980 if "mount_point" in glob_dict:
Mark Salyzyn780f5952018-10-19 13:44:36 -0700981 # The caller knows the mount point and provides a dictionary needed by
Tao Baoc7a6f1e2015-06-23 11:16:05 -0700982 # BuildImage().
Ying Wangae61f502015-03-12 18:30:39 -0700983 image_properties = glob_dict
Ying Wang9f8e8db2011-11-04 11:37:01 -0700984 else:
Cole Faust152cdfa2023-07-26 14:33:51 -0700985 image_filename = os.path.basename(args.out_file)
Ying Wangae61f502015-03-12 18:30:39 -0700986 mount_point = ""
987 if image_filename == "system.img":
988 mount_point = "system"
Alex Light4e358ab2016-06-16 14:47:10 -0700989 elif image_filename == "system_other.img":
990 mount_point = "system_other"
Ying Wangae61f502015-03-12 18:30:39 -0700991 elif image_filename == "userdata.img":
992 mount_point = "data"
993 elif image_filename == "cache.img":
994 mount_point = "cache"
995 elif image_filename == "vendor.img":
996 mount_point = "vendor"
Bowgo Tsaid624fa62017-11-14 23:42:30 +0800997 elif image_filename == "odm.img":
998 mount_point = "odm"
Yifan Hongcfb917a2020-05-07 14:58:20 -0700999 elif image_filename == "vendor_dlkm.img":
1000 mount_point = "vendor_dlkm"
Yifan Hongf496f1b2020-07-15 16:52:59 -07001001 elif image_filename == "odm_dlkm.img":
1002 mount_point = "odm_dlkm"
Ramji Jiyani13a41372022-01-27 07:05:08 +00001003 elif image_filename == "system_dlkm.img":
1004 mount_point = "system_dlkm"
Ying Wangae61f502015-03-12 18:30:39 -07001005 elif image_filename == "oem.img":
1006 mount_point = "oem"
Jaekyun Seokb7735d82017-11-27 17:04:47 +09001007 elif image_filename == "product.img":
1008 mount_point = "product"
Justin Yun6151e3f2019-06-25 15:58:13 +09001009 elif image_filename == "system_ext.img":
1010 mount_point = "system_ext"
Kelvin Zhang37bc3042022-12-15 10:31:34 -08001011 elif "vbmeta" in image_filename:
1012 mount_point = "vbmeta"
Ying Wangae61f502015-03-12 18:30:39 -07001013 else:
Tao Bao32fcdab2018-10-12 10:30:39 -07001014 logger.error("Unknown image file name %s", image_filename)
Tao Bao1c830bf2017-12-25 10:43:47 -08001015 sys.exit(1)
Ying Wangbd93d422011-10-28 17:02:30 -07001016
Kelvin Zhang37bc3042022-12-15 10:31:34 -08001017 if "vbmeta" != mount_point:
1018 image_properties = ImagePropFromGlobalDict(glob_dict, mount_point)
Ying Wangae61f502015-03-12 18:30:39 -07001019
Cole Faust152cdfa2023-07-26 14:33:51 -07001020 if args.input_directory_filter_file and not os.environ.get("BUILD_BROKEN_INCORRECT_PARTITION_IMAGES"):
1021 with tempfile.TemporaryDirectory(dir=os.path.dirname(args.input_directory)) as new_input_directory:
1022 CopyInputDirectory(args.input_directory, new_input_directory, args.input_directory_filter_file)
1023 BuildImageOrVBMeta(new_input_directory, args.target_out, glob_dict, image_properties, args.out_file)
1024 else:
1025 BuildImageOrVBMeta(args.input_directory, args.target_out, glob_dict, image_properties, args.out_file)
Ying Wangbd93d422011-10-28 17:02:30 -07001026
Tao Bao32fcdab2018-10-12 10:30:39 -07001027
Ying Wangbd93d422011-10-28 17:02:30 -07001028if __name__ == '__main__':
Tao Bao1c830bf2017-12-25 10:43:47 -08001029 try:
1030 main(sys.argv[1:])
1031 finally:
1032 common.Cleanup()