blob: 8c6d597b01674aaf5c05ade80aa58476fab4680f [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
Kelvin Zhangc819b292023-06-02 16:41:19 -070026import datetime
Tao Baoc72727a2017-12-07 10:33:00 -080027
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
Tao Baoc72727a2017-12-07 10:33:00 -080037
38import common
Tao Bao71197512018-10-11 14:08:45 -070039import verity_utils
Ying Wangbd93d422011-10-28 17:02:30 -070040
Kelvin Zhangc819b292023-06-02 16:41:19 -070041
Tao Bao32fcdab2018-10-12 10:30:39 -070042logger = logging.getLogger(__name__)
43
Baligh Uddin601ddea2015-06-09 15:48:14 -070044OPTIONS = common.OPTIONS
Tao Bao71197512018-10-11 14:08:45 -070045BLOCK_SIZE = common.BLOCK_SIZE
Yifan Hongbbcba1e2018-06-18 16:32:35 -070046BYTES_IN_MB = 1024 * 1024
Geremy Condrae8e982a2014-05-16 19:14:30 -070047
Kelvin Zhangc819b292023-06-02 16:41:19 -070048# Use a fixed timestamp (01/01/2009 00:00:00 UTC) for files when packaging
49# images. (b/24377993, b/80600931)
50FIXED_FILE_TIMESTAMP = int((
51 datetime.datetime(2009, 1, 1, 0, 0, 0, 0, None) -
52 datetime.datetime.utcfromtimestamp(0)).total_seconds())
53
Tao Baoc72727a2017-12-07 10:33:00 -080054
Tao Baoc6bd70a2018-09-27 16:58:00 -070055class BuildImageError(Exception):
56 """An Exception raised during image building."""
57
58 def __init__(self, message):
59 Exception.__init__(self, message)
60
61
Yifan Hongbbcba1e2018-06-18 16:32:35 -070062def GetDiskUsage(path):
Tao Baoc6bd70a2018-09-27 16:58:00 -070063 """Returns the number of bytes that "path" occupies on host.
Yifan Hongbbcba1e2018-06-18 16:32:35 -070064
65 Args:
Mark Salyzyn780f5952018-10-19 13:44:36 -070066 path: The directory or file to calculate size on.
Tao Baoc6bd70a2018-09-27 16:58:00 -070067
Yifan Hongbbcba1e2018-06-18 16:32:35 -070068 Returns:
Mark Salyzyn780f5952018-10-19 13:44:36 -070069 The number of bytes based on a 1K block_size.
Yifan Hongbbcba1e2018-06-18 16:32:35 -070070 """
Chirayu Desai96a913e2020-03-27 03:49:31 +053071 cmd = ["du", "-b", "-k", "-s", path]
Tao Baof3fc62c2018-10-25 12:23:12 -070072 output = common.RunAndCheckOutput(cmd, verbose=False)
Mark Salyzyn780f5952018-10-19 13:44:36 -070073 return int(output.split()[0]) * 1024
74
75
76def GetInodeUsage(path):
77 """Returns the number of inodes that "path" occupies on host.
78
79 Args:
80 path: The directory or file to calculate inode number on.
81
82 Returns:
83 The number of inodes used.
Mark Salyzyn780f5952018-10-19 13:44:36 -070084 """
85 cmd = ["find", path, "-print"]
Tao Baof3fc62c2018-10-25 12:23:12 -070086 output = common.RunAndCheckOutput(cmd, verbose=False)
David Anderson203057c2021-03-31 20:01:41 -070087 # increase by > 6% as number of files and directories is not whole picture.
Mark Salyzync25b2bf2019-01-16 08:03:10 -080088 inodes = output.count('\n')
David Anderson203057c2021-03-31 20:01:41 -070089 spare_inodes = inodes * 6 // 100
Mark Salyzyn60fa99d2019-01-16 08:03:10 -080090 min_spare_inodes = 12
Mark Salyzync25b2bf2019-01-16 08:03:10 -080091 if spare_inodes < min_spare_inodes:
92 spare_inodes = min_spare_inodes
93 return inodes + spare_inodes
Mark Salyzyn780f5952018-10-19 13:44:36 -070094
95
Jaegeuk Kim13696542021-05-22 09:47:48 -070096def GetFilesystemCharacteristics(fs_type, image_path, sparse_image=True):
Mark Salyzyn6541d0a2019-01-10 14:30:51 -080097 """Returns various filesystem characteristics of "image_path".
Mark Salyzyn780f5952018-10-19 13:44:36 -070098
99 Args:
Mark Salyzyn6541d0a2019-01-10 14:30:51 -0800100 image_path: The file to analyze.
101 sparse_image: Image is sparse
Mark Salyzyn780f5952018-10-19 13:44:36 -0700102
103 Returns:
104 The characteristics dictionary.
Mark Salyzyn780f5952018-10-19 13:44:36 -0700105 """
Mark Salyzyn6541d0a2019-01-10 14:30:51 -0800106 unsparse_image_path = image_path
107 if sparse_image:
108 unsparse_image_path = UnsparseImage(image_path, replace=False)
Mark Salyzyn780f5952018-10-19 13:44:36 -0700109
Jaegeuk Kim13696542021-05-22 09:47:48 -0700110 if fs_type.startswith("ext"):
111 cmd = ["tune2fs", "-l", unsparse_image_path]
112 elif fs_type.startswith("f2fs"):
113 cmd = ["fsck.f2fs", "-l", unsparse_image_path]
114
Mark Salyzyn780f5952018-10-19 13:44:36 -0700115 try:
116 output = common.RunAndCheckOutput(cmd, verbose=False)
Tao Baof3fc62c2018-10-25 12:23:12 -0700117 finally:
Mark Salyzyn6541d0a2019-01-10 14:30:51 -0800118 if sparse_image:
119 os.remove(unsparse_image_path)
Tao Baof3fc62c2018-10-25 12:23:12 -0700120 fs_dict = {}
Mark Salyzyn780f5952018-10-19 13:44:36 -0700121 for line in output.splitlines():
122 fields = line.split(":")
123 if len(fields) == 2:
124 fs_dict[fields[0].strip()] = fields[1].strip()
125 return fs_dict
Yifan Hongbbcba1e2018-06-18 16:32:35 -0700126
127
Geremy Condra6e8f53c2013-12-05 17:09:18 -0800128def UnsparseImage(sparse_image_path, replace=True):
Geremy Condrafd6f7512013-06-16 17:26:08 -0700129 img_dir = os.path.dirname(sparse_image_path)
130 unsparse_image_path = "unsparse_" + os.path.basename(sparse_image_path)
131 unsparse_image_path = os.path.join(img_dir, unsparse_image_path)
132 if os.path.exists(unsparse_image_path):
Geremy Condra6e8f53c2013-12-05 17:09:18 -0800133 if replace:
134 os.unlink(unsparse_image_path)
135 else:
Tao Baoc6bd70a2018-09-27 16:58:00 -0700136 return unsparse_image_path
Geremy Condrafd6f7512013-06-16 17:26:08 -0700137 inflate_command = ["simg2img", sparse_image_path, unsparse_image_path]
Tao Bao986ee862018-10-04 15:46:16 -0700138 try:
139 common.RunAndCheckOutput(inflate_command)
140 except:
Geremy Condrafd6f7512013-06-16 17:26:08 -0700141 os.remove(unsparse_image_path)
Tao Bao986ee862018-10-04 15:46:16 -0700142 raise
Tao Baoc6bd70a2018-09-27 16:58:00 -0700143 return unsparse_image_path
Geremy Condrafd6f7512013-06-16 17:26:08 -0700144
Tao Baoc72727a2017-12-07 10:33:00 -0800145
Mohamad Ayyashf8765552016-03-02 21:07:23 -0800146def ConvertBlockMapToBaseFs(block_map_file):
Tao Bao1c830bf2017-12-25 10:43:47 -0800147 base_fs_file = common.MakeTempFile(prefix="script_gen_", suffix=".base_fs")
Mohamad Ayyashf8765552016-03-02 21:07:23 -0800148 convert_command = ["blk_alloc_to_base_fs", block_map_file, base_fs_file]
Tao Bao986ee862018-10-04 15:46:16 -0700149 common.RunAndCheckOutput(convert_command)
Tao Baoc6bd70a2018-09-27 16:58:00 -0700150 return base_fs_file
Mohamad Ayyashf8765552016-03-02 21:07:23 -0800151
Tao Baod4349f22017-12-07 23:01:25 -0800152
Tao Baoc2606eb2018-07-20 14:44:46 -0700153def SetUpInDirAndFsConfig(origin_in, prop_dict):
154 """Returns the in_dir and fs_config that should be used for image building.
155
Tom Cherryd14b8952018-08-09 14:26:00 -0700156 When building system.img for all targets, it creates and returns a staged dir
157 that combines the contents of /system (i.e. in the given in_dir) and root.
Tao Baoc2606eb2018-07-20 14:44:46 -0700158
159 Args:
160 origin_in: Path to the input directory.
161 prop_dict: A property dict that contains info like partition size. Values
162 may be updated.
163
164 Returns:
165 A tuple of in_dir and fs_config that should be used to build the image.
166 """
167 fs_config = prop_dict.get("fs_config")
Tom Cherryd14b8952018-08-09 14:26:00 -0700168
169 if prop_dict["mount_point"] == "system_other":
170 prop_dict["mount_point"] = "system"
171 return origin_in, fs_config
172
173 if prop_dict["mount_point"] != "system":
Tao Baoc2606eb2018-07-20 14:44:46 -0700174 return origin_in, fs_config
175
Mark Salyzyn780f5952018-10-19 13:44:36 -0700176 if "first_pass" in prop_dict:
177 prop_dict["mount_point"] = "/"
178 return prop_dict["first_pass"]
179
Tao Baoc2606eb2018-07-20 14:44:46 -0700180 # Construct a staging directory of the root file system.
181 in_dir = common.MakeTempDir()
182 root_dir = prop_dict.get("root_dir")
183 if root_dir:
184 shutil.rmtree(in_dir)
185 shutil.copytree(root_dir, in_dir, symlinks=True)
186 in_dir_system = os.path.join(in_dir, "system")
187 shutil.rmtree(in_dir_system, ignore_errors=True)
188 shutil.copytree(origin_in, in_dir_system, symlinks=True)
189
190 # Change the mount point to "/".
191 prop_dict["mount_point"] = "/"
192 if fs_config:
193 # We need to merge the fs_config files of system and root.
194 merged_fs_config = common.MakeTempFile(
195 prefix="merged_fs_config", suffix=".txt")
196 with open(merged_fs_config, "w") as fw:
197 if "root_fs_config" in prop_dict:
198 with open(prop_dict["root_fs_config"]) as fr:
199 fw.writelines(fr.readlines())
200 with open(fs_config) as fr:
201 fw.writelines(fr.readlines())
202 fs_config = merged_fs_config
Mark Salyzyn780f5952018-10-19 13:44:36 -0700203 prop_dict["first_pass"] = (in_dir, fs_config)
Tao Baoc2606eb2018-07-20 14:44:46 -0700204 return in_dir, fs_config
205
206
Tao Baod4349f22017-12-07 23:01:25 -0800207def CheckHeadroom(ext4fs_output, prop_dict):
208 """Checks if there's enough headroom space available.
209
210 Headroom is the reserved space on system image (via PRODUCT_SYSTEM_HEADROOM),
211 which is useful for devices with low disk space that have system image
212 variation between builds. The 'partition_headroom' in prop_dict is the size
213 in bytes, while the numbers in 'ext4fs_output' are for 4K-blocks.
214
215 Args:
216 ext4fs_output: The output string from mke2fs command.
217 prop_dict: The property dict.
218
Tao Baod8a953d2018-01-02 21:19:27 -0800219 Raises:
220 AssertionError: On invalid input.
Tao Baoc6bd70a2018-09-27 16:58:00 -0700221 BuildImageError: On check failure.
Tao Baod4349f22017-12-07 23:01:25 -0800222 """
Tao Baod8a953d2018-01-02 21:19:27 -0800223 assert ext4fs_output is not None
224 assert prop_dict.get('fs_type', '').startswith('ext4')
225 assert 'partition_headroom' in prop_dict
226 assert 'mount_point' in prop_dict
227
Tao Baod4349f22017-12-07 23:01:25 -0800228 ext4fs_stats = re.compile(
229 r'Created filesystem with .* (?P<used_blocks>[0-9]+)/'
230 r'(?P<total_blocks>[0-9]+) blocks')
Tao Baoc72727a2017-12-07 10:33:00 -0800231 last_line = ext4fs_output.strip().split('\n')[-1]
232 m = ext4fs_stats.match(last_line)
Tao Baod4349f22017-12-07 23:01:25 -0800233 used_blocks = int(m.groupdict().get('used_blocks'))
234 total_blocks = int(m.groupdict().get('total_blocks'))
Mark Salyzyn780f5952018-10-19 13:44:36 -0700235 headroom_blocks = int(prop_dict['partition_headroom']) // BLOCK_SIZE
Tao Baod4349f22017-12-07 23:01:25 -0800236 adjusted_blocks = total_blocks - headroom_blocks
237 if used_blocks > adjusted_blocks:
Tao Baod8a953d2018-01-02 21:19:27 -0800238 mount_point = prop_dict["mount_point"]
Tao Baoc6bd70a2018-09-27 16:58:00 -0700239 raise BuildImageError(
240 "Error: Not enough room on {} (total: {} blocks, used: {} blocks, "
241 "headroom: {} blocks, available: {} blocks)".format(
242 mount_point, total_blocks, used_blocks, headroom_blocks,
243 adjusted_blocks))
Tao Baod4349f22017-12-07 23:01:25 -0800244
Kelvin Zhang37bc3042022-12-15 10:31:34 -0800245
Huang Jianan65527272021-09-08 18:28:32 +0800246def CalculateSizeAndReserved(prop_dict, size):
247 fs_type = prop_dict.get("fs_type", "")
248 partition_headroom = int(prop_dict.get("partition_headroom", 0))
249 # If not specified, give us 16MB margin for GetDiskUsage error ...
Kelvin Zhang37bc3042022-12-15 10:31:34 -0800250 reserved_size = int(prop_dict.get(
251 "partition_reserved_size", BYTES_IN_MB * 16))
Huang Jianan65527272021-09-08 18:28:32 +0800252
253 if fs_type == "erofs":
254 reserved_size = int(prop_dict.get("partition_reserved_size", 0))
255 if reserved_size == 0:
256 # give .3% margin or a minimum size for AVB footer
257 return max(size * 1003 // 1000, 256 * 1024)
258
259 if fs_type.startswith("ext4") and partition_headroom > reserved_size:
260 reserved_size = partition_headroom
261
262 return size + reserved_size
Tao Baod4349f22017-12-07 23:01:25 -0800263
Kelvin Zhang37bc3042022-12-15 10:31:34 -0800264
Mark Salyzyn3cd24602018-11-07 07:40:31 -0800265def BuildImageMkfs(in_dir, prop_dict, out_file, target_out, fs_config):
266 """Builds a pure image for the files under in_dir and writes it to out_file.
Tao Baoc2606eb2018-07-20 14:44:46 -0700267
Ying Wangbd93d422011-10-28 17:02:30 -0700268 Args:
Tao Baoc2606eb2018-07-20 14:44:46 -0700269 in_dir: Path to input directory.
270 prop_dict: A property dict that contains info like partition size. Values
271 will be updated with computed values.
272 out_file: The output image file.
273 target_out: Path to the TARGET_OUT directory as in Makefile. It actually
274 points to the /system directory under PRODUCT_OUT. fs_config (the one
275 under system/core/libcutils) reads device specific FS config files from
276 there.
Mark Salyzyn3cd24602018-11-07 07:40:31 -0800277 fs_config: The fs_config file that drives the prototype
Ying Wangbd93d422011-10-28 17:02:30 -0700278
Tao Baoc6bd70a2018-09-27 16:58:00 -0700279 Raises:
280 BuildImageError: On build image failures.
Ying Wangbd93d422011-10-28 17:02:30 -0700281 """
282 build_command = []
283 fs_type = prop_dict.get("fs_type", "")
David Anderson94ad5bb2022-03-04 10:57:58 -0800284 run_fsck = None
Daniel Rosenberg6cc2c812019-12-17 17:36:31 -0800285 needs_projid = prop_dict.get("needs_projid", 0)
286 needs_casefold = prop_dict.get("needs_casefold", 0)
Jaegeuk Kimed754fb2020-10-12 19:50:05 -0700287 needs_compress = prop_dict.get("needs_compress", 0)
Geremy Condrafd6f7512013-06-16 17:26:08 -0700288
David Anderson9e95a022021-08-31 21:32:45 -0700289 disable_sparse = "disable_sparse" in prop_dict
David Anderson94ad5bb2022-03-04 10:57:58 -0800290 manual_sparse = False
David Anderson9e95a022021-08-31 21:32:45 -0700291
Ying Wangbd93d422011-10-28 17:02:30 -0700292 if fs_type.startswith("ext"):
Adrien Schildknecht9a072cc2016-11-18 17:06:29 -0800293 build_command = [prop_dict["ext_mkuserimg"]]
David Anderson9e95a022021-08-31 21:32:45 -0700294 if "extfs_sparse_flag" in prop_dict and not disable_sparse:
Ying Wangbd93d422011-10-28 17:02:30 -0700295 build_command.append(prop_dict["extfs_sparse_flag"])
David Anderson94ad5bb2022-03-04 10:57:58 -0800296 run_e2fsck = RunE2fsck
Ying Wangbd93d422011-10-28 17:02:30 -0700297 build_command.extend([in_dir, out_file, fs_type,
298 prop_dict["mount_point"]])
Tao Bao35f4ebc2018-09-27 15:31:11 -0700299 build_command.append(prop_dict["image_size"])
Ying Wangf3b86352014-11-18 18:03:13 -0800300 if "journal_size" in prop_dict:
301 build_command.extend(["-j", prop_dict["journal_size"]])
Doug Zongker850b8072013-12-05 15:54:55 -0800302 if "timestamp" in prop_dict:
303 build_command.extend(["-T", str(prop_dict["timestamp"])])
Ying Wanga2292c92015-03-24 19:07:40 -0700304 if fs_config:
Doug Zongker82822822014-06-16 09:10:55 -0700305 build_command.extend(["-C", fs_config])
Thierry Strudel74a81e62015-07-09 09:54:55 -0700306 if target_out:
307 build_command.extend(["-D", target_out])
Ying Wanga2292c92015-03-24 19:07:40 -0700308 if "block_list" in prop_dict:
309 build_command.extend(["-B", prop_dict["block_list"]])
Mohamad Ayyashf8765552016-03-02 21:07:23 -0800310 if "base_fs_file" in prop_dict:
311 base_fs_file = ConvertBlockMapToBaseFs(prop_dict["base_fs_file"])
Mohamad Ayyashf8765552016-03-02 21:07:23 -0800312 build_command.extend(["-d", base_fs_file])
Christoffer Dall8ed01f32014-12-17 21:34:12 +0100313 build_command.extend(["-L", prop_dict["mount_point"]])
Patrick Tjina1900842016-10-20 10:58:12 -0700314 if "extfs_inode_count" in prop_dict:
315 build_command.extend(["-i", prop_dict["extfs_inode_count"]])
Patrick Tjin3f5f9932018-03-23 11:36:43 -0700316 if "extfs_rsv_pct" in prop_dict:
317 build_command.extend(["-M", prop_dict["extfs_rsv_pct"]])
Connor O'Brien20f08c32017-01-05 16:48:14 -0800318 if "flash_erase_block_size" in prop_dict:
319 build_command.extend(["-e", prop_dict["flash_erase_block_size"]])
320 if "flash_logical_block_size" in prop_dict:
321 build_command.extend(["-o", prop_dict["flash_logical_block_size"]])
Tao Baod86e3112017-09-22 15:45:33 -0700322 # Specify UUID and hash_seed if using mke2fs.
HÃ¥kan Kvist2e1f5272021-05-11 11:14:48 +0200323 if os.path.basename(prop_dict["ext_mkuserimg"]) == "mkuserimg_mke2fs":
Tao Baod86e3112017-09-22 15:45:33 -0700324 if "uuid" in prop_dict:
325 build_command.extend(["-U", prop_dict["uuid"]])
326 if "hash_seed" in prop_dict:
327 build_command.extend(["-S", prop_dict["hash_seed"]])
Tamas Petzc0a8c632020-02-03 15:41:02 +0100328 if prop_dict.get("ext4_share_dup_blocks") == "true":
Jin Qianfde9f792018-01-22 13:15:46 -0800329 build_command.append("-c")
Daniel Rosenberg6cc2c812019-12-17 17:36:31 -0800330 if (needs_projid):
331 build_command.extend(["--inode_size", "512"])
332 else:
333 build_command.extend(["--inode_size", "256"])
Ying Wanga2292c92015-03-24 19:07:40 -0700334 if "selinux_fc" in prop_dict:
Kenny Rootf32dc712012-04-08 10:42:34 -0700335 build_command.append(prop_dict["selinux_fc"])
Gao Xiang961041a2020-06-17 13:59:16 +0800336 elif fs_type.startswith("erofs"):
David Anderson94ad5bb2022-03-04 10:57:58 -0800337 build_command = ["mkfs.erofs"]
338
David Anderson40a821f2021-09-22 18:02:01 -0700339 compressor = None
340 if "erofs_default_compressor" in prop_dict:
341 compressor = prop_dict["erofs_default_compressor"]
342 if "erofs_compressor" in prop_dict:
343 compressor = prop_dict["erofs_compressor"]
David Andersonf3c81d72022-06-27 23:18:46 +0000344 if compressor and compressor != "none":
David Anderson40a821f2021-09-22 18:02:01 -0700345 build_command.extend(["-z", compressor])
David Anderson94ad5bb2022-03-04 10:57:58 -0800346
Dmitrii Merkurev8ab66032022-05-17 23:10:37 +0000347 compress_hints = None
348 if "erofs_default_compress_hints" in prop_dict:
349 compress_hints = prop_dict["erofs_default_compress_hints"]
350 if "erofs_compress_hints" in prop_dict:
351 compress_hints = prop_dict["erofs_compress_hints"]
352 if compress_hints:
353 build_command.extend(["--compress-hints", compress_hints])
354
David Anderson94ad5bb2022-03-04 10:57:58 -0800355 build_command.extend(["--mount-point", prop_dict["mount_point"]])
356 if target_out:
357 build_command.extend(["--product-out", target_out])
358 if fs_config:
359 build_command.extend(["--fs-config-file", fs_config])
360 if "selinux_fc" in prop_dict:
361 build_command.extend(["--file-contexts", prop_dict["selinux_fc"]])
David Andersond29e5372021-10-08 18:33:43 -0700362 if "timestamp" in prop_dict:
363 build_command.extend(["-T", str(prop_dict["timestamp"])])
364 if "uuid" in prop_dict:
365 build_command.extend(["-U", prop_dict["uuid"]])
366 if "block_list" in prop_dict:
David Anderson94ad5bb2022-03-04 10:57:58 -0800367 build_command.extend(["--block-list-file", prop_dict["block_list"]])
David Anderson64b351b2021-10-13 00:20:43 -0700368 if "erofs_pcluster_size" in prop_dict:
David Anderson94ad5bb2022-03-04 10:57:58 -0800369 build_command.extend(["-C", prop_dict["erofs_pcluster_size"]])
David Anderson64b351b2021-10-13 00:20:43 -0700370 if "erofs_share_dup_blocks" in prop_dict:
David Anderson94ad5bb2022-03-04 10:57:58 -0800371 build_command.extend(["--chunksize", "4096"])
David Andersonf54665f2022-03-04 14:42:18 -0800372 if "erofs_use_legacy_compression" in prop_dict:
373 build_command.extend(["-E", "legacy-compress"])
David Anderson94ad5bb2022-03-04 10:57:58 -0800374
375 build_command.extend([out_file, in_dir])
376 if "erofs_sparse_flag" in prop_dict and not disable_sparse:
377 manual_sparse = True
378
379 run_fsck = RunErofsFsck
Mohamad Ayyashb97746e2015-03-03 12:30:37 -0800380 elif fs_type.startswith("squash"):
Cole Faustb0002082022-09-05 18:34:56 -0700381 build_command = ["mksquashfsimage"]
Mohamad Ayyashb97746e2015-03-03 12:30:37 -0800382 build_command.extend([in_dir, out_file])
David Anderson9e95a022021-08-31 21:32:45 -0700383 if "squashfs_sparse_flag" in prop_dict and not disable_sparse:
Todd Poynorb2a555e2015-12-15 18:00:14 -0800384 build_command.extend([prop_dict["squashfs_sparse_flag"]])
Mohamad Ayyashb97746e2015-03-03 12:30:37 -0800385 build_command.extend(["-m", prop_dict["mount_point"]])
Thierry Strudel74a81e62015-07-09 09:54:55 -0700386 if target_out:
387 build_command.extend(["-d", target_out])
Mohamad Ayyash88378822016-04-07 22:10:51 -0700388 if fs_config:
389 build_command.extend(["-C", fs_config])
Ying Wanga2292c92015-03-24 19:07:40 -0700390 if "selinux_fc" in prop_dict:
Mohamad Ayyashb97746e2015-03-03 12:30:37 -0800391 build_command.extend(["-c", prop_dict["selinux_fc"]])
Mohamad Ayyashc3484f72016-06-13 09:46:58 -0700392 if "block_list" in prop_dict:
393 build_command.extend(["-B", prop_dict["block_list"]])
Ng Zhi An9446c1d2018-01-19 15:51:46 -0800394 if "squashfs_block_size" in prop_dict:
395 build_command.extend(["-b", prop_dict["squashfs_block_size"]])
Simon Wilsonf86e7ee2015-06-17 12:35:15 -0700396 if "squashfs_compressor" in prop_dict:
397 build_command.extend(["-z", prop_dict["squashfs_compressor"]])
398 if "squashfs_compressor_opt" in prop_dict:
399 build_command.extend(["-zo", prop_dict["squashfs_compressor_opt"]])
Tao Baoc72727a2017-12-07 10:33:00 -0800400 if prop_dict.get("squashfs_disable_4k_align") == "true":
Mohamad Ayyash1b6d3482016-06-15 15:53:07 -0700401 build_command.extend(["-a"])
JP Abgrall5bfed5a2014-06-16 14:17:40 -0700402 elif fs_type.startswith("f2fs"):
Cole Faustb0002082022-09-05 18:34:56 -0700403 build_command = ["mkf2fsuserimg"]
Tao Bao35f4ebc2018-09-27 15:31:11 -0700404 build_command.extend([out_file, prop_dict["image_size"]])
David Anderson9e95a022021-08-31 21:32:45 -0700405 if "f2fs_sparse_flag" in prop_dict and not disable_sparse:
Alistair Delva91238cc2019-10-16 10:53:41 -0700406 build_command.extend([prop_dict["f2fs_sparse_flag"]])
Jaegeuk Kim2ea1eba2017-11-28 19:21:28 -0800407 if fs_config:
408 build_command.extend(["-C", fs_config])
409 build_command.extend(["-f", in_dir])
410 if target_out:
411 build_command.extend(["-D", target_out])
412 if "selinux_fc" in prop_dict:
413 build_command.extend(["-s", prop_dict["selinux_fc"]])
414 build_command.extend(["-t", prop_dict["mount_point"]])
415 if "timestamp" in prop_dict:
416 build_command.extend(["-T", str(prop_dict["timestamp"])])
Jaegeuk Kim3dc47282021-06-13 08:54:01 -0700417 if "block_list" in prop_dict:
418 build_command.extend(["-B", prop_dict["block_list"]])
Jaegeuk Kim2ea1eba2017-11-28 19:21:28 -0800419 build_command.extend(["-L", prop_dict["mount_point"]])
Daniel Rosenberg6cc2c812019-12-17 17:36:31 -0800420 if (needs_projid):
421 build_command.append("--prjquota")
422 if (needs_casefold):
423 build_command.append("--casefold")
Jaegeuk Kim13696542021-05-22 09:47:48 -0700424 if (needs_compress or prop_dict.get("f2fs_compress") == "true"):
Jaegeuk Kimed754fb2020-10-12 19:50:05 -0700425 build_command.append("--compression")
Jaegeuk Kim551a2e62022-10-27 09:46:03 -0700426 if "ro_mount_point" in prop_dict:
Jaegeuk Kim46e0ea22021-05-20 23:13:59 -0700427 build_command.append("--readonly")
Jaegeuk Kim3dc47282021-06-13 08:54:01 -0700428 if (prop_dict.get("f2fs_compress") == "true"):
Robin Hsu3e51f422020-11-04 09:29:09 +0800429 build_command.append("--sldc")
Jaegeuk Kim13696542021-05-22 09:47:48 -0700430 if (prop_dict.get("f2fs_sldc_flags") == None):
Robin Hsu3e51f422020-11-04 09:29:09 +0800431 build_command.append(str(0))
432 else:
Jaegeuk Kim13696542021-05-22 09:47:48 -0700433 sldc_flags_str = prop_dict.get("f2fs_sldc_flags")
Robin Hsu3e51f422020-11-04 09:29:09 +0800434 sldc_flags = sldc_flags_str.split()
435 build_command.append(str(len(sldc_flags)))
436 build_command.extend(sldc_flags)
Ying Wangbd93d422011-10-28 17:02:30 -0700437 else:
Tao Baoc6bd70a2018-09-27 16:58:00 -0700438 raise BuildImageError(
439 "Error: unknown filesystem type: {}".format(fs_type))
Ying Wangbd93d422011-10-28 17:02:30 -0700440
Tao Bao986ee862018-10-04 15:46:16 -0700441 try:
442 mkfs_output = common.RunAndCheckOutput(build_command)
443 except:
Tao Baoc6bd70a2018-09-27 16:58:00 -0700444 try:
445 du = GetDiskUsage(in_dir)
446 du_str = "{} bytes ({} MB)".format(du, du // BYTES_IN_MB)
Tao Bao986ee862018-10-04 15:46:16 -0700447 # Suppress any errors from GetDiskUsage() to avoid hiding the real errors
448 # from common.RunAndCheckOutput().
Tao Bao32fcdab2018-10-12 10:30:39 -0700449 except Exception: # pylint: disable=broad-except
450 logger.exception("Failed to compute disk usage with du")
Tao Baoc6bd70a2018-09-27 16:58:00 -0700451 du_str = "unknown"
Tao Bao4251fe92018-07-23 13:05:00 -0700452 print(
Mark Salyzyn3cd24602018-11-07 07:40:31 -0800453 "Out of space? Out of inodes? The tree size of {} is {}, "
454 "with reserved space of {} bytes ({} MB).".format(
Tao Baoc2606eb2018-07-20 14:44:46 -0700455 in_dir, du_str,
Tao Bao4251fe92018-07-23 13:05:00 -0700456 int(prop_dict.get("partition_reserved_size", 0)),
457 int(prop_dict.get("partition_reserved_size", 0)) // BYTES_IN_MB))
Huang Jiananf63abb12021-04-29 15:24:50 +0800458 if ("image_size" in prop_dict and "partition_size" in prop_dict):
459 print(
460 "The max image size for filesystem files is {} bytes ({} MB), "
461 "out of a total partition size of {} bytes ({} MB).".format(
462 int(prop_dict["image_size"]),
463 int(prop_dict["image_size"]) // BYTES_IN_MB,
464 int(prop_dict["partition_size"]),
465 int(prop_dict["partition_size"]) // BYTES_IN_MB))
Tao Bao986ee862018-10-04 15:46:16 -0700466 raise
Ying Wang69e9b4d2012-11-26 18:10:23 -0800467
David Anderson94ad5bb2022-03-04 10:57:58 -0800468 if run_fsck and prop_dict.get("skip_fsck") != "true":
469 run_fsck(out_file)
Mark Salyzyn3cd24602018-11-07 07:40:31 -0800470
David Anderson94ad5bb2022-03-04 10:57:58 -0800471 if manual_sparse:
472 temp_file = out_file + ".sparse"
473 img2simg_argv = ["img2simg", out_file, temp_file]
474 common.RunAndCheckOutput(img2simg_argv)
475 os.rename(temp_file, out_file)
Mark Salyzyn3cd24602018-11-07 07:40:31 -0800476
477 return mkfs_output
478
David Anderson94ad5bb2022-03-04 10:57:58 -0800479
480def RunE2fsck(out_file):
481 unsparse_image = UnsparseImage(out_file, replace=False)
482
483 # Run e2fsck on the inflated image file
484 e2fsck_command = ["e2fsck", "-f", "-n", unsparse_image]
485 try:
486 common.RunAndCheckOutput(e2fsck_command)
487 finally:
488 os.remove(unsparse_image)
489
490
491def RunErofsFsck(out_file):
492 fsck_command = ["fsck.erofs", "--extract", out_file]
493 try:
494 common.RunAndCheckOutput(fsck_command)
495 except:
496 print("Check failed for EROFS image {}".format(out_file))
497 raise
498
499
Kelvin Zhangc819b292023-06-02 16:41:19 -0700500def SetUUIDIfNotExist(image_props):
501
502 # Use repeatable ext4 FS UUID and hash_seed UUID (based on partition name and
503 # build fingerprint). Also use the legacy build id, because the vbmeta digest
504 # isn't available at this point.
505 what = image_props["mount_point"]
506 fingerprint = image_props.get("fingerprint", "")
507 uuid_seed = what + "-" + fingerprint
508 logger.info("Using fingerprint %s for partition %s", fingerprint, what)
509 image_props["uuid"] = str(uuid.uuid5(uuid.NAMESPACE_URL, uuid_seed))
510 hash_seed = "hash_seed-" + uuid_seed
511 image_props["hash_seed"] = str(uuid.uuid5(uuid.NAMESPACE_URL, hash_seed))
512
513
Mark Salyzyn3cd24602018-11-07 07:40:31 -0800514def BuildImage(in_dir, prop_dict, out_file, target_out=None):
515 """Builds an image for the files under in_dir and writes it to out_file.
516
517 Args:
518 in_dir: Path to input directory.
519 prop_dict: A property dict that contains info like partition size. Values
520 will be updated with computed values.
521 out_file: The output image file.
522 target_out: Path to the TARGET_OUT directory as in Makefile. It actually
523 points to the /system directory under PRODUCT_OUT. fs_config (the one
524 under system/core/libcutils) reads device specific FS config files from
525 there.
526
527 Raises:
528 BuildImageError: On build image failures.
529 """
530 in_dir, fs_config = SetUpInDirAndFsConfig(in_dir, prop_dict)
Kelvin Zhangc819b292023-06-02 16:41:19 -0700531 SetUUIDIfNotExist(prop_dict)
Mark Salyzyn3cd24602018-11-07 07:40:31 -0800532
533 build_command = []
534 fs_type = prop_dict.get("fs_type", "")
535
536 fs_spans_partition = True
Huang Jianan62d926e2020-12-04 16:53:06 +0800537 if fs_type.startswith("squash") or fs_type.startswith("erofs"):
Mark Salyzyn3cd24602018-11-07 07:40:31 -0800538 fs_spans_partition = False
Jaegeuk Kim13696542021-05-22 09:47:48 -0700539 elif fs_type.startswith("f2fs") and prop_dict.get("f2fs_compress") == "true":
540 fs_spans_partition = False
Mark Salyzyn3cd24602018-11-07 07:40:31 -0800541
542 # Get a builder for creating an image that's to be verified by Verified Boot,
543 # or None if not applicable.
544 verity_image_builder = verity_utils.CreateVerityImageBuilder(prop_dict)
545
David Anderson9e95a022021-08-31 21:32:45 -0700546 disable_sparse = "disable_sparse" in prop_dict
Huang Jiananffa1d572021-09-08 18:11:22 +0800547 mkfs_output = None
Mark Salyzyn3cd24602018-11-07 07:40:31 -0800548 if (prop_dict.get("use_dynamic_partition_size") == "true" and
Kelvin Zhang37bc3042022-12-15 10:31:34 -0800549 "partition_size" not in prop_dict):
Mark Salyzyn3cd24602018-11-07 07:40:31 -0800550 # If partition_size is not defined, use output of `du' + reserved_size.
Huang Jianan35f015e2020-12-04 16:58:24 +0800551 # For compressed file system, it's better to use the compressed size to avoid wasting space.
552 if fs_type.startswith("erofs"):
Kelvin Zhang37bc3042022-12-15 10:31:34 -0800553 mkfs_output = BuildImageMkfs(
554 in_dir, prop_dict, out_file, target_out, fs_config)
Huang Jiananffa1d572021-09-08 18:11:22 +0800555 if "erofs_sparse_flag" in prop_dict and not disable_sparse:
556 image_path = UnsparseImage(out_file, replace=False)
557 size = GetDiskUsage(image_path)
558 os.remove(image_path)
559 else:
560 size = GetDiskUsage(out_file)
Huang Jianan35f015e2020-12-04 16:58:24 +0800561 else:
562 size = GetDiskUsage(in_dir)
Mark Salyzyn3cd24602018-11-07 07:40:31 -0800563 logger.info(
564 "The tree size of %s is %d MB.", in_dir, size // BYTES_IN_MB)
Huang Jianan65527272021-09-08 18:28:32 +0800565 size = CalculateSizeAndReserved(prop_dict, size)
Mark Salyzyn3cd24602018-11-07 07:40:31 -0800566 # Round this up to a multiple of 4K so that avbtool works
567 size = common.RoundUpTo4K(size)
568 if fs_type.startswith("ext"):
569 prop_dict["partition_size"] = str(size)
570 prop_dict["image_size"] = str(size)
571 if "extfs_inode_count" not in prop_dict:
572 prop_dict["extfs_inode_count"] = str(GetInodeUsage(in_dir))
573 logger.info(
574 "First Pass based on estimates of %d MB and %s inodes.",
575 size // BYTES_IN_MB, prop_dict["extfs_inode_count"])
576 BuildImageMkfs(in_dir, prop_dict, out_file, target_out, fs_config)
Mark Salyzyn6541d0a2019-01-10 14:30:51 -0800577 sparse_image = False
David Anderson9e95a022021-08-31 21:32:45 -0700578 if "extfs_sparse_flag" in prop_dict and not disable_sparse:
Mark Salyzyn6541d0a2019-01-10 14:30:51 -0800579 sparse_image = True
Jaegeuk Kim13696542021-05-22 09:47:48 -0700580 fs_dict = GetFilesystemCharacteristics(fs_type, out_file, sparse_image)
Mark Salyzyn3cd24602018-11-07 07:40:31 -0800581 os.remove(out_file)
582 block_size = int(fs_dict.get("Block size", "4096"))
583 free_size = int(fs_dict.get("Free blocks", "0")) * block_size
584 reserved_size = int(prop_dict.get("partition_reserved_size", 0))
585 partition_headroom = int(fs_dict.get("partition_headroom", 0))
586 if fs_type.startswith("ext4") and partition_headroom > reserved_size:
587 reserved_size = partition_headroom
588 if free_size <= reserved_size:
589 logger.info(
590 "Not worth reducing image %d <= %d.", free_size, reserved_size)
591 else:
592 size -= free_size
593 size += reserved_size
Mark Salyzyn60a716f2019-01-10 08:36:34 -0800594 if reserved_size == 0:
Mark Salyzync25b2bf2019-01-16 08:03:10 -0800595 # add .3% margin
596 size = size * 1003 // 1000
Mark Salyzyn60a716f2019-01-10 08:36:34 -0800597 # Use a minimum size, otherwise we will fail to calculate an AVB footer
598 # or fail to construct an ext4 image.
599 size = max(size, 256 * 1024)
Mark Salyzyn3cd24602018-11-07 07:40:31 -0800600 if block_size <= 4096:
601 size = common.RoundUpTo4K(size)
602 else:
603 size = ((size + block_size - 1) // block_size) * block_size
604 extfs_inode_count = prop_dict["extfs_inode_count"]
605 inodes = int(fs_dict.get("Inode count", extfs_inode_count))
606 inodes -= int(fs_dict.get("Free inodes", "0"))
Mark Salyzync25b2bf2019-01-16 08:03:10 -0800607 # add .2% margin or 1 inode, whichever is greater
608 spare_inodes = inodes * 2 // 1000
609 min_spare_inodes = 1
610 if spare_inodes < min_spare_inodes:
611 spare_inodes = min_spare_inodes
612 inodes += spare_inodes
Mark Salyzyn3cd24602018-11-07 07:40:31 -0800613 prop_dict["extfs_inode_count"] = str(inodes)
614 prop_dict["partition_size"] = str(size)
615 logger.info(
616 "Allocating %d Inodes for %s.", inodes, out_file)
Jaegeuk Kim13696542021-05-22 09:47:48 -0700617 elif fs_type.startswith("f2fs") and prop_dict.get("f2fs_compress") == "true":
618 prop_dict["partition_size"] = str(size)
619 prop_dict["image_size"] = str(size)
620 BuildImageMkfs(in_dir, prop_dict, out_file, target_out, fs_config)
621 sparse_image = False
David Anderson9e95a022021-08-31 21:32:45 -0700622 if "f2fs_sparse_flag" in prop_dict and not disable_sparse:
Jaegeuk Kim13696542021-05-22 09:47:48 -0700623 sparse_image = True
624 fs_dict = GetFilesystemCharacteristics(fs_type, out_file, sparse_image)
625 os.remove(out_file)
626 block_count = int(fs_dict.get("block_count", "0"))
627 log_blocksize = int(fs_dict.get("log_blocksize", "12"))
628 size = block_count << log_blocksize
629 prop_dict["partition_size"] = str(size)
Mark Salyzyn3cd24602018-11-07 07:40:31 -0800630 if verity_image_builder:
631 size = verity_image_builder.CalculateDynamicPartitionSize(size)
632 prop_dict["partition_size"] = str(size)
633 logger.info(
634 "Allocating %d MB for %s.", size // BYTES_IN_MB, out_file)
635
636 prop_dict["image_size"] = prop_dict["partition_size"]
637
638 # Adjust the image size to make room for the hashes if this is to be verified.
639 if verity_image_builder:
640 max_image_size = verity_image_builder.CalculateMaxImageSize()
641 prop_dict["image_size"] = str(max_image_size)
642
Huang Jiananffa1d572021-09-08 18:11:22 +0800643 if not mkfs_output:
Kelvin Zhang37bc3042022-12-15 10:31:34 -0800644 mkfs_output = BuildImageMkfs(
645 in_dir, prop_dict, out_file, target_out, fs_config)
Mark Salyzyn3cd24602018-11-07 07:40:31 -0800646
David Anderson009d6f82021-11-12 02:01:29 +0000647 # Update the image (eg filesystem size). This can be different eg if mkfs
648 # rounds the requested size down due to alignment.
649 prop_dict["image_size"] = common.sparse_img.GetImagePartitionSize(out_file)
650
Tao Baod4349f22017-12-07 23:01:25 -0800651 # Check if there's enough headroom space available for ext4 image.
Tao Bao79d52f82017-12-07 14:07:44 -0800652 if "partition_headroom" in prop_dict and fs_type.startswith("ext4"):
Tao Baoc6bd70a2018-09-27 16:58:00 -0700653 CheckHeadroom(mkfs_output, prop_dict)
Tao Baoc7a6f1e2015-06-23 11:16:05 -0700654
Tao Bao7549e5e2018-10-03 14:23:59 -0700655 if not fs_spans_partition and verity_image_builder:
656 verity_image_builder.PadSparseImage(out_file)
Mohamad Ayyashdd063522015-03-24 12:42:03 -0700657
Tao Baoc72727a2017-12-07 10:33:00 -0800658 # Create the verified image if this is to be verified.
Tao Bao7549e5e2018-10-03 14:23:59 -0700659 if verity_image_builder:
660 verity_image_builder.Build(out_file)
David Zeuthen4014a9d2016-09-30 17:29:22 -0400661
Kelvin Zhang37bc3042022-12-15 10:31:34 -0800662
Kelvin Zhangc819b292023-06-02 16:41:19 -0700663def TryParseFingerprint(glob_dict: dict):
664 for (key, val) in glob_dict.items():
665 if not key.endswith("_add_hashtree_footer_args") and not key.endswith("_add_hash_footer_args"):
666 continue
667 for arg in shlex.split(val):
668 m = re.match(r"^com\.android\.build\.\w+\.fingerprint:", arg)
669 if m is None:
670 continue
671 fingerprint = arg[len(m.group()):]
672 glob_dict["fingerprint"] = fingerprint
673 return
674
675
Ying Wangbd93d422011-10-28 17:02:30 -0700676def ImagePropFromGlobalDict(glob_dict, mount_point):
677 """Build an image property dictionary from the global dictionary.
678
679 Args:
680 glob_dict: the global dictionary from the build system.
681 mount_point: such as "system", "data" etc.
682 """
Doug Zongker1ad7ade2013-12-06 11:53:27 -0800683 d = {}
Kelvin Zhangc819b292023-06-02 16:41:19 -0700684 TryParseFingerprint(glob_dict)
Tao Bao052ae352015-09-28 13:44:13 -0700685
Justin Yun22ce9472023-07-15 15:35:07 +0900686 # Set fixed timestamp for building the OTA package.
687 if "use_fixed_timestamp" in glob_dict:
688 d["timestamp"] = FIXED_FILE_TIMESTAMP
Tao Bao822f5842015-09-30 16:01:14 -0700689 if "build.prop" in glob_dict:
Tianjie Xu0fde41e2020-05-09 05:24:18 +0000690 timestamp = glob_dict["build.prop"].GetProp("ro.build.date.utc")
691 if timestamp:
692 d["timestamp"] = timestamp
Ying Wang9f8e8db2011-11-04 11:37:01 -0700693
694 def copy_prop(src_p, dest_p):
Patrick Tjin3f5f9932018-03-23 11:36:43 -0700695 """Copy a property from the global dictionary.
696
697 Args:
698 src_p: The source property in the global dictionary.
699 dest_p: The destination property.
700 Returns:
701 True if property was found and copied, False otherwise.
702 """
Ying Wang9f8e8db2011-11-04 11:37:01 -0700703 if src_p in glob_dict:
704 d[dest_p] = str(glob_dict[src_p])
Patrick Tjin3f5f9932018-03-23 11:36:43 -0700705 return True
706 return False
Ying Wang9f8e8db2011-11-04 11:37:01 -0700707
Ying Wangbd93d422011-10-28 17:02:30 -0700708 common_props = (
Ying Wangbd93d422011-10-28 17:02:30 -0700709 "extfs_sparse_flag",
David Anderson40a821f2021-09-22 18:02:01 -0700710 "erofs_default_compressor",
Dmitrii Merkurev8ab66032022-05-17 23:10:37 +0000711 "erofs_default_compress_hints",
David Anderson64b351b2021-10-13 00:20:43 -0700712 "erofs_pcluster_size",
713 "erofs_share_dup_blocks",
Gao Xiang961041a2020-06-17 13:59:16 +0800714 "erofs_sparse_flag",
David Andersonf54665f2022-03-04 14:42:18 -0800715 "erofs_use_legacy_compression",
Todd Poynorb2a555e2015-12-15 18:00:14 -0800716 "squashfs_sparse_flag",
Jaegeuk Kim13696542021-05-22 09:47:48 -0700717 "system_f2fs_compress",
Robin Hsu3e51f422020-11-04 09:29:09 +0800718 "system_f2fs_sldc_flags",
Alistair Delva91238cc2019-10-16 10:53:41 -0700719 "f2fs_sparse_flag",
Ying Wang6a42a252013-02-27 13:54:02 -0800720 "skip_fsck",
Adrien Schildknecht9a072cc2016-11-18 17:06:29 -0800721 "ext_mkuserimg",
Bowgo Tsai3e599ea2017-05-26 18:30:04 +0800722 "avb_enable",
Tao Bao2b6dfd62017-09-27 17:17:43 -0700723 "avb_avbtool",
Yifan Hong2dae5722018-07-31 12:47:27 -0700724 "use_dynamic_partition_size",
Kelvin Zhangc819b292023-06-02 16:41:19 -0700725 "fingerprint",
Tao Bao2b6dfd62017-09-27 17:17:43 -0700726 )
Ying Wangbd93d422011-10-28 17:02:30 -0700727 for p in common_props:
Ying Wang9f8e8db2011-11-04 11:37:01 -0700728 copy_prop(p, p)
Ying Wangbd93d422011-10-28 17:02:30 -0700729
David Anderson271dab62021-10-11 17:31:26 -0700730 ro_mount_points = set([
731 "odm",
732 "odm_dlkm",
733 "oem",
734 "product",
735 "system",
Ramji Jiyani13a41372022-01-27 07:05:08 +0000736 "system_dlkm",
David Anderson271dab62021-10-11 17:31:26 -0700737 "system_ext",
738 "system_other",
739 "vendor",
740 "vendor_dlkm",
741 ])
David Andersonaac502f2021-09-23 15:48:29 -0700742
David Anderson271dab62021-10-11 17:31:26 -0700743 # Tuple layout: (readonly, specific prop, general prop)
744 fmt_props = (
745 # Generic first, then specific file type.
746 (False, "fs_type", "fs_type"),
747 (False, "{}_fs_type", "fs_type"),
748
749 # Ordering for these doesn't matter.
750 (False, "{}_selinux_fc", "selinux_fc"),
751 (False, "{}_size", "partition_size"),
752 (True, "avb_{}_add_hashtree_footer_args", "avb_add_hashtree_footer_args"),
753 (True, "avb_{}_algorithm", "avb_algorithm"),
754 (True, "avb_{}_hashtree_enable", "avb_hashtree_enable"),
755 (True, "avb_{}_key_path", "avb_key_path"),
756 (True, "avb_{}_salt", "avb_salt"),
David Andersonf54665f2022-03-04 14:42:18 -0800757 (True, "erofs_use_legacy_compression", "erofs_use_legacy_compression"),
David Anderson271dab62021-10-11 17:31:26 -0700758 (True, "ext4_share_dup_blocks", "ext4_share_dup_blocks"),
759 (True, "{}_base_fs_file", "base_fs_file"),
760 (True, "{}_disable_sparse", "disable_sparse"),
761 (True, "{}_erofs_compressor", "erofs_compressor"),
Dmitrii Merkurev8ab66032022-05-17 23:10:37 +0000762 (True, "{}_erofs_compress_hints", "erofs_compress_hints"),
David Anderson64b351b2021-10-13 00:20:43 -0700763 (True, "{}_erofs_pcluster_size", "erofs_pcluster_size"),
764 (True, "{}_erofs_share_dup_blocks", "erofs_share_dup_blocks"),
David Anderson271dab62021-10-11 17:31:26 -0700765 (True, "{}_extfs_inode_count", "extfs_inode_count"),
766 (True, "{}_f2fs_compress", "f2fs_compress"),
767 (True, "{}_f2fs_sldc_flags", "f2fs_sldc_flags"),
768 (True, "{}_reserved_size", "partition_reserved_size"),
769 (True, "{}_squashfs_block_size", "squashfs_block_size"),
770 (True, "{}_squashfs_compressor", "squashfs_compressor"),
771 (True, "{}_squashfs_compressor_opt", "squashfs_compressor_opt"),
772 (True, "{}_squashfs_disable_4k_align", "squashfs_disable_4k_align"),
773 (True, "{}_verity_block_device", "verity_block_device"),
774 )
775
776 # Translate prefixed properties into generic ones.
777 if mount_point == "data":
778 prefix = "userdata"
779 else:
780 prefix = mount_point
781
782 for readonly, src_prop, dest_prop in fmt_props:
783 if readonly and mount_point not in ro_mount_points:
784 continue
785
786 if src_prop == "fs_type":
787 # This property is legacy and only used on a few partitions. b/202600377
788 allowed_partitions = set(["system", "system_other", "data", "oem"])
789 if mount_point not in allowed_partitions:
Kelvin Zhang37bc3042022-12-15 10:31:34 -0800790 continue
David Anderson271dab62021-10-11 17:31:26 -0700791
Po Hu1c48b592022-02-18 09:10:22 +0000792 if (mount_point == "system_other") and (dest_prop != "partition_size"):
David Anderson271dab62021-10-11 17:31:26 -0700793 # Propagate system properties to system_other. They'll get overridden
794 # after as needed.
795 copy_prop(src_prop.format("system"), dest_prop)
796
797 copy_prop(src_prop.format(prefix), dest_prop)
798
799 # Set prefixed properties that need a default value.
800 if mount_point in ro_mount_points:
801 prop = "{}_journal_size".format(prefix)
802 if not copy_prop(prop, "journal_size"):
803 d["journal_size"] = "0"
804
805 prop = "{}_extfs_rsv_pct".format(prefix)
806 if not copy_prop(prop, "extfs_rsv_pct"):
807 d["extfs_rsv_pct"] = "0"
808
Jaegeuk Kim551a2e62022-10-27 09:46:03 -0700809 d["ro_mount_point"] = "1"
810
David Anderson271dab62021-10-11 17:31:26 -0700811 # Copy partition-specific properties.
Ying Wangbd93d422011-10-28 17:02:30 -0700812 d["mount_point"] = mount_point
813 if mount_point == "system":
Julius D'souza001c6762017-05-03 13:43:27 -0700814 copy_prop("system_headroom", "partition_headroom")
Tao Baof3282b42015-04-01 11:21:55 -0700815 copy_prop("system_root_image", "system_root_image")
Tao Bao8bfd3c72018-07-20 15:20:28 -0700816 copy_prop("root_dir", "root_dir")
817 copy_prop("root_fs_config", "root_fs_config")
Ying Wangbd93d422011-10-28 17:02:30 -0700818 elif mount_point == "data":
JP Abgrall5bfed5a2014-06-16 14:17:40 -0700819 # Copy the generic fs type first, override with specific one if available.
Tao Baoc72727a2017-12-07 10:33:00 -0800820 copy_prop("flash_logical_block_size", "flash_logical_block_size")
Connor O'Brien20f08c32017-01-05 16:48:14 -0800821 copy_prop("flash_erase_block_size", "flash_erase_block_size")
Daniel Rosenberg6cc2c812019-12-17 17:36:31 -0800822 copy_prop("needs_casefold", "needs_casefold")
823 copy_prop("needs_projid", "needs_projid")
Jaegeuk Kimed754fb2020-10-12 19:50:05 -0700824 copy_prop("needs_compress", "needs_compress")
David Zeuthen4014a9d2016-09-30 17:29:22 -0400825 d["partition_name"] = mount_point
Ying Wangbd93d422011-10-28 17:02:30 -0700826 return d
827
828
829def LoadGlobalDict(filename):
830 """Load "name=value" pairs from filename"""
831 d = {}
832 f = open(filename)
833 for line in f:
834 line = line.strip()
835 if not line or line.startswith("#"):
836 continue
837 k, v = line.split("=", 1)
838 d[k] = v
839 f.close()
840 return d
841
842
Yifan Hongbbcba1e2018-06-18 16:32:35 -0700843def GlobalDictFromImageProp(image_prop, mount_point):
844 d = {}
Kelvin Zhang37bc3042022-12-15 10:31:34 -0800845
Yifan Hongbbcba1e2018-06-18 16:32:35 -0700846 def copy_prop(src_p, dest_p):
847 if src_p in image_prop:
848 d[dest_p] = image_prop[src_p]
849 return True
850 return False
Tao Bao4251fe92018-07-23 13:05:00 -0700851
Yifan Hongbbcba1e2018-06-18 16:32:35 -0700852 if mount_point == "system":
Tao Bao35f4ebc2018-09-27 15:31:11 -0700853 copy_prop("partition_size", "system_size")
Yifan Hongbbcba1e2018-06-18 16:32:35 -0700854 elif mount_point == "system_other":
Bowgo Tsai867ab662019-01-29 13:30:18 +0800855 copy_prop("partition_size", "system_other_size")
Yifan Hong749062d2018-06-19 16:23:16 -0700856 elif mount_point == "vendor":
Tao Bao35f4ebc2018-09-27 15:31:11 -0700857 copy_prop("partition_size", "vendor_size")
Bowgo Tsaid624fa62017-11-14 23:42:30 +0800858 elif mount_point == "odm":
Tao Bao35f4ebc2018-09-27 15:31:11 -0700859 copy_prop("partition_size", "odm_size")
Yifan Hongcfb917a2020-05-07 14:58:20 -0700860 elif mount_point == "vendor_dlkm":
861 copy_prop("partition_size", "vendor_dlkm_size")
Yifan Hongf496f1b2020-07-15 16:52:59 -0700862 elif mount_point == "odm_dlkm":
863 copy_prop("partition_size", "odm_dlkm_size")
Ramji Jiyani13a41372022-01-27 07:05:08 +0000864 elif mount_point == "system_dlkm":
865 copy_prop("partition_size", "system_dlkm_size")
Yifan Hong56a6c3b2018-07-20 15:19:34 -0700866 elif mount_point == "product":
Tao Bao35f4ebc2018-09-27 15:31:11 -0700867 copy_prop("partition_size", "product_size")
Justin Yun6151e3f2019-06-25 15:58:13 +0900868 elif mount_point == "system_ext":
869 copy_prop("partition_size", "system_ext_size")
Yifan Hongbbcba1e2018-06-18 16:32:35 -0700870 return d
871
872
Kelvin Zhang37bc3042022-12-15 10:31:34 -0800873def BuildVBMeta(in_dir, glob_dict, output_path):
874 """Creates a VBMeta image.
875
876 It generates the requested VBMeta image. The requested image could be for
877 top-level or chained VBMeta image, which is determined based on the name.
878
879 Args:
880 output_path: Path to generated vbmeta.img
881 partitions: A dict that's keyed by partition names with image paths as
882 values. Only valid partition names are accepted, as partitions listed
883 in common.AVB_PARTITIONS and custom partitions listed in
884 OPTIONS.info_dict.get("avb_custom_images_partition_list")
885 name: Name of the VBMeta partition, e.g. 'vbmeta', 'vbmeta_system'.
886 needed_partitions: Partitions whose descriptors should be included into the
887 generated VBMeta image.
888
889 Returns:
890 Path to the created image.
891
892 Raises:
893 AssertionError: On invalid input args.
894 """
895 vbmeta_partitions = common.AVB_PARTITIONS[:]
896 name = os.path.basename(output_path).rstrip(".img")
897 vbmeta_system = glob_dict.get("avb_vbmeta_system", "").strip()
898 vbmeta_vendor = glob_dict.get("avb_vbmeta_vendor", "").strip()
899 if "vbmeta_system" in name:
900 vbmeta_partitions = vbmeta_system.split()
901 elif "vbmeta_vendor" in name:
902 vbmeta_partitions = vbmeta_vendor.split()
903 else:
904 if vbmeta_system:
905 vbmeta_partitions = [
906 item for item in vbmeta_partitions
907 if item not in vbmeta_system.split()]
908 vbmeta_partitions.append("vbmeta_system")
909
910 if vbmeta_vendor:
911 vbmeta_partitions = [
912 item for item in vbmeta_partitions
913 if item not in vbmeta_vendor.split()]
914 vbmeta_partitions.append("vbmeta_vendor")
915
Kelvin Zhang37bc3042022-12-15 10:31:34 -0800916 partitions = {part: os.path.join(in_dir, part + ".img")
917 for part in vbmeta_partitions}
Kelvin Zhangc819b292023-06-02 16:41:19 -0700918 partitions = {part: path for (part, path) in partitions.items() if os.path.exists(path)}
Kelvin Zhang37bc3042022-12-15 10:31:34 -0800919 common.BuildVBMeta(output_path, partitions, name, vbmeta_partitions)
920
921
Ying Wangbd93d422011-10-28 17:02:30 -0700922def main(argv):
Jooyung Hand9d0d692022-04-22 01:51:34 +0900923 args = common.ParseOptions(argv, __doc__)
924
925 if len(args) != 4:
Tao Baoc72727a2017-12-07 10:33:00 -0800926 print(__doc__)
Ying Wangbd93d422011-10-28 17:02:30 -0700927 sys.exit(1)
928
Tao Bao32fcdab2018-10-12 10:30:39 -0700929 common.InitLogging()
930
Jooyung Hand9d0d692022-04-22 01:51:34 +0900931 in_dir = args[0]
932 glob_dict_file = args[1]
933 out_file = args[2]
934 target_out = args[3]
Ying Wangbd93d422011-10-28 17:02:30 -0700935
936 glob_dict = LoadGlobalDict(glob_dict_file)
Ying Wangae61f502015-03-12 18:30:39 -0700937 if "mount_point" in glob_dict:
Mark Salyzyn780f5952018-10-19 13:44:36 -0700938 # The caller knows the mount point and provides a dictionary needed by
Tao Baoc7a6f1e2015-06-23 11:16:05 -0700939 # BuildImage().
Ying Wangae61f502015-03-12 18:30:39 -0700940 image_properties = glob_dict
Ying Wang9f8e8db2011-11-04 11:37:01 -0700941 else:
Ying Wangae61f502015-03-12 18:30:39 -0700942 image_filename = os.path.basename(out_file)
943 mount_point = ""
944 if image_filename == "system.img":
945 mount_point = "system"
Alex Light4e358ab2016-06-16 14:47:10 -0700946 elif image_filename == "system_other.img":
947 mount_point = "system_other"
Ying Wangae61f502015-03-12 18:30:39 -0700948 elif image_filename == "userdata.img":
949 mount_point = "data"
950 elif image_filename == "cache.img":
951 mount_point = "cache"
952 elif image_filename == "vendor.img":
953 mount_point = "vendor"
Bowgo Tsaid624fa62017-11-14 23:42:30 +0800954 elif image_filename == "odm.img":
955 mount_point = "odm"
Yifan Hongcfb917a2020-05-07 14:58:20 -0700956 elif image_filename == "vendor_dlkm.img":
957 mount_point = "vendor_dlkm"
Yifan Hongf496f1b2020-07-15 16:52:59 -0700958 elif image_filename == "odm_dlkm.img":
959 mount_point = "odm_dlkm"
Ramji Jiyani13a41372022-01-27 07:05:08 +0000960 elif image_filename == "system_dlkm.img":
961 mount_point = "system_dlkm"
Ying Wangae61f502015-03-12 18:30:39 -0700962 elif image_filename == "oem.img":
963 mount_point = "oem"
Jaekyun Seokb7735d82017-11-27 17:04:47 +0900964 elif image_filename == "product.img":
965 mount_point = "product"
Justin Yun6151e3f2019-06-25 15:58:13 +0900966 elif image_filename == "system_ext.img":
967 mount_point = "system_ext"
Kelvin Zhang37bc3042022-12-15 10:31:34 -0800968 elif "vbmeta" in image_filename:
969 mount_point = "vbmeta"
Ying Wangae61f502015-03-12 18:30:39 -0700970 else:
Tao Bao32fcdab2018-10-12 10:30:39 -0700971 logger.error("Unknown image file name %s", image_filename)
Tao Bao1c830bf2017-12-25 10:43:47 -0800972 sys.exit(1)
Ying Wangbd93d422011-10-28 17:02:30 -0700973
Kelvin Zhang37bc3042022-12-15 10:31:34 -0800974 if "vbmeta" != mount_point:
975 image_properties = ImagePropFromGlobalDict(glob_dict, mount_point)
Ying Wangae61f502015-03-12 18:30:39 -0700976
Tao Baoc6bd70a2018-09-27 16:58:00 -0700977 try:
Kelvin Zhang37bc3042022-12-15 10:31:34 -0800978 if "vbmeta" in os.path.basename(out_file):
979 OPTIONS.info_dict = glob_dict
980 BuildVBMeta(in_dir, glob_dict, out_file)
981 else:
982 BuildImage(in_dir, image_properties, out_file, target_out)
Tao Baoc6bd70a2018-09-27 16:58:00 -0700983 except:
Tao Bao32fcdab2018-10-12 10:30:39 -0700984 logger.error("Failed to build %s from %s", out_file, in_dir)
Tao Baoc6bd70a2018-09-27 16:58:00 -0700985 raise
Ying Wangbd93d422011-10-28 17:02:30 -0700986
Tao Bao32fcdab2018-10-12 10:30:39 -0700987
Ying Wangbd93d422011-10-28 17:02:30 -0700988if __name__ == '__main__':
Tao Bao1c830bf2017-12-25 10:43:47 -0800989 try:
990 main(sys.argv[1:])
991 finally:
992 common.Cleanup()