blob: 8a5d627b36afce5d928e273b12274afcfac19a14 [file] [log] [blame]
Ying Wangbd93d422011-10-28 17:02:30 -07001#!/usr/bin/env python
2#
3# Copyright (C) 2011 The Android Open Source Project
4#
5# Licensed under the Apache License, Version 2.0 (the "License");
6# you may not use this file except in compliance with the License.
7# You may obtain a copy of the License at
8#
9# http://www.apache.org/licenses/LICENSE-2.0
10#
11# Unless required by applicable law or agreed to in writing, software
12# distributed under the License is distributed on an "AS IS" BASIS,
13# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14# See the License for the specific language governing permissions and
15# limitations under the License.
16
17"""
Tao Baoc72727a2017-12-07 10:33:00 -080018Builds output_image from the given input_directory, properties_file,
19and writes the image to target_output_directory.
Ying Wangbd93d422011-10-28 17:02:30 -070020
Tao Bao2bbb07c2019-05-07 13:12:21 -070021Usage: build_image input_directory properties_file output_image \\
Yifan Hong8c3dce02019-04-09 17:03:57 +000022 target_output_directory
Ying Wangbd93d422011-10-28 17:02:30 -070023"""
Tao Baoc72727a2017-12-07 10:33:00 -080024
25from __future__ import print_function
26
Inseob Kim9cda3972021-10-12 22:59:12 +090027import glob
Tao Bao32fcdab2018-10-12 10:30:39 -070028import logging
Ying Wangbd93d422011-10-28 17:02:30 -070029import os
Ying Wang69e9b4d2012-11-26 18:10:23 -080030import os.path
Tao Baoc7a6f1e2015-06-23 11:16:05 -070031import re
Geremy Condrafd6f7512013-06-16 17:26:08 -070032import shutil
Tao Baoc72727a2017-12-07 10:33:00 -080033import sys
34
35import common
Tao Bao71197512018-10-11 14:08:45 -070036import verity_utils
Ying Wangbd93d422011-10-28 17:02:30 -070037
Inseob Kimf69346e2021-10-13 15:16:33 +090038from fsverity_digests_pb2 import FSVerityDigests
Inseob Kim9cda3972021-10-12 22:59:12 +090039from fsverity_metadata_generator import FSVerityMetadataGenerator
40
Tao Bao32fcdab2018-10-12 10:30:39 -070041logger = logging.getLogger(__name__)
42
Baligh Uddin601ddea2015-06-09 15:48:14 -070043OPTIONS = common.OPTIONS
Tao Bao71197512018-10-11 14:08:45 -070044BLOCK_SIZE = common.BLOCK_SIZE
Yifan Hongbbcba1e2018-06-18 16:32:35 -070045BYTES_IN_MB = 1024 * 1024
Geremy Condrae8e982a2014-05-16 19:14:30 -070046
Tao Baoc72727a2017-12-07 10:33:00 -080047
Tao Baoc6bd70a2018-09-27 16:58:00 -070048class BuildImageError(Exception):
49 """An Exception raised during image building."""
50
51 def __init__(self, message):
52 Exception.__init__(self, message)
53
54
Yifan Hongbbcba1e2018-06-18 16:32:35 -070055def GetDiskUsage(path):
Tao Baoc6bd70a2018-09-27 16:58:00 -070056 """Returns the number of bytes that "path" occupies on host.
Yifan Hongbbcba1e2018-06-18 16:32:35 -070057
58 Args:
Mark Salyzyn780f5952018-10-19 13:44:36 -070059 path: The directory or file to calculate size on.
Tao Baoc6bd70a2018-09-27 16:58:00 -070060
Yifan Hongbbcba1e2018-06-18 16:32:35 -070061 Returns:
Mark Salyzyn780f5952018-10-19 13:44:36 -070062 The number of bytes based on a 1K block_size.
Yifan Hongbbcba1e2018-06-18 16:32:35 -070063 """
Chirayu Desai96a913e2020-03-27 03:49:31 +053064 cmd = ["du", "-b", "-k", "-s", path]
Tao Baof3fc62c2018-10-25 12:23:12 -070065 output = common.RunAndCheckOutput(cmd, verbose=False)
Mark Salyzyn780f5952018-10-19 13:44:36 -070066 return int(output.split()[0]) * 1024
67
68
69def GetInodeUsage(path):
70 """Returns the number of inodes that "path" occupies on host.
71
72 Args:
73 path: The directory or file to calculate inode number on.
74
75 Returns:
76 The number of inodes used.
Mark Salyzyn780f5952018-10-19 13:44:36 -070077 """
78 cmd = ["find", path, "-print"]
Tao Baof3fc62c2018-10-25 12:23:12 -070079 output = common.RunAndCheckOutput(cmd, verbose=False)
David Anderson203057c2021-03-31 20:01:41 -070080 # increase by > 6% as number of files and directories is not whole picture.
Mark Salyzync25b2bf2019-01-16 08:03:10 -080081 inodes = output.count('\n')
David Anderson203057c2021-03-31 20:01:41 -070082 spare_inodes = inodes * 6 // 100
Mark Salyzyn60fa99d2019-01-16 08:03:10 -080083 min_spare_inodes = 12
Mark Salyzync25b2bf2019-01-16 08:03:10 -080084 if spare_inodes < min_spare_inodes:
85 spare_inodes = min_spare_inodes
86 return inodes + spare_inodes
Mark Salyzyn780f5952018-10-19 13:44:36 -070087
88
Jaegeuk Kim13696542021-05-22 09:47:48 -070089def GetFilesystemCharacteristics(fs_type, image_path, sparse_image=True):
Mark Salyzyn6541d0a2019-01-10 14:30:51 -080090 """Returns various filesystem characteristics of "image_path".
Mark Salyzyn780f5952018-10-19 13:44:36 -070091
92 Args:
Mark Salyzyn6541d0a2019-01-10 14:30:51 -080093 image_path: The file to analyze.
94 sparse_image: Image is sparse
Mark Salyzyn780f5952018-10-19 13:44:36 -070095
96 Returns:
97 The characteristics dictionary.
Mark Salyzyn780f5952018-10-19 13:44:36 -070098 """
Mark Salyzyn6541d0a2019-01-10 14:30:51 -080099 unsparse_image_path = image_path
100 if sparse_image:
101 unsparse_image_path = UnsparseImage(image_path, replace=False)
Mark Salyzyn780f5952018-10-19 13:44:36 -0700102
Jaegeuk Kim13696542021-05-22 09:47:48 -0700103 if fs_type.startswith("ext"):
104 cmd = ["tune2fs", "-l", unsparse_image_path]
105 elif fs_type.startswith("f2fs"):
106 cmd = ["fsck.f2fs", "-l", unsparse_image_path]
107
Mark Salyzyn780f5952018-10-19 13:44:36 -0700108 try:
109 output = common.RunAndCheckOutput(cmd, verbose=False)
Tao Baof3fc62c2018-10-25 12:23:12 -0700110 finally:
Mark Salyzyn6541d0a2019-01-10 14:30:51 -0800111 if sparse_image:
112 os.remove(unsparse_image_path)
Tao Baof3fc62c2018-10-25 12:23:12 -0700113 fs_dict = {}
Mark Salyzyn780f5952018-10-19 13:44:36 -0700114 for line in output.splitlines():
115 fields = line.split(":")
116 if len(fields) == 2:
117 fs_dict[fields[0].strip()] = fields[1].strip()
118 return fs_dict
Yifan Hongbbcba1e2018-06-18 16:32:35 -0700119
120
Geremy Condra6e8f53c2013-12-05 17:09:18 -0800121def UnsparseImage(sparse_image_path, replace=True):
Geremy Condrafd6f7512013-06-16 17:26:08 -0700122 img_dir = os.path.dirname(sparse_image_path)
123 unsparse_image_path = "unsparse_" + os.path.basename(sparse_image_path)
124 unsparse_image_path = os.path.join(img_dir, unsparse_image_path)
125 if os.path.exists(unsparse_image_path):
Geremy Condra6e8f53c2013-12-05 17:09:18 -0800126 if replace:
127 os.unlink(unsparse_image_path)
128 else:
Tao Baoc6bd70a2018-09-27 16:58:00 -0700129 return unsparse_image_path
Geremy Condrafd6f7512013-06-16 17:26:08 -0700130 inflate_command = ["simg2img", sparse_image_path, unsparse_image_path]
Tao Bao986ee862018-10-04 15:46:16 -0700131 try:
132 common.RunAndCheckOutput(inflate_command)
133 except:
Geremy Condrafd6f7512013-06-16 17:26:08 -0700134 os.remove(unsparse_image_path)
Tao Bao986ee862018-10-04 15:46:16 -0700135 raise
Tao Baoc6bd70a2018-09-27 16:58:00 -0700136 return unsparse_image_path
Geremy Condrafd6f7512013-06-16 17:26:08 -0700137
Tao Baoc72727a2017-12-07 10:33:00 -0800138
Mohamad Ayyashf8765552016-03-02 21:07:23 -0800139def ConvertBlockMapToBaseFs(block_map_file):
Tao Bao1c830bf2017-12-25 10:43:47 -0800140 base_fs_file = common.MakeTempFile(prefix="script_gen_", suffix=".base_fs")
Mohamad Ayyashf8765552016-03-02 21:07:23 -0800141 convert_command = ["blk_alloc_to_base_fs", block_map_file, base_fs_file]
Tao Bao986ee862018-10-04 15:46:16 -0700142 common.RunAndCheckOutput(convert_command)
Tao Baoc6bd70a2018-09-27 16:58:00 -0700143 return base_fs_file
Mohamad Ayyashf8765552016-03-02 21:07:23 -0800144
Tao Baod4349f22017-12-07 23:01:25 -0800145
Tao Baoc2606eb2018-07-20 14:44:46 -0700146def SetUpInDirAndFsConfig(origin_in, prop_dict):
147 """Returns the in_dir and fs_config that should be used for image building.
148
Tom Cherryd14b8952018-08-09 14:26:00 -0700149 When building system.img for all targets, it creates and returns a staged dir
150 that combines the contents of /system (i.e. in the given in_dir) and root.
Tao Baoc2606eb2018-07-20 14:44:46 -0700151
152 Args:
153 origin_in: Path to the input directory.
154 prop_dict: A property dict that contains info like partition size. Values
155 may be updated.
156
157 Returns:
158 A tuple of in_dir and fs_config that should be used to build the image.
159 """
160 fs_config = prop_dict.get("fs_config")
Tom Cherryd14b8952018-08-09 14:26:00 -0700161
162 if prop_dict["mount_point"] == "system_other":
163 prop_dict["mount_point"] = "system"
164 return origin_in, fs_config
165
166 if prop_dict["mount_point"] != "system":
Tao Baoc2606eb2018-07-20 14:44:46 -0700167 return origin_in, fs_config
168
Mark Salyzyn780f5952018-10-19 13:44:36 -0700169 if "first_pass" in prop_dict:
170 prop_dict["mount_point"] = "/"
171 return prop_dict["first_pass"]
172
Tao Baoc2606eb2018-07-20 14:44:46 -0700173 # Construct a staging directory of the root file system.
174 in_dir = common.MakeTempDir()
175 root_dir = prop_dict.get("root_dir")
176 if root_dir:
177 shutil.rmtree(in_dir)
178 shutil.copytree(root_dir, in_dir, symlinks=True)
179 in_dir_system = os.path.join(in_dir, "system")
180 shutil.rmtree(in_dir_system, ignore_errors=True)
181 shutil.copytree(origin_in, in_dir_system, symlinks=True)
182
183 # Change the mount point to "/".
184 prop_dict["mount_point"] = "/"
185 if fs_config:
186 # We need to merge the fs_config files of system and root.
187 merged_fs_config = common.MakeTempFile(
188 prefix="merged_fs_config", suffix=".txt")
189 with open(merged_fs_config, "w") as fw:
190 if "root_fs_config" in prop_dict:
191 with open(prop_dict["root_fs_config"]) as fr:
192 fw.writelines(fr.readlines())
193 with open(fs_config) as fr:
194 fw.writelines(fr.readlines())
195 fs_config = merged_fs_config
Mark Salyzyn780f5952018-10-19 13:44:36 -0700196 prop_dict["first_pass"] = (in_dir, fs_config)
Tao Baoc2606eb2018-07-20 14:44:46 -0700197 return in_dir, fs_config
198
199
Tao Baod4349f22017-12-07 23:01:25 -0800200def CheckHeadroom(ext4fs_output, prop_dict):
201 """Checks if there's enough headroom space available.
202
203 Headroom is the reserved space on system image (via PRODUCT_SYSTEM_HEADROOM),
204 which is useful for devices with low disk space that have system image
205 variation between builds. The 'partition_headroom' in prop_dict is the size
206 in bytes, while the numbers in 'ext4fs_output' are for 4K-blocks.
207
208 Args:
209 ext4fs_output: The output string from mke2fs command.
210 prop_dict: The property dict.
211
Tao Baod8a953d2018-01-02 21:19:27 -0800212 Raises:
213 AssertionError: On invalid input.
Tao Baoc6bd70a2018-09-27 16:58:00 -0700214 BuildImageError: On check failure.
Tao Baod4349f22017-12-07 23:01:25 -0800215 """
Tao Baod8a953d2018-01-02 21:19:27 -0800216 assert ext4fs_output is not None
217 assert prop_dict.get('fs_type', '').startswith('ext4')
218 assert 'partition_headroom' in prop_dict
219 assert 'mount_point' in prop_dict
220
Tao Baod4349f22017-12-07 23:01:25 -0800221 ext4fs_stats = re.compile(
222 r'Created filesystem with .* (?P<used_blocks>[0-9]+)/'
223 r'(?P<total_blocks>[0-9]+) blocks')
Tao Baoc72727a2017-12-07 10:33:00 -0800224 last_line = ext4fs_output.strip().split('\n')[-1]
225 m = ext4fs_stats.match(last_line)
Tao Baod4349f22017-12-07 23:01:25 -0800226 used_blocks = int(m.groupdict().get('used_blocks'))
227 total_blocks = int(m.groupdict().get('total_blocks'))
Mark Salyzyn780f5952018-10-19 13:44:36 -0700228 headroom_blocks = int(prop_dict['partition_headroom']) // BLOCK_SIZE
Tao Baod4349f22017-12-07 23:01:25 -0800229 adjusted_blocks = total_blocks - headroom_blocks
230 if used_blocks > adjusted_blocks:
Tao Baod8a953d2018-01-02 21:19:27 -0800231 mount_point = prop_dict["mount_point"]
Tao Baoc6bd70a2018-09-27 16:58:00 -0700232 raise BuildImageError(
233 "Error: Not enough room on {} (total: {} blocks, used: {} blocks, "
234 "headroom: {} blocks, available: {} blocks)".format(
235 mount_point, total_blocks, used_blocks, headroom_blocks,
236 adjusted_blocks))
Tao Baod4349f22017-12-07 23:01:25 -0800237
Huang Jianan65527272021-09-08 18:28:32 +0800238def CalculateSizeAndReserved(prop_dict, size):
239 fs_type = prop_dict.get("fs_type", "")
240 partition_headroom = int(prop_dict.get("partition_headroom", 0))
241 # If not specified, give us 16MB margin for GetDiskUsage error ...
242 reserved_size = int(prop_dict.get("partition_reserved_size", BYTES_IN_MB * 16))
243
244 if fs_type == "erofs":
245 reserved_size = int(prop_dict.get("partition_reserved_size", 0))
246 if reserved_size == 0:
247 # give .3% margin or a minimum size for AVB footer
248 return max(size * 1003 // 1000, 256 * 1024)
249
250 if fs_type.startswith("ext4") and partition_headroom > reserved_size:
251 reserved_size = partition_headroom
252
253 return size + reserved_size
Tao Baod4349f22017-12-07 23:01:25 -0800254
Mark Salyzyn3cd24602018-11-07 07:40:31 -0800255def BuildImageMkfs(in_dir, prop_dict, out_file, target_out, fs_config):
256 """Builds a pure image for the files under in_dir and writes it to out_file.
Tao Baoc2606eb2018-07-20 14:44:46 -0700257
Ying Wangbd93d422011-10-28 17:02:30 -0700258 Args:
Tao Baoc2606eb2018-07-20 14:44:46 -0700259 in_dir: Path to input directory.
260 prop_dict: A property dict that contains info like partition size. Values
261 will be updated with computed values.
262 out_file: The output image file.
263 target_out: Path to the TARGET_OUT directory as in Makefile. It actually
264 points to the /system directory under PRODUCT_OUT. fs_config (the one
265 under system/core/libcutils) reads device specific FS config files from
266 there.
Mark Salyzyn3cd24602018-11-07 07:40:31 -0800267 fs_config: The fs_config file that drives the prototype
Ying Wangbd93d422011-10-28 17:02:30 -0700268
Tao Baoc6bd70a2018-09-27 16:58:00 -0700269 Raises:
270 BuildImageError: On build image failures.
Ying Wangbd93d422011-10-28 17:02:30 -0700271 """
272 build_command = []
273 fs_type = prop_dict.get("fs_type", "")
Tao Baoc72727a2017-12-07 10:33:00 -0800274 run_e2fsck = False
Daniel Rosenberg6cc2c812019-12-17 17:36:31 -0800275 needs_projid = prop_dict.get("needs_projid", 0)
276 needs_casefold = prop_dict.get("needs_casefold", 0)
Jaegeuk Kimed754fb2020-10-12 19:50:05 -0700277 needs_compress = prop_dict.get("needs_compress", 0)
Geremy Condrafd6f7512013-06-16 17:26:08 -0700278
David Anderson9e95a022021-08-31 21:32:45 -0700279 disable_sparse = "disable_sparse" in prop_dict
280
Ying Wangbd93d422011-10-28 17:02:30 -0700281 if fs_type.startswith("ext"):
Adrien Schildknecht9a072cc2016-11-18 17:06:29 -0800282 build_command = [prop_dict["ext_mkuserimg"]]
David Anderson9e95a022021-08-31 21:32:45 -0700283 if "extfs_sparse_flag" in prop_dict and not disable_sparse:
Ying Wangbd93d422011-10-28 17:02:30 -0700284 build_command.append(prop_dict["extfs_sparse_flag"])
Tao Baoc72727a2017-12-07 10:33:00 -0800285 run_e2fsck = True
Ying Wangbd93d422011-10-28 17:02:30 -0700286 build_command.extend([in_dir, out_file, fs_type,
287 prop_dict["mount_point"]])
Tao Bao35f4ebc2018-09-27 15:31:11 -0700288 build_command.append(prop_dict["image_size"])
Ying Wangf3b86352014-11-18 18:03:13 -0800289 if "journal_size" in prop_dict:
290 build_command.extend(["-j", prop_dict["journal_size"]])
Doug Zongker850b8072013-12-05 15:54:55 -0800291 if "timestamp" in prop_dict:
292 build_command.extend(["-T", str(prop_dict["timestamp"])])
Ying Wanga2292c92015-03-24 19:07:40 -0700293 if fs_config:
Doug Zongker82822822014-06-16 09:10:55 -0700294 build_command.extend(["-C", fs_config])
Thierry Strudel74a81e62015-07-09 09:54:55 -0700295 if target_out:
296 build_command.extend(["-D", target_out])
Ying Wanga2292c92015-03-24 19:07:40 -0700297 if "block_list" in prop_dict:
298 build_command.extend(["-B", prop_dict["block_list"]])
Mohamad Ayyashf8765552016-03-02 21:07:23 -0800299 if "base_fs_file" in prop_dict:
300 base_fs_file = ConvertBlockMapToBaseFs(prop_dict["base_fs_file"])
Mohamad Ayyashf8765552016-03-02 21:07:23 -0800301 build_command.extend(["-d", base_fs_file])
Christoffer Dall8ed01f32014-12-17 21:34:12 +0100302 build_command.extend(["-L", prop_dict["mount_point"]])
Patrick Tjina1900842016-10-20 10:58:12 -0700303 if "extfs_inode_count" in prop_dict:
304 build_command.extend(["-i", prop_dict["extfs_inode_count"]])
Patrick Tjin3f5f9932018-03-23 11:36:43 -0700305 if "extfs_rsv_pct" in prop_dict:
306 build_command.extend(["-M", prop_dict["extfs_rsv_pct"]])
Connor O'Brien20f08c32017-01-05 16:48:14 -0800307 if "flash_erase_block_size" in prop_dict:
308 build_command.extend(["-e", prop_dict["flash_erase_block_size"]])
309 if "flash_logical_block_size" in prop_dict:
310 build_command.extend(["-o", prop_dict["flash_logical_block_size"]])
Tao Baod86e3112017-09-22 15:45:33 -0700311 # Specify UUID and hash_seed if using mke2fs.
HÃ¥kan Kvist2e1f5272021-05-11 11:14:48 +0200312 if os.path.basename(prop_dict["ext_mkuserimg"]) == "mkuserimg_mke2fs":
Tao Baod86e3112017-09-22 15:45:33 -0700313 if "uuid" in prop_dict:
314 build_command.extend(["-U", prop_dict["uuid"]])
315 if "hash_seed" in prop_dict:
316 build_command.extend(["-S", prop_dict["hash_seed"]])
Tamas Petzc0a8c632020-02-03 15:41:02 +0100317 if prop_dict.get("ext4_share_dup_blocks") == "true":
Jin Qianfde9f792018-01-22 13:15:46 -0800318 build_command.append("-c")
Daniel Rosenberg6cc2c812019-12-17 17:36:31 -0800319 if (needs_projid):
320 build_command.extend(["--inode_size", "512"])
321 else:
322 build_command.extend(["--inode_size", "256"])
Ying Wanga2292c92015-03-24 19:07:40 -0700323 if "selinux_fc" in prop_dict:
Kenny Rootf32dc712012-04-08 10:42:34 -0700324 build_command.append(prop_dict["selinux_fc"])
Gao Xiang961041a2020-06-17 13:59:16 +0800325 elif fs_type.startswith("erofs"):
326 build_command = ["mkerofsimage.sh"]
327 build_command.extend([in_dir, out_file])
David Anderson9e95a022021-08-31 21:32:45 -0700328 if "erofs_sparse_flag" in prop_dict and not disable_sparse:
Gao Xiang961041a2020-06-17 13:59:16 +0800329 build_command.extend([prop_dict["erofs_sparse_flag"]])
330 build_command.extend(["-m", prop_dict["mount_point"]])
331 if target_out:
332 build_command.extend(["-d", target_out])
333 if fs_config:
334 build_command.extend(["-C", fs_config])
335 if "selinux_fc" in prop_dict:
336 build_command.extend(["-c", prop_dict["selinux_fc"]])
David Anderson40a821f2021-09-22 18:02:01 -0700337 compressor = None
338 if "erofs_default_compressor" in prop_dict:
339 compressor = prop_dict["erofs_default_compressor"]
340 if "erofs_compressor" in prop_dict:
341 compressor = prop_dict["erofs_compressor"]
342 if compressor:
343 build_command.extend(["-z", compressor])
David Andersond29e5372021-10-08 18:33:43 -0700344 if "timestamp" in prop_dict:
345 build_command.extend(["-T", str(prop_dict["timestamp"])])
346 if "uuid" in prop_dict:
347 build_command.extend(["-U", prop_dict["uuid"]])
348 if "block_list" in prop_dict:
349 build_command.extend(["-B", prop_dict["block_list"]])
David Anderson64b351b2021-10-13 00:20:43 -0700350 if "erofs_pcluster_size" in prop_dict:
351 build_command.extend(["-P", prop_dict["erofs_pcluster_size"]])
352 if "erofs_share_dup_blocks" in prop_dict:
353 build_command.extend(["-k", "4096"])
Mohamad Ayyashb97746e2015-03-03 12:30:37 -0800354 elif fs_type.startswith("squash"):
355 build_command = ["mksquashfsimage.sh"]
356 build_command.extend([in_dir, out_file])
David Anderson9e95a022021-08-31 21:32:45 -0700357 if "squashfs_sparse_flag" in prop_dict and not disable_sparse:
Todd Poynorb2a555e2015-12-15 18:00:14 -0800358 build_command.extend([prop_dict["squashfs_sparse_flag"]])
Mohamad Ayyashb97746e2015-03-03 12:30:37 -0800359 build_command.extend(["-m", prop_dict["mount_point"]])
Thierry Strudel74a81e62015-07-09 09:54:55 -0700360 if target_out:
361 build_command.extend(["-d", target_out])
Mohamad Ayyash88378822016-04-07 22:10:51 -0700362 if fs_config:
363 build_command.extend(["-C", fs_config])
Ying Wanga2292c92015-03-24 19:07:40 -0700364 if "selinux_fc" in prop_dict:
Mohamad Ayyashb97746e2015-03-03 12:30:37 -0800365 build_command.extend(["-c", prop_dict["selinux_fc"]])
Mohamad Ayyashc3484f72016-06-13 09:46:58 -0700366 if "block_list" in prop_dict:
367 build_command.extend(["-B", prop_dict["block_list"]])
Ng Zhi An9446c1d2018-01-19 15:51:46 -0800368 if "squashfs_block_size" in prop_dict:
369 build_command.extend(["-b", prop_dict["squashfs_block_size"]])
Simon Wilsonf86e7ee2015-06-17 12:35:15 -0700370 if "squashfs_compressor" in prop_dict:
371 build_command.extend(["-z", prop_dict["squashfs_compressor"]])
372 if "squashfs_compressor_opt" in prop_dict:
373 build_command.extend(["-zo", prop_dict["squashfs_compressor_opt"]])
Tao Baoc72727a2017-12-07 10:33:00 -0800374 if prop_dict.get("squashfs_disable_4k_align") == "true":
Mohamad Ayyash1b6d3482016-06-15 15:53:07 -0700375 build_command.extend(["-a"])
JP Abgrall5bfed5a2014-06-16 14:17:40 -0700376 elif fs_type.startswith("f2fs"):
377 build_command = ["mkf2fsuserimg.sh"]
Tao Bao35f4ebc2018-09-27 15:31:11 -0700378 build_command.extend([out_file, prop_dict["image_size"]])
David Anderson9e95a022021-08-31 21:32:45 -0700379 if "f2fs_sparse_flag" in prop_dict and not disable_sparse:
Alistair Delva91238cc2019-10-16 10:53:41 -0700380 build_command.extend([prop_dict["f2fs_sparse_flag"]])
Jaegeuk Kim2ea1eba2017-11-28 19:21:28 -0800381 if fs_config:
382 build_command.extend(["-C", fs_config])
383 build_command.extend(["-f", in_dir])
384 if target_out:
385 build_command.extend(["-D", target_out])
386 if "selinux_fc" in prop_dict:
387 build_command.extend(["-s", prop_dict["selinux_fc"]])
388 build_command.extend(["-t", prop_dict["mount_point"]])
389 if "timestamp" in prop_dict:
390 build_command.extend(["-T", str(prop_dict["timestamp"])])
Jaegeuk Kim3dc47282021-06-13 08:54:01 -0700391 if "block_list" in prop_dict:
392 build_command.extend(["-B", prop_dict["block_list"]])
Jaegeuk Kim2ea1eba2017-11-28 19:21:28 -0800393 build_command.extend(["-L", prop_dict["mount_point"]])
Daniel Rosenberg6cc2c812019-12-17 17:36:31 -0800394 if (needs_projid):
395 build_command.append("--prjquota")
396 if (needs_casefold):
397 build_command.append("--casefold")
Jaegeuk Kim13696542021-05-22 09:47:48 -0700398 if (needs_compress or prop_dict.get("f2fs_compress") == "true"):
Jaegeuk Kimed754fb2020-10-12 19:50:05 -0700399 build_command.append("--compression")
Jaegeuk Kim3dc47282021-06-13 08:54:01 -0700400 if (prop_dict.get("mount_point") != "data"):
Jaegeuk Kim46e0ea22021-05-20 23:13:59 -0700401 build_command.append("--readonly")
Jaegeuk Kim3dc47282021-06-13 08:54:01 -0700402 if (prop_dict.get("f2fs_compress") == "true"):
Robin Hsu3e51f422020-11-04 09:29:09 +0800403 build_command.append("--sldc")
Jaegeuk Kim13696542021-05-22 09:47:48 -0700404 if (prop_dict.get("f2fs_sldc_flags") == None):
Robin Hsu3e51f422020-11-04 09:29:09 +0800405 build_command.append(str(0))
406 else:
Jaegeuk Kim13696542021-05-22 09:47:48 -0700407 sldc_flags_str = prop_dict.get("f2fs_sldc_flags")
Robin Hsu3e51f422020-11-04 09:29:09 +0800408 sldc_flags = sldc_flags_str.split()
409 build_command.append(str(len(sldc_flags)))
410 build_command.extend(sldc_flags)
Ying Wangbd93d422011-10-28 17:02:30 -0700411 else:
Tao Baoc6bd70a2018-09-27 16:58:00 -0700412 raise BuildImageError(
413 "Error: unknown filesystem type: {}".format(fs_type))
Ying Wangbd93d422011-10-28 17:02:30 -0700414
Tao Bao986ee862018-10-04 15:46:16 -0700415 try:
416 mkfs_output = common.RunAndCheckOutput(build_command)
417 except:
Tao Baoc6bd70a2018-09-27 16:58:00 -0700418 try:
419 du = GetDiskUsage(in_dir)
420 du_str = "{} bytes ({} MB)".format(du, du // BYTES_IN_MB)
Tao Bao986ee862018-10-04 15:46:16 -0700421 # Suppress any errors from GetDiskUsage() to avoid hiding the real errors
422 # from common.RunAndCheckOutput().
Tao Bao32fcdab2018-10-12 10:30:39 -0700423 except Exception: # pylint: disable=broad-except
424 logger.exception("Failed to compute disk usage with du")
Tao Baoc6bd70a2018-09-27 16:58:00 -0700425 du_str = "unknown"
Tao Bao4251fe92018-07-23 13:05:00 -0700426 print(
Mark Salyzyn3cd24602018-11-07 07:40:31 -0800427 "Out of space? Out of inodes? The tree size of {} is {}, "
428 "with reserved space of {} bytes ({} MB).".format(
Tao Baoc2606eb2018-07-20 14:44:46 -0700429 in_dir, du_str,
Tao Bao4251fe92018-07-23 13:05:00 -0700430 int(prop_dict.get("partition_reserved_size", 0)),
431 int(prop_dict.get("partition_reserved_size", 0)) // BYTES_IN_MB))
Huang Jiananf63abb12021-04-29 15:24:50 +0800432 if ("image_size" in prop_dict and "partition_size" in prop_dict):
433 print(
434 "The max image size for filesystem files is {} bytes ({} MB), "
435 "out of a total partition size of {} bytes ({} MB).".format(
436 int(prop_dict["image_size"]),
437 int(prop_dict["image_size"]) // BYTES_IN_MB,
438 int(prop_dict["partition_size"]),
439 int(prop_dict["partition_size"]) // BYTES_IN_MB))
Tao Bao986ee862018-10-04 15:46:16 -0700440 raise
Ying Wang69e9b4d2012-11-26 18:10:23 -0800441
Mark Salyzyn3cd24602018-11-07 07:40:31 -0800442 if run_e2fsck and prop_dict.get("skip_fsck") != "true":
443 unsparse_image = UnsparseImage(out_file, replace=False)
444
445 # Run e2fsck on the inflated image file
446 e2fsck_command = ["e2fsck", "-f", "-n", unsparse_image]
447 try:
448 common.RunAndCheckOutput(e2fsck_command)
449 finally:
450 os.remove(unsparse_image)
451
452 return mkfs_output
453
Inseob Kimf69346e2021-10-13 15:16:33 +0900454def GenerateFSVerityMetadata(in_dir, fsverity_path, apk_key_path, apk_manifest_path, apk_out_path):
455 """Generates fsverity metadata files.
456
457 By setting PRODUCT_SYSTEM_FSVERITY_GENERATE_METADATA := true, fsverity
458 metadata files will be generated. For the input files, see `patterns` below.
459
460 One metadata file per one input file will be generated with the suffix
461 .fsv_meta. e.g. system/framework/foo.jar -> system/framework/foo.jar.fsv_meta
462 Also a mapping file containing fsverity digests will be generated to
463 system/etc/security/fsverity/BuildManifest.apk.
464
465 Args:
466 in_dir: temporary working directory (same as BuildImage)
467 fsverity_path: path to host tool fsverity
468 apk_key_path: path to key (e.g. build/make/target/product/security/platform)
469 apk_manifest_path: path to AndroidManifest.xml for APK
470 apk_out_path: path to the output APK
471
472 Returns:
473 None. The files are generated directly under in_dir.
474 """
475
476 patterns = [
477 "system/framework/*.jar",
478 "system/framework/oat/*/*.oat",
479 "system/framework/oat/*/*.vdex",
480 "system/framework/oat/*/*.art",
481 "system/etc/boot-image.prof",
482 "system/etc/dirty-image-objects",
483 ]
484 files = []
485 for pattern in patterns:
486 files += glob.glob(os.path.join(in_dir, pattern))
487 files = sorted(set(files))
488
489 generator = FSVerityMetadataGenerator(fsverity_path)
490 generator.set_hash_alg("sha256")
491
492 digests = FSVerityDigests()
493 for f in files:
494 generator.generate(f)
495 # f is a full path for now; make it relative so it starts with {mount_point}/
496 digest = digests.digests[os.path.relpath(f, in_dir)]
497 digest.digest = generator.digest(f)
498 digest.hash_alg = "sha256"
499
500 temp_dir = common.MakeTempDir()
501
502 os.mkdir(os.path.join(temp_dir, "assets"))
503 metadata_path = os.path.join(temp_dir, "assets", "build_manifest")
504 with open(metadata_path, "wb") as f:
505 f.write(digests.SerializeToString())
506
507 apk_path = os.path.join(in_dir, apk_out_path)
508
509 common.RunAndCheckOutput(["aapt2", "link",
510 "-A", os.path.join(temp_dir, "assets"),
511 "-o", apk_path,
512 "--manifest", apk_manifest_path])
513 common.RunAndCheckOutput(["apksigner", "sign", "--in", apk_path,
514 "--cert", apk_key_path + ".x509.pem",
515 "--key", apk_key_path + ".pk8"])
Mark Salyzyn3cd24602018-11-07 07:40:31 -0800516
517def BuildImage(in_dir, prop_dict, out_file, target_out=None):
518 """Builds an image for the files under in_dir and writes it to out_file.
519
520 Args:
521 in_dir: Path to input directory.
522 prop_dict: A property dict that contains info like partition size. Values
523 will be updated with computed values.
524 out_file: The output image file.
525 target_out: Path to the TARGET_OUT directory as in Makefile. It actually
526 points to the /system directory under PRODUCT_OUT. fs_config (the one
527 under system/core/libcutils) reads device specific FS config files from
528 there.
529
530 Raises:
531 BuildImageError: On build image failures.
532 """
533 in_dir, fs_config = SetUpInDirAndFsConfig(in_dir, prop_dict)
534
535 build_command = []
536 fs_type = prop_dict.get("fs_type", "")
537
538 fs_spans_partition = True
Huang Jianan62d926e2020-12-04 16:53:06 +0800539 if fs_type.startswith("squash") or fs_type.startswith("erofs"):
Mark Salyzyn3cd24602018-11-07 07:40:31 -0800540 fs_spans_partition = False
Jaegeuk Kim13696542021-05-22 09:47:48 -0700541 elif fs_type.startswith("f2fs") and prop_dict.get("f2fs_compress") == "true":
542 fs_spans_partition = False
Mark Salyzyn3cd24602018-11-07 07:40:31 -0800543
Inseob Kim9cda3972021-10-12 22:59:12 +0900544 if "fsverity_generate_metadata" in prop_dict:
Inseob Kimf69346e2021-10-13 15:16:33 +0900545 GenerateFSVerityMetadata(in_dir,
546 fsverity_path=prop_dict["fsverity"],
547 apk_key_path=prop_dict["fsverity_apk_key"],
548 apk_manifest_path=prop_dict["fsverity_apk_manifest"],
549 apk_out_path=prop_dict["fsverity_apk_out"])
Inseob Kim9cda3972021-10-12 22:59:12 +0900550
Mark Salyzyn3cd24602018-11-07 07:40:31 -0800551 # Get a builder for creating an image that's to be verified by Verified Boot,
552 # or None if not applicable.
553 verity_image_builder = verity_utils.CreateVerityImageBuilder(prop_dict)
554
David Anderson9e95a022021-08-31 21:32:45 -0700555 disable_sparse = "disable_sparse" in prop_dict
Huang Jiananffa1d572021-09-08 18:11:22 +0800556 mkfs_output = None
Mark Salyzyn3cd24602018-11-07 07:40:31 -0800557 if (prop_dict.get("use_dynamic_partition_size") == "true" and
558 "partition_size" not in prop_dict):
559 # If partition_size is not defined, use output of `du' + reserved_size.
Huang Jianan35f015e2020-12-04 16:58:24 +0800560 # For compressed file system, it's better to use the compressed size to avoid wasting space.
561 if fs_type.startswith("erofs"):
Huang Jiananffa1d572021-09-08 18:11:22 +0800562 mkfs_output = BuildImageMkfs(in_dir, prop_dict, out_file, target_out, fs_config)
563 if "erofs_sparse_flag" in prop_dict and not disable_sparse:
564 image_path = UnsparseImage(out_file, replace=False)
565 size = GetDiskUsage(image_path)
566 os.remove(image_path)
567 else:
568 size = GetDiskUsage(out_file)
Huang Jianan35f015e2020-12-04 16:58:24 +0800569 else:
570 size = GetDiskUsage(in_dir)
Mark Salyzyn3cd24602018-11-07 07:40:31 -0800571 logger.info(
572 "The tree size of %s is %d MB.", in_dir, size // BYTES_IN_MB)
Huang Jianan65527272021-09-08 18:28:32 +0800573 size = CalculateSizeAndReserved(prop_dict, size)
Mark Salyzyn3cd24602018-11-07 07:40:31 -0800574 # Round this up to a multiple of 4K so that avbtool works
575 size = common.RoundUpTo4K(size)
576 if fs_type.startswith("ext"):
577 prop_dict["partition_size"] = str(size)
578 prop_dict["image_size"] = str(size)
579 if "extfs_inode_count" not in prop_dict:
580 prop_dict["extfs_inode_count"] = str(GetInodeUsage(in_dir))
581 logger.info(
582 "First Pass based on estimates of %d MB and %s inodes.",
583 size // BYTES_IN_MB, prop_dict["extfs_inode_count"])
584 BuildImageMkfs(in_dir, prop_dict, out_file, target_out, fs_config)
Mark Salyzyn6541d0a2019-01-10 14:30:51 -0800585 sparse_image = False
David Anderson9e95a022021-08-31 21:32:45 -0700586 if "extfs_sparse_flag" in prop_dict and not disable_sparse:
Mark Salyzyn6541d0a2019-01-10 14:30:51 -0800587 sparse_image = True
Jaegeuk Kim13696542021-05-22 09:47:48 -0700588 fs_dict = GetFilesystemCharacteristics(fs_type, out_file, sparse_image)
Mark Salyzyn3cd24602018-11-07 07:40:31 -0800589 os.remove(out_file)
590 block_size = int(fs_dict.get("Block size", "4096"))
591 free_size = int(fs_dict.get("Free blocks", "0")) * block_size
592 reserved_size = int(prop_dict.get("partition_reserved_size", 0))
593 partition_headroom = int(fs_dict.get("partition_headroom", 0))
594 if fs_type.startswith("ext4") and partition_headroom > reserved_size:
595 reserved_size = partition_headroom
596 if free_size <= reserved_size:
597 logger.info(
598 "Not worth reducing image %d <= %d.", free_size, reserved_size)
599 else:
600 size -= free_size
601 size += reserved_size
Mark Salyzyn60a716f2019-01-10 08:36:34 -0800602 if reserved_size == 0:
Mark Salyzync25b2bf2019-01-16 08:03:10 -0800603 # add .3% margin
604 size = size * 1003 // 1000
Mark Salyzyn60a716f2019-01-10 08:36:34 -0800605 # Use a minimum size, otherwise we will fail to calculate an AVB footer
606 # or fail to construct an ext4 image.
607 size = max(size, 256 * 1024)
Mark Salyzyn3cd24602018-11-07 07:40:31 -0800608 if block_size <= 4096:
609 size = common.RoundUpTo4K(size)
610 else:
611 size = ((size + block_size - 1) // block_size) * block_size
612 extfs_inode_count = prop_dict["extfs_inode_count"]
613 inodes = int(fs_dict.get("Inode count", extfs_inode_count))
614 inodes -= int(fs_dict.get("Free inodes", "0"))
Mark Salyzync25b2bf2019-01-16 08:03:10 -0800615 # add .2% margin or 1 inode, whichever is greater
616 spare_inodes = inodes * 2 // 1000
617 min_spare_inodes = 1
618 if spare_inodes < min_spare_inodes:
619 spare_inodes = min_spare_inodes
620 inodes += spare_inodes
Mark Salyzyn3cd24602018-11-07 07:40:31 -0800621 prop_dict["extfs_inode_count"] = str(inodes)
622 prop_dict["partition_size"] = str(size)
623 logger.info(
624 "Allocating %d Inodes for %s.", inodes, out_file)
Jaegeuk Kim13696542021-05-22 09:47:48 -0700625 elif fs_type.startswith("f2fs") and prop_dict.get("f2fs_compress") == "true":
626 prop_dict["partition_size"] = str(size)
627 prop_dict["image_size"] = str(size)
628 BuildImageMkfs(in_dir, prop_dict, out_file, target_out, fs_config)
629 sparse_image = False
David Anderson9e95a022021-08-31 21:32:45 -0700630 if "f2fs_sparse_flag" in prop_dict and not disable_sparse:
Jaegeuk Kim13696542021-05-22 09:47:48 -0700631 sparse_image = True
632 fs_dict = GetFilesystemCharacteristics(fs_type, out_file, sparse_image)
633 os.remove(out_file)
634 block_count = int(fs_dict.get("block_count", "0"))
635 log_blocksize = int(fs_dict.get("log_blocksize", "12"))
636 size = block_count << log_blocksize
637 prop_dict["partition_size"] = str(size)
Mark Salyzyn3cd24602018-11-07 07:40:31 -0800638 if verity_image_builder:
639 size = verity_image_builder.CalculateDynamicPartitionSize(size)
640 prop_dict["partition_size"] = str(size)
641 logger.info(
642 "Allocating %d MB for %s.", size // BYTES_IN_MB, out_file)
643
644 prop_dict["image_size"] = prop_dict["partition_size"]
645
646 # Adjust the image size to make room for the hashes if this is to be verified.
647 if verity_image_builder:
648 max_image_size = verity_image_builder.CalculateMaxImageSize()
649 prop_dict["image_size"] = str(max_image_size)
650
Huang Jiananffa1d572021-09-08 18:11:22 +0800651 if not mkfs_output:
652 mkfs_output = BuildImageMkfs(in_dir, prop_dict, out_file, target_out, fs_config)
Mark Salyzyn3cd24602018-11-07 07:40:31 -0800653
Tao Baod4349f22017-12-07 23:01:25 -0800654 # Check if there's enough headroom space available for ext4 image.
Tao Bao79d52f82017-12-07 14:07:44 -0800655 if "partition_headroom" in prop_dict and fs_type.startswith("ext4"):
Tao Baoc6bd70a2018-09-27 16:58:00 -0700656 CheckHeadroom(mkfs_output, prop_dict)
Tao Baoc7a6f1e2015-06-23 11:16:05 -0700657
Tao Bao7549e5e2018-10-03 14:23:59 -0700658 if not fs_spans_partition and verity_image_builder:
659 verity_image_builder.PadSparseImage(out_file)
Mohamad Ayyashdd063522015-03-24 12:42:03 -0700660
Tao Baoc72727a2017-12-07 10:33:00 -0800661 # Create the verified image if this is to be verified.
Tao Bao7549e5e2018-10-03 14:23:59 -0700662 if verity_image_builder:
663 verity_image_builder.Build(out_file)
David Zeuthen4014a9d2016-09-30 17:29:22 -0400664
Ying Wangbd93d422011-10-28 17:02:30 -0700665def ImagePropFromGlobalDict(glob_dict, mount_point):
666 """Build an image property dictionary from the global dictionary.
667
668 Args:
669 glob_dict: the global dictionary from the build system.
670 mount_point: such as "system", "data" etc.
671 """
Doug Zongker1ad7ade2013-12-06 11:53:27 -0800672 d = {}
Tao Bao052ae352015-09-28 13:44:13 -0700673
Tao Bao822f5842015-09-30 16:01:14 -0700674 if "build.prop" in glob_dict:
Tianjie Xu0fde41e2020-05-09 05:24:18 +0000675 timestamp = glob_dict["build.prop"].GetProp("ro.build.date.utc")
676 if timestamp:
677 d["timestamp"] = timestamp
Ying Wang9f8e8db2011-11-04 11:37:01 -0700678
679 def copy_prop(src_p, dest_p):
Patrick Tjin3f5f9932018-03-23 11:36:43 -0700680 """Copy a property from the global dictionary.
681
682 Args:
683 src_p: The source property in the global dictionary.
684 dest_p: The destination property.
685 Returns:
686 True if property was found and copied, False otherwise.
687 """
Ying Wang9f8e8db2011-11-04 11:37:01 -0700688 if src_p in glob_dict:
689 d[dest_p] = str(glob_dict[src_p])
Patrick Tjin3f5f9932018-03-23 11:36:43 -0700690 return True
691 return False
Ying Wang9f8e8db2011-11-04 11:37:01 -0700692
Ying Wangbd93d422011-10-28 17:02:30 -0700693 common_props = (
Ying Wangbd93d422011-10-28 17:02:30 -0700694 "extfs_sparse_flag",
David Anderson40a821f2021-09-22 18:02:01 -0700695 "erofs_default_compressor",
David Anderson64b351b2021-10-13 00:20:43 -0700696 "erofs_pcluster_size",
697 "erofs_share_dup_blocks",
Gao Xiang961041a2020-06-17 13:59:16 +0800698 "erofs_sparse_flag",
Todd Poynorb2a555e2015-12-15 18:00:14 -0800699 "squashfs_sparse_flag",
Jaegeuk Kim13696542021-05-22 09:47:48 -0700700 "system_f2fs_compress",
Robin Hsu3e51f422020-11-04 09:29:09 +0800701 "system_f2fs_sldc_flags",
Alistair Delva91238cc2019-10-16 10:53:41 -0700702 "f2fs_sparse_flag",
Ying Wang6a42a252013-02-27 13:54:02 -0800703 "skip_fsck",
Adrien Schildknecht9a072cc2016-11-18 17:06:29 -0800704 "ext_mkuserimg",
Geremy Condrafd6f7512013-06-16 17:26:08 -0700705 "verity",
Geremy Condrafd6f7512013-06-16 17:26:08 -0700706 "verity_key",
Sami Tolvanenf99b5312015-05-20 07:30:57 +0100707 "verity_signer_cmd",
David Zeuthen4014a9d2016-09-30 17:29:22 -0400708 "verity_fec",
Bowgo Tsai6ceeb1a2017-10-11 16:21:48 +0800709 "verity_disable",
Bowgo Tsai3e599ea2017-05-26 18:30:04 +0800710 "avb_enable",
Tao Bao2b6dfd62017-09-27 17:17:43 -0700711 "avb_avbtool",
Yifan Hong2dae5722018-07-31 12:47:27 -0700712 "use_dynamic_partition_size",
Tao Bao2b6dfd62017-09-27 17:17:43 -0700713 )
Ying Wangbd93d422011-10-28 17:02:30 -0700714 for p in common_props:
Ying Wang9f8e8db2011-11-04 11:37:01 -0700715 copy_prop(p, p)
Ying Wangbd93d422011-10-28 17:02:30 -0700716
David Anderson271dab62021-10-11 17:31:26 -0700717 ro_mount_points = set([
718 "odm",
719 "odm_dlkm",
720 "oem",
721 "product",
722 "system",
723 "system_ext",
724 "system_other",
725 "vendor",
726 "vendor_dlkm",
727 ])
David Andersonaac502f2021-09-23 15:48:29 -0700728
David Anderson271dab62021-10-11 17:31:26 -0700729 # Tuple layout: (readonly, specific prop, general prop)
730 fmt_props = (
731 # Generic first, then specific file type.
732 (False, "fs_type", "fs_type"),
733 (False, "{}_fs_type", "fs_type"),
734
735 # Ordering for these doesn't matter.
736 (False, "{}_selinux_fc", "selinux_fc"),
737 (False, "{}_size", "partition_size"),
738 (True, "avb_{}_add_hashtree_footer_args", "avb_add_hashtree_footer_args"),
739 (True, "avb_{}_algorithm", "avb_algorithm"),
740 (True, "avb_{}_hashtree_enable", "avb_hashtree_enable"),
741 (True, "avb_{}_key_path", "avb_key_path"),
742 (True, "avb_{}_salt", "avb_salt"),
743 (True, "ext4_share_dup_blocks", "ext4_share_dup_blocks"),
744 (True, "{}_base_fs_file", "base_fs_file"),
745 (True, "{}_disable_sparse", "disable_sparse"),
746 (True, "{}_erofs_compressor", "erofs_compressor"),
David Anderson64b351b2021-10-13 00:20:43 -0700747 (True, "{}_erofs_pcluster_size", "erofs_pcluster_size"),
748 (True, "{}_erofs_share_dup_blocks", "erofs_share_dup_blocks"),
David Anderson271dab62021-10-11 17:31:26 -0700749 (True, "{}_extfs_inode_count", "extfs_inode_count"),
750 (True, "{}_f2fs_compress", "f2fs_compress"),
751 (True, "{}_f2fs_sldc_flags", "f2fs_sldc_flags"),
752 (True, "{}_reserved_size", "partition_reserved_size"),
753 (True, "{}_squashfs_block_size", "squashfs_block_size"),
754 (True, "{}_squashfs_compressor", "squashfs_compressor"),
755 (True, "{}_squashfs_compressor_opt", "squashfs_compressor_opt"),
756 (True, "{}_squashfs_disable_4k_align", "squashfs_disable_4k_align"),
757 (True, "{}_verity_block_device", "verity_block_device"),
758 )
759
760 # Translate prefixed properties into generic ones.
761 if mount_point == "data":
762 prefix = "userdata"
763 else:
764 prefix = mount_point
765
766 for readonly, src_prop, dest_prop in fmt_props:
767 if readonly and mount_point not in ro_mount_points:
768 continue
769
770 if src_prop == "fs_type":
771 # This property is legacy and only used on a few partitions. b/202600377
772 allowed_partitions = set(["system", "system_other", "data", "oem"])
773 if mount_point not in allowed_partitions:
774 continue
775
776 if mount_point == "system_other":
777 # Propagate system properties to system_other. They'll get overridden
778 # after as needed.
779 copy_prop(src_prop.format("system"), dest_prop)
780
781 copy_prop(src_prop.format(prefix), dest_prop)
782
783 # Set prefixed properties that need a default value.
784 if mount_point in ro_mount_points:
785 prop = "{}_journal_size".format(prefix)
786 if not copy_prop(prop, "journal_size"):
787 d["journal_size"] = "0"
788
789 prop = "{}_extfs_rsv_pct".format(prefix)
790 if not copy_prop(prop, "extfs_rsv_pct"):
791 d["extfs_rsv_pct"] = "0"
792
793 # Copy partition-specific properties.
Ying Wangbd93d422011-10-28 17:02:30 -0700794 d["mount_point"] = mount_point
795 if mount_point == "system":
Julius D'souza001c6762017-05-03 13:43:27 -0700796 copy_prop("system_headroom", "partition_headroom")
Tao Baof3282b42015-04-01 11:21:55 -0700797 copy_prop("system_root_image", "system_root_image")
Tao Bao8bfd3c72018-07-20 15:20:28 -0700798 copy_prop("root_dir", "root_dir")
799 copy_prop("root_fs_config", "root_fs_config")
Inseob Kim9cda3972021-10-12 22:59:12 +0900800 copy_prop("fsverity", "fsverity")
801 copy_prop("fsverity_generate_metadata", "fsverity_generate_metadata")
Inseob Kimf69346e2021-10-13 15:16:33 +0900802 copy_prop("fsverity_apk_key","fsverity_apk_key")
803 copy_prop("fsverity_apk_manifest","fsverity_apk_manifest")
804 copy_prop("fsverity_apk_out","fsverity_apk_out")
Ying Wangbd93d422011-10-28 17:02:30 -0700805 elif mount_point == "data":
JP Abgrall5bfed5a2014-06-16 14:17:40 -0700806 # Copy the generic fs type first, override with specific one if available.
Tao Baoc72727a2017-12-07 10:33:00 -0800807 copy_prop("flash_logical_block_size", "flash_logical_block_size")
Connor O'Brien20f08c32017-01-05 16:48:14 -0800808 copy_prop("flash_erase_block_size", "flash_erase_block_size")
Daniel Rosenberg6cc2c812019-12-17 17:36:31 -0800809 copy_prop("needs_casefold", "needs_casefold")
810 copy_prop("needs_projid", "needs_projid")
Jaegeuk Kimed754fb2020-10-12 19:50:05 -0700811 copy_prop("needs_compress", "needs_compress")
David Zeuthen4014a9d2016-09-30 17:29:22 -0400812 d["partition_name"] = mount_point
Ying Wangbd93d422011-10-28 17:02:30 -0700813 return d
814
815
816def LoadGlobalDict(filename):
817 """Load "name=value" pairs from filename"""
818 d = {}
819 f = open(filename)
820 for line in f:
821 line = line.strip()
822 if not line or line.startswith("#"):
823 continue
824 k, v = line.split("=", 1)
825 d[k] = v
826 f.close()
827 return d
828
829
Yifan Hongbbcba1e2018-06-18 16:32:35 -0700830def GlobalDictFromImageProp(image_prop, mount_point):
831 d = {}
832 def copy_prop(src_p, dest_p):
833 if src_p in image_prop:
834 d[dest_p] = image_prop[src_p]
835 return True
836 return False
Tao Bao4251fe92018-07-23 13:05:00 -0700837
Yifan Hongbbcba1e2018-06-18 16:32:35 -0700838 if mount_point == "system":
Tao Bao35f4ebc2018-09-27 15:31:11 -0700839 copy_prop("partition_size", "system_size")
Yifan Hongbbcba1e2018-06-18 16:32:35 -0700840 elif mount_point == "system_other":
Bowgo Tsai867ab662019-01-29 13:30:18 +0800841 copy_prop("partition_size", "system_other_size")
Yifan Hong749062d2018-06-19 16:23:16 -0700842 elif mount_point == "vendor":
Tao Bao35f4ebc2018-09-27 15:31:11 -0700843 copy_prop("partition_size", "vendor_size")
Bowgo Tsaid624fa62017-11-14 23:42:30 +0800844 elif mount_point == "odm":
Tao Bao35f4ebc2018-09-27 15:31:11 -0700845 copy_prop("partition_size", "odm_size")
Yifan Hongcfb917a2020-05-07 14:58:20 -0700846 elif mount_point == "vendor_dlkm":
847 copy_prop("partition_size", "vendor_dlkm_size")
Yifan Hongf496f1b2020-07-15 16:52:59 -0700848 elif mount_point == "odm_dlkm":
849 copy_prop("partition_size", "odm_dlkm_size")
Yifan Hong56a6c3b2018-07-20 15:19:34 -0700850 elif mount_point == "product":
Tao Bao35f4ebc2018-09-27 15:31:11 -0700851 copy_prop("partition_size", "product_size")
Justin Yun6151e3f2019-06-25 15:58:13 +0900852 elif mount_point == "system_ext":
853 copy_prop("partition_size", "system_ext_size")
Yifan Hongbbcba1e2018-06-18 16:32:35 -0700854 return d
855
856
Ying Wangbd93d422011-10-28 17:02:30 -0700857def main(argv):
Yifan Hong8c3dce02019-04-09 17:03:57 +0000858 if len(argv) != 4:
Tao Baoc72727a2017-12-07 10:33:00 -0800859 print(__doc__)
Ying Wangbd93d422011-10-28 17:02:30 -0700860 sys.exit(1)
861
Tao Bao32fcdab2018-10-12 10:30:39 -0700862 common.InitLogging()
863
Ying Wangbd93d422011-10-28 17:02:30 -0700864 in_dir = argv[0]
865 glob_dict_file = argv[1]
866 out_file = argv[2]
Thierry Strudel74a81e62015-07-09 09:54:55 -0700867 target_out = argv[3]
Ying Wangbd93d422011-10-28 17:02:30 -0700868
869 glob_dict = LoadGlobalDict(glob_dict_file)
Ying Wangae61f502015-03-12 18:30:39 -0700870 if "mount_point" in glob_dict:
Mark Salyzyn780f5952018-10-19 13:44:36 -0700871 # The caller knows the mount point and provides a dictionary needed by
Tao Baoc7a6f1e2015-06-23 11:16:05 -0700872 # BuildImage().
Ying Wangae61f502015-03-12 18:30:39 -0700873 image_properties = glob_dict
Ying Wang9f8e8db2011-11-04 11:37:01 -0700874 else:
Ying Wangae61f502015-03-12 18:30:39 -0700875 image_filename = os.path.basename(out_file)
876 mount_point = ""
877 if image_filename == "system.img":
878 mount_point = "system"
Alex Light4e358ab2016-06-16 14:47:10 -0700879 elif image_filename == "system_other.img":
880 mount_point = "system_other"
Ying Wangae61f502015-03-12 18:30:39 -0700881 elif image_filename == "userdata.img":
882 mount_point = "data"
883 elif image_filename == "cache.img":
884 mount_point = "cache"
885 elif image_filename == "vendor.img":
886 mount_point = "vendor"
Bowgo Tsaid624fa62017-11-14 23:42:30 +0800887 elif image_filename == "odm.img":
888 mount_point = "odm"
Yifan Hongcfb917a2020-05-07 14:58:20 -0700889 elif image_filename == "vendor_dlkm.img":
890 mount_point = "vendor_dlkm"
Yifan Hongf496f1b2020-07-15 16:52:59 -0700891 elif image_filename == "odm_dlkm.img":
892 mount_point = "odm_dlkm"
Ying Wangae61f502015-03-12 18:30:39 -0700893 elif image_filename == "oem.img":
894 mount_point = "oem"
Jaekyun Seokb7735d82017-11-27 17:04:47 +0900895 elif image_filename == "product.img":
896 mount_point = "product"
Justin Yun6151e3f2019-06-25 15:58:13 +0900897 elif image_filename == "system_ext.img":
898 mount_point = "system_ext"
Ying Wangae61f502015-03-12 18:30:39 -0700899 else:
Tao Bao32fcdab2018-10-12 10:30:39 -0700900 logger.error("Unknown image file name %s", image_filename)
Tao Bao1c830bf2017-12-25 10:43:47 -0800901 sys.exit(1)
Ying Wangbd93d422011-10-28 17:02:30 -0700902
Ying Wangae61f502015-03-12 18:30:39 -0700903 image_properties = ImagePropFromGlobalDict(glob_dict, mount_point)
904
Tao Baoc6bd70a2018-09-27 16:58:00 -0700905 try:
906 BuildImage(in_dir, image_properties, out_file, target_out)
907 except:
Tao Bao32fcdab2018-10-12 10:30:39 -0700908 logger.error("Failed to build %s from %s", out_file, in_dir)
Tao Baoc6bd70a2018-09-27 16:58:00 -0700909 raise
Ying Wangbd93d422011-10-28 17:02:30 -0700910
Tao Bao32fcdab2018-10-12 10:30:39 -0700911
Ying Wangbd93d422011-10-28 17:02:30 -0700912if __name__ == '__main__':
Tao Bao1c830bf2017-12-25 10:43:47 -0800913 try:
914 main(sys.argv[1:])
915 finally:
916 common.Cleanup()