blob: 1fe468e0b14df1424e8d9ed8b748f98edfc6cb9b [file] [log] [blame]
Ying Wangbd93d422011-10-28 17:02:30 -07001#!/usr/bin/env python
2#
3# Copyright (C) 2011 The Android Open Source Project
4#
5# Licensed under the Apache License, Version 2.0 (the "License");
6# you may not use this file except in compliance with the License.
7# You may obtain a copy of the License at
8#
9# http://www.apache.org/licenses/LICENSE-2.0
10#
11# Unless required by applicable law or agreed to in writing, software
12# distributed under the License is distributed on an "AS IS" BASIS,
13# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14# See the License for the specific language governing permissions and
15# limitations under the License.
16
17"""
Tao Baoc72727a2017-12-07 10:33:00 -080018Builds output_image from the given input_directory, properties_file,
19and writes the image to target_output_directory.
Ying Wangbd93d422011-10-28 17:02:30 -070020
Tao Bao2bbb07c2019-05-07 13:12:21 -070021Usage: build_image input_directory properties_file output_image \\
Yifan Hong8c3dce02019-04-09 17:03:57 +000022 target_output_directory
Ying Wangbd93d422011-10-28 17:02:30 -070023"""
Tao Baoc72727a2017-12-07 10:33:00 -080024
25from __future__ import print_function
26
Tao Bao32fcdab2018-10-12 10:30:39 -070027import logging
Ying Wangbd93d422011-10-28 17:02:30 -070028import os
Ying Wang69e9b4d2012-11-26 18:10:23 -080029import os.path
Tao Baoc7a6f1e2015-06-23 11:16:05 -070030import re
Geremy Condrafd6f7512013-06-16 17:26:08 -070031import shutil
Tao Baoc72727a2017-12-07 10:33:00 -080032import sys
33
34import common
Tao Bao71197512018-10-11 14:08:45 -070035import verity_utils
Ying Wangbd93d422011-10-28 17:02:30 -070036
Tao Bao32fcdab2018-10-12 10:30:39 -070037logger = logging.getLogger(__name__)
38
Baligh Uddin601ddea2015-06-09 15:48:14 -070039OPTIONS = common.OPTIONS
Tao Bao71197512018-10-11 14:08:45 -070040BLOCK_SIZE = common.BLOCK_SIZE
Yifan Hongbbcba1e2018-06-18 16:32:35 -070041BYTES_IN_MB = 1024 * 1024
Geremy Condrae8e982a2014-05-16 19:14:30 -070042
Tao Baoc72727a2017-12-07 10:33:00 -080043
Tao Baoc6bd70a2018-09-27 16:58:00 -070044class BuildImageError(Exception):
45 """An Exception raised during image building."""
46
47 def __init__(self, message):
48 Exception.__init__(self, message)
49
50
Yifan Hongbbcba1e2018-06-18 16:32:35 -070051def GetDiskUsage(path):
Tao Baoc6bd70a2018-09-27 16:58:00 -070052 """Returns the number of bytes that "path" occupies on host.
Yifan Hongbbcba1e2018-06-18 16:32:35 -070053
54 Args:
Mark Salyzyn780f5952018-10-19 13:44:36 -070055 path: The directory or file to calculate size on.
Tao Baoc6bd70a2018-09-27 16:58:00 -070056
Yifan Hongbbcba1e2018-06-18 16:32:35 -070057 Returns:
Mark Salyzyn780f5952018-10-19 13:44:36 -070058 The number of bytes based on a 1K block_size.
Yifan Hongbbcba1e2018-06-18 16:32:35 -070059 """
Chirayu Desai96a913e2020-03-27 03:49:31 +053060 cmd = ["du", "-b", "-k", "-s", path]
Tao Baof3fc62c2018-10-25 12:23:12 -070061 output = common.RunAndCheckOutput(cmd, verbose=False)
Mark Salyzyn780f5952018-10-19 13:44:36 -070062 return int(output.split()[0]) * 1024
63
64
65def GetInodeUsage(path):
66 """Returns the number of inodes that "path" occupies on host.
67
68 Args:
69 path: The directory or file to calculate inode number on.
70
71 Returns:
72 The number of inodes used.
Mark Salyzyn780f5952018-10-19 13:44:36 -070073 """
74 cmd = ["find", path, "-print"]
Tao Baof3fc62c2018-10-25 12:23:12 -070075 output = common.RunAndCheckOutput(cmd, verbose=False)
David Anderson203057c2021-03-31 20:01:41 -070076 # increase by > 6% as number of files and directories is not whole picture.
Mark Salyzync25b2bf2019-01-16 08:03:10 -080077 inodes = output.count('\n')
David Anderson203057c2021-03-31 20:01:41 -070078 spare_inodes = inodes * 6 // 100
Mark Salyzyn60fa99d2019-01-16 08:03:10 -080079 min_spare_inodes = 12
Mark Salyzync25b2bf2019-01-16 08:03:10 -080080 if spare_inodes < min_spare_inodes:
81 spare_inodes = min_spare_inodes
82 return inodes + spare_inodes
Mark Salyzyn780f5952018-10-19 13:44:36 -070083
84
Jaegeuk Kim13696542021-05-22 09:47:48 -070085def GetFilesystemCharacteristics(fs_type, image_path, sparse_image=True):
Mark Salyzyn6541d0a2019-01-10 14:30:51 -080086 """Returns various filesystem characteristics of "image_path".
Mark Salyzyn780f5952018-10-19 13:44:36 -070087
88 Args:
Mark Salyzyn6541d0a2019-01-10 14:30:51 -080089 image_path: The file to analyze.
90 sparse_image: Image is sparse
Mark Salyzyn780f5952018-10-19 13:44:36 -070091
92 Returns:
93 The characteristics dictionary.
Mark Salyzyn780f5952018-10-19 13:44:36 -070094 """
Mark Salyzyn6541d0a2019-01-10 14:30:51 -080095 unsparse_image_path = image_path
96 if sparse_image:
97 unsparse_image_path = UnsparseImage(image_path, replace=False)
Mark Salyzyn780f5952018-10-19 13:44:36 -070098
Jaegeuk Kim13696542021-05-22 09:47:48 -070099 if fs_type.startswith("ext"):
100 cmd = ["tune2fs", "-l", unsparse_image_path]
101 elif fs_type.startswith("f2fs"):
102 cmd = ["fsck.f2fs", "-l", unsparse_image_path]
103
Mark Salyzyn780f5952018-10-19 13:44:36 -0700104 try:
105 output = common.RunAndCheckOutput(cmd, verbose=False)
Tao Baof3fc62c2018-10-25 12:23:12 -0700106 finally:
Mark Salyzyn6541d0a2019-01-10 14:30:51 -0800107 if sparse_image:
108 os.remove(unsparse_image_path)
Tao Baof3fc62c2018-10-25 12:23:12 -0700109 fs_dict = {}
Mark Salyzyn780f5952018-10-19 13:44:36 -0700110 for line in output.splitlines():
111 fields = line.split(":")
112 if len(fields) == 2:
113 fs_dict[fields[0].strip()] = fields[1].strip()
114 return fs_dict
Yifan Hongbbcba1e2018-06-18 16:32:35 -0700115
116
Geremy Condra6e8f53c2013-12-05 17:09:18 -0800117def UnsparseImage(sparse_image_path, replace=True):
Geremy Condrafd6f7512013-06-16 17:26:08 -0700118 img_dir = os.path.dirname(sparse_image_path)
119 unsparse_image_path = "unsparse_" + os.path.basename(sparse_image_path)
120 unsparse_image_path = os.path.join(img_dir, unsparse_image_path)
121 if os.path.exists(unsparse_image_path):
Geremy Condra6e8f53c2013-12-05 17:09:18 -0800122 if replace:
123 os.unlink(unsparse_image_path)
124 else:
Tao Baoc6bd70a2018-09-27 16:58:00 -0700125 return unsparse_image_path
Geremy Condrafd6f7512013-06-16 17:26:08 -0700126 inflate_command = ["simg2img", sparse_image_path, unsparse_image_path]
Tao Bao986ee862018-10-04 15:46:16 -0700127 try:
128 common.RunAndCheckOutput(inflate_command)
129 except:
Geremy Condrafd6f7512013-06-16 17:26:08 -0700130 os.remove(unsparse_image_path)
Tao Bao986ee862018-10-04 15:46:16 -0700131 raise
Tao Baoc6bd70a2018-09-27 16:58:00 -0700132 return unsparse_image_path
Geremy Condrafd6f7512013-06-16 17:26:08 -0700133
Tao Baoc72727a2017-12-07 10:33:00 -0800134
Mohamad Ayyashf8765552016-03-02 21:07:23 -0800135def ConvertBlockMapToBaseFs(block_map_file):
Tao Bao1c830bf2017-12-25 10:43:47 -0800136 base_fs_file = common.MakeTempFile(prefix="script_gen_", suffix=".base_fs")
Mohamad Ayyashf8765552016-03-02 21:07:23 -0800137 convert_command = ["blk_alloc_to_base_fs", block_map_file, base_fs_file]
Tao Bao986ee862018-10-04 15:46:16 -0700138 common.RunAndCheckOutput(convert_command)
Tao Baoc6bd70a2018-09-27 16:58:00 -0700139 return base_fs_file
Mohamad Ayyashf8765552016-03-02 21:07:23 -0800140
Tao Baod4349f22017-12-07 23:01:25 -0800141
Tao Baoc2606eb2018-07-20 14:44:46 -0700142def SetUpInDirAndFsConfig(origin_in, prop_dict):
143 """Returns the in_dir and fs_config that should be used for image building.
144
Tom Cherryd14b8952018-08-09 14:26:00 -0700145 When building system.img for all targets, it creates and returns a staged dir
146 that combines the contents of /system (i.e. in the given in_dir) and root.
Tao Baoc2606eb2018-07-20 14:44:46 -0700147
148 Args:
149 origin_in: Path to the input directory.
150 prop_dict: A property dict that contains info like partition size. Values
151 may be updated.
152
153 Returns:
154 A tuple of in_dir and fs_config that should be used to build the image.
155 """
156 fs_config = prop_dict.get("fs_config")
Tom Cherryd14b8952018-08-09 14:26:00 -0700157
158 if prop_dict["mount_point"] == "system_other":
159 prop_dict["mount_point"] = "system"
160 return origin_in, fs_config
161
162 if prop_dict["mount_point"] != "system":
Tao Baoc2606eb2018-07-20 14:44:46 -0700163 return origin_in, fs_config
164
Mark Salyzyn780f5952018-10-19 13:44:36 -0700165 if "first_pass" in prop_dict:
166 prop_dict["mount_point"] = "/"
167 return prop_dict["first_pass"]
168
Tao Baoc2606eb2018-07-20 14:44:46 -0700169 # Construct a staging directory of the root file system.
170 in_dir = common.MakeTempDir()
171 root_dir = prop_dict.get("root_dir")
172 if root_dir:
173 shutil.rmtree(in_dir)
174 shutil.copytree(root_dir, in_dir, symlinks=True)
175 in_dir_system = os.path.join(in_dir, "system")
176 shutil.rmtree(in_dir_system, ignore_errors=True)
177 shutil.copytree(origin_in, in_dir_system, symlinks=True)
178
179 # Change the mount point to "/".
180 prop_dict["mount_point"] = "/"
181 if fs_config:
182 # We need to merge the fs_config files of system and root.
183 merged_fs_config = common.MakeTempFile(
184 prefix="merged_fs_config", suffix=".txt")
185 with open(merged_fs_config, "w") as fw:
186 if "root_fs_config" in prop_dict:
187 with open(prop_dict["root_fs_config"]) as fr:
188 fw.writelines(fr.readlines())
189 with open(fs_config) as fr:
190 fw.writelines(fr.readlines())
191 fs_config = merged_fs_config
Mark Salyzyn780f5952018-10-19 13:44:36 -0700192 prop_dict["first_pass"] = (in_dir, fs_config)
Tao Baoc2606eb2018-07-20 14:44:46 -0700193 return in_dir, fs_config
194
195
Tao Baod4349f22017-12-07 23:01:25 -0800196def CheckHeadroom(ext4fs_output, prop_dict):
197 """Checks if there's enough headroom space available.
198
199 Headroom is the reserved space on system image (via PRODUCT_SYSTEM_HEADROOM),
200 which is useful for devices with low disk space that have system image
201 variation between builds. The 'partition_headroom' in prop_dict is the size
202 in bytes, while the numbers in 'ext4fs_output' are for 4K-blocks.
203
204 Args:
205 ext4fs_output: The output string from mke2fs command.
206 prop_dict: The property dict.
207
Tao Baod8a953d2018-01-02 21:19:27 -0800208 Raises:
209 AssertionError: On invalid input.
Tao Baoc6bd70a2018-09-27 16:58:00 -0700210 BuildImageError: On check failure.
Tao Baod4349f22017-12-07 23:01:25 -0800211 """
Tao Baod8a953d2018-01-02 21:19:27 -0800212 assert ext4fs_output is not None
213 assert prop_dict.get('fs_type', '').startswith('ext4')
214 assert 'partition_headroom' in prop_dict
215 assert 'mount_point' in prop_dict
216
Tao Baod4349f22017-12-07 23:01:25 -0800217 ext4fs_stats = re.compile(
218 r'Created filesystem with .* (?P<used_blocks>[0-9]+)/'
219 r'(?P<total_blocks>[0-9]+) blocks')
Tao Baoc72727a2017-12-07 10:33:00 -0800220 last_line = ext4fs_output.strip().split('\n')[-1]
221 m = ext4fs_stats.match(last_line)
Tao Baod4349f22017-12-07 23:01:25 -0800222 used_blocks = int(m.groupdict().get('used_blocks'))
223 total_blocks = int(m.groupdict().get('total_blocks'))
Mark Salyzyn780f5952018-10-19 13:44:36 -0700224 headroom_blocks = int(prop_dict['partition_headroom']) // BLOCK_SIZE
Tao Baod4349f22017-12-07 23:01:25 -0800225 adjusted_blocks = total_blocks - headroom_blocks
226 if used_blocks > adjusted_blocks:
Tao Baod8a953d2018-01-02 21:19:27 -0800227 mount_point = prop_dict["mount_point"]
Tao Baoc6bd70a2018-09-27 16:58:00 -0700228 raise BuildImageError(
229 "Error: Not enough room on {} (total: {} blocks, used: {} blocks, "
230 "headroom: {} blocks, available: {} blocks)".format(
231 mount_point, total_blocks, used_blocks, headroom_blocks,
232 adjusted_blocks))
Tao Baod4349f22017-12-07 23:01:25 -0800233
234
Mark Salyzyn3cd24602018-11-07 07:40:31 -0800235def BuildImageMkfs(in_dir, prop_dict, out_file, target_out, fs_config):
236 """Builds a pure image for the files under in_dir and writes it to out_file.
Tao Baoc2606eb2018-07-20 14:44:46 -0700237
Ying Wangbd93d422011-10-28 17:02:30 -0700238 Args:
Tao Baoc2606eb2018-07-20 14:44:46 -0700239 in_dir: Path to input directory.
240 prop_dict: A property dict that contains info like partition size. Values
241 will be updated with computed values.
242 out_file: The output image file.
243 target_out: Path to the TARGET_OUT directory as in Makefile. It actually
244 points to the /system directory under PRODUCT_OUT. fs_config (the one
245 under system/core/libcutils) reads device specific FS config files from
246 there.
Mark Salyzyn3cd24602018-11-07 07:40:31 -0800247 fs_config: The fs_config file that drives the prototype
Ying Wangbd93d422011-10-28 17:02:30 -0700248
Tao Baoc6bd70a2018-09-27 16:58:00 -0700249 Raises:
250 BuildImageError: On build image failures.
Ying Wangbd93d422011-10-28 17:02:30 -0700251 """
252 build_command = []
253 fs_type = prop_dict.get("fs_type", "")
Tao Baoc72727a2017-12-07 10:33:00 -0800254 run_e2fsck = False
Daniel Rosenberg6cc2c812019-12-17 17:36:31 -0800255 needs_projid = prop_dict.get("needs_projid", 0)
256 needs_casefold = prop_dict.get("needs_casefold", 0)
Jaegeuk Kimed754fb2020-10-12 19:50:05 -0700257 needs_compress = prop_dict.get("needs_compress", 0)
Geremy Condrafd6f7512013-06-16 17:26:08 -0700258
David Anderson9e95a022021-08-31 21:32:45 -0700259 disable_sparse = "disable_sparse" in prop_dict
260
Ying Wangbd93d422011-10-28 17:02:30 -0700261 if fs_type.startswith("ext"):
Adrien Schildknecht9a072cc2016-11-18 17:06:29 -0800262 build_command = [prop_dict["ext_mkuserimg"]]
David Anderson9e95a022021-08-31 21:32:45 -0700263 if "extfs_sparse_flag" in prop_dict and not disable_sparse:
Ying Wangbd93d422011-10-28 17:02:30 -0700264 build_command.append(prop_dict["extfs_sparse_flag"])
Tao Baoc72727a2017-12-07 10:33:00 -0800265 run_e2fsck = True
Ying Wangbd93d422011-10-28 17:02:30 -0700266 build_command.extend([in_dir, out_file, fs_type,
267 prop_dict["mount_point"]])
Tao Bao35f4ebc2018-09-27 15:31:11 -0700268 build_command.append(prop_dict["image_size"])
Ying Wangf3b86352014-11-18 18:03:13 -0800269 if "journal_size" in prop_dict:
270 build_command.extend(["-j", prop_dict["journal_size"]])
Doug Zongker850b8072013-12-05 15:54:55 -0800271 if "timestamp" in prop_dict:
272 build_command.extend(["-T", str(prop_dict["timestamp"])])
Ying Wanga2292c92015-03-24 19:07:40 -0700273 if fs_config:
Doug Zongker82822822014-06-16 09:10:55 -0700274 build_command.extend(["-C", fs_config])
Thierry Strudel74a81e62015-07-09 09:54:55 -0700275 if target_out:
276 build_command.extend(["-D", target_out])
Ying Wanga2292c92015-03-24 19:07:40 -0700277 if "block_list" in prop_dict:
278 build_command.extend(["-B", prop_dict["block_list"]])
Mohamad Ayyashf8765552016-03-02 21:07:23 -0800279 if "base_fs_file" in prop_dict:
280 base_fs_file = ConvertBlockMapToBaseFs(prop_dict["base_fs_file"])
Mohamad Ayyashf8765552016-03-02 21:07:23 -0800281 build_command.extend(["-d", base_fs_file])
Christoffer Dall8ed01f32014-12-17 21:34:12 +0100282 build_command.extend(["-L", prop_dict["mount_point"]])
Patrick Tjina1900842016-10-20 10:58:12 -0700283 if "extfs_inode_count" in prop_dict:
284 build_command.extend(["-i", prop_dict["extfs_inode_count"]])
Patrick Tjin3f5f9932018-03-23 11:36:43 -0700285 if "extfs_rsv_pct" in prop_dict:
286 build_command.extend(["-M", prop_dict["extfs_rsv_pct"]])
Connor O'Brien20f08c32017-01-05 16:48:14 -0800287 if "flash_erase_block_size" in prop_dict:
288 build_command.extend(["-e", prop_dict["flash_erase_block_size"]])
289 if "flash_logical_block_size" in prop_dict:
290 build_command.extend(["-o", prop_dict["flash_logical_block_size"]])
Tao Baod86e3112017-09-22 15:45:33 -0700291 # Specify UUID and hash_seed if using mke2fs.
HÃ¥kan Kvist2e1f5272021-05-11 11:14:48 +0200292 if os.path.basename(prop_dict["ext_mkuserimg"]) == "mkuserimg_mke2fs":
Tao Baod86e3112017-09-22 15:45:33 -0700293 if "uuid" in prop_dict:
294 build_command.extend(["-U", prop_dict["uuid"]])
295 if "hash_seed" in prop_dict:
296 build_command.extend(["-S", prop_dict["hash_seed"]])
Tamas Petzc0a8c632020-02-03 15:41:02 +0100297 if prop_dict.get("ext4_share_dup_blocks") == "true":
Jin Qianfde9f792018-01-22 13:15:46 -0800298 build_command.append("-c")
Daniel Rosenberg6cc2c812019-12-17 17:36:31 -0800299 if (needs_projid):
300 build_command.extend(["--inode_size", "512"])
301 else:
302 build_command.extend(["--inode_size", "256"])
Ying Wanga2292c92015-03-24 19:07:40 -0700303 if "selinux_fc" in prop_dict:
Kenny Rootf32dc712012-04-08 10:42:34 -0700304 build_command.append(prop_dict["selinux_fc"])
Gao Xiang961041a2020-06-17 13:59:16 +0800305 elif fs_type.startswith("erofs"):
306 build_command = ["mkerofsimage.sh"]
307 build_command.extend([in_dir, out_file])
David Anderson9e95a022021-08-31 21:32:45 -0700308 if "erofs_sparse_flag" in prop_dict and not disable_sparse:
Gao Xiang961041a2020-06-17 13:59:16 +0800309 build_command.extend([prop_dict["erofs_sparse_flag"]])
310 build_command.extend(["-m", prop_dict["mount_point"]])
311 if target_out:
312 build_command.extend(["-d", target_out])
313 if fs_config:
314 build_command.extend(["-C", fs_config])
315 if "selinux_fc" in prop_dict:
316 build_command.extend(["-c", prop_dict["selinux_fc"]])
Huang Jianan1ed889b2021-02-19 16:48:31 +0800317 if "timestamp" in prop_dict:
318 build_command.extend(["-T", str(prop_dict["timestamp"])])
319 if "uuid" in prop_dict:
320 build_command.extend(["-U", prop_dict["uuid"]])
Mohamad Ayyashb97746e2015-03-03 12:30:37 -0800321 elif fs_type.startswith("squash"):
322 build_command = ["mksquashfsimage.sh"]
323 build_command.extend([in_dir, out_file])
David Anderson9e95a022021-08-31 21:32:45 -0700324 if "squashfs_sparse_flag" in prop_dict and not disable_sparse:
Todd Poynorb2a555e2015-12-15 18:00:14 -0800325 build_command.extend([prop_dict["squashfs_sparse_flag"]])
Mohamad Ayyashb97746e2015-03-03 12:30:37 -0800326 build_command.extend(["-m", prop_dict["mount_point"]])
Thierry Strudel74a81e62015-07-09 09:54:55 -0700327 if target_out:
328 build_command.extend(["-d", target_out])
Mohamad Ayyash88378822016-04-07 22:10:51 -0700329 if fs_config:
330 build_command.extend(["-C", fs_config])
Ying Wanga2292c92015-03-24 19:07:40 -0700331 if "selinux_fc" in prop_dict:
Mohamad Ayyashb97746e2015-03-03 12:30:37 -0800332 build_command.extend(["-c", prop_dict["selinux_fc"]])
Mohamad Ayyashc3484f72016-06-13 09:46:58 -0700333 if "block_list" in prop_dict:
334 build_command.extend(["-B", prop_dict["block_list"]])
Ng Zhi An9446c1d2018-01-19 15:51:46 -0800335 if "squashfs_block_size" in prop_dict:
336 build_command.extend(["-b", prop_dict["squashfs_block_size"]])
Simon Wilsonf86e7ee2015-06-17 12:35:15 -0700337 if "squashfs_compressor" in prop_dict:
338 build_command.extend(["-z", prop_dict["squashfs_compressor"]])
339 if "squashfs_compressor_opt" in prop_dict:
340 build_command.extend(["-zo", prop_dict["squashfs_compressor_opt"]])
Tao Baoc72727a2017-12-07 10:33:00 -0800341 if prop_dict.get("squashfs_disable_4k_align") == "true":
Mohamad Ayyash1b6d3482016-06-15 15:53:07 -0700342 build_command.extend(["-a"])
JP Abgrall5bfed5a2014-06-16 14:17:40 -0700343 elif fs_type.startswith("f2fs"):
344 build_command = ["mkf2fsuserimg.sh"]
Tao Bao35f4ebc2018-09-27 15:31:11 -0700345 build_command.extend([out_file, prop_dict["image_size"]])
David Anderson9e95a022021-08-31 21:32:45 -0700346 if "f2fs_sparse_flag" in prop_dict and not disable_sparse:
Alistair Delva91238cc2019-10-16 10:53:41 -0700347 build_command.extend([prop_dict["f2fs_sparse_flag"]])
Jaegeuk Kim2ea1eba2017-11-28 19:21:28 -0800348 if fs_config:
349 build_command.extend(["-C", fs_config])
350 build_command.extend(["-f", in_dir])
351 if target_out:
352 build_command.extend(["-D", target_out])
353 if "selinux_fc" in prop_dict:
354 build_command.extend(["-s", prop_dict["selinux_fc"]])
355 build_command.extend(["-t", prop_dict["mount_point"]])
356 if "timestamp" in prop_dict:
357 build_command.extend(["-T", str(prop_dict["timestamp"])])
Jaegeuk Kim3dc47282021-06-13 08:54:01 -0700358 if "block_list" in prop_dict:
359 build_command.extend(["-B", prop_dict["block_list"]])
Jaegeuk Kim2ea1eba2017-11-28 19:21:28 -0800360 build_command.extend(["-L", prop_dict["mount_point"]])
Daniel Rosenberg6cc2c812019-12-17 17:36:31 -0800361 if (needs_projid):
362 build_command.append("--prjquota")
363 if (needs_casefold):
364 build_command.append("--casefold")
Jaegeuk Kim13696542021-05-22 09:47:48 -0700365 if (needs_compress or prop_dict.get("f2fs_compress") == "true"):
Jaegeuk Kimed754fb2020-10-12 19:50:05 -0700366 build_command.append("--compression")
Jaegeuk Kim3dc47282021-06-13 08:54:01 -0700367 if (prop_dict.get("mount_point") != "data"):
Jaegeuk Kim46e0ea22021-05-20 23:13:59 -0700368 build_command.append("--readonly")
Jaegeuk Kim3dc47282021-06-13 08:54:01 -0700369 if (prop_dict.get("f2fs_compress") == "true"):
Robin Hsu3e51f422020-11-04 09:29:09 +0800370 build_command.append("--sldc")
Jaegeuk Kim13696542021-05-22 09:47:48 -0700371 if (prop_dict.get("f2fs_sldc_flags") == None):
Robin Hsu3e51f422020-11-04 09:29:09 +0800372 build_command.append(str(0))
373 else:
Jaegeuk Kim13696542021-05-22 09:47:48 -0700374 sldc_flags_str = prop_dict.get("f2fs_sldc_flags")
Robin Hsu3e51f422020-11-04 09:29:09 +0800375 sldc_flags = sldc_flags_str.split()
376 build_command.append(str(len(sldc_flags)))
377 build_command.extend(sldc_flags)
Ying Wangbd93d422011-10-28 17:02:30 -0700378 else:
Tao Baoc6bd70a2018-09-27 16:58:00 -0700379 raise BuildImageError(
380 "Error: unknown filesystem type: {}".format(fs_type))
Ying Wangbd93d422011-10-28 17:02:30 -0700381
Tao Bao986ee862018-10-04 15:46:16 -0700382 try:
383 mkfs_output = common.RunAndCheckOutput(build_command)
384 except:
Tao Baoc6bd70a2018-09-27 16:58:00 -0700385 try:
386 du = GetDiskUsage(in_dir)
387 du_str = "{} bytes ({} MB)".format(du, du // BYTES_IN_MB)
Tao Bao986ee862018-10-04 15:46:16 -0700388 # Suppress any errors from GetDiskUsage() to avoid hiding the real errors
389 # from common.RunAndCheckOutput().
Tao Bao32fcdab2018-10-12 10:30:39 -0700390 except Exception: # pylint: disable=broad-except
391 logger.exception("Failed to compute disk usage with du")
Tao Baoc6bd70a2018-09-27 16:58:00 -0700392 du_str = "unknown"
Tao Bao4251fe92018-07-23 13:05:00 -0700393 print(
Mark Salyzyn3cd24602018-11-07 07:40:31 -0800394 "Out of space? Out of inodes? The tree size of {} is {}, "
395 "with reserved space of {} bytes ({} MB).".format(
Tao Baoc2606eb2018-07-20 14:44:46 -0700396 in_dir, du_str,
Tao Bao4251fe92018-07-23 13:05:00 -0700397 int(prop_dict.get("partition_reserved_size", 0)),
398 int(prop_dict.get("partition_reserved_size", 0)) // BYTES_IN_MB))
Huang Jiananf63abb12021-04-29 15:24:50 +0800399 if ("image_size" in prop_dict and "partition_size" in prop_dict):
400 print(
401 "The max image size for filesystem files is {} bytes ({} MB), "
402 "out of a total partition size of {} bytes ({} MB).".format(
403 int(prop_dict["image_size"]),
404 int(prop_dict["image_size"]) // BYTES_IN_MB,
405 int(prop_dict["partition_size"]),
406 int(prop_dict["partition_size"]) // BYTES_IN_MB))
Tao Bao986ee862018-10-04 15:46:16 -0700407 raise
Ying Wang69e9b4d2012-11-26 18:10:23 -0800408
Mark Salyzyn3cd24602018-11-07 07:40:31 -0800409 if run_e2fsck and prop_dict.get("skip_fsck") != "true":
410 unsparse_image = UnsparseImage(out_file, replace=False)
411
412 # Run e2fsck on the inflated image file
413 e2fsck_command = ["e2fsck", "-f", "-n", unsparse_image]
414 try:
415 common.RunAndCheckOutput(e2fsck_command)
416 finally:
417 os.remove(unsparse_image)
418
419 return mkfs_output
420
421
422def BuildImage(in_dir, prop_dict, out_file, target_out=None):
423 """Builds an image for the files under in_dir and writes it to out_file.
424
425 Args:
426 in_dir: Path to input directory.
427 prop_dict: A property dict that contains info like partition size. Values
428 will be updated with computed values.
429 out_file: The output image file.
430 target_out: Path to the TARGET_OUT directory as in Makefile. It actually
431 points to the /system directory under PRODUCT_OUT. fs_config (the one
432 under system/core/libcutils) reads device specific FS config files from
433 there.
434
435 Raises:
436 BuildImageError: On build image failures.
437 """
438 in_dir, fs_config = SetUpInDirAndFsConfig(in_dir, prop_dict)
439
440 build_command = []
441 fs_type = prop_dict.get("fs_type", "")
442
443 fs_spans_partition = True
Huang Jianan62d926e2020-12-04 16:53:06 +0800444 if fs_type.startswith("squash") or fs_type.startswith("erofs"):
Mark Salyzyn3cd24602018-11-07 07:40:31 -0800445 fs_spans_partition = False
Jaegeuk Kim13696542021-05-22 09:47:48 -0700446 elif fs_type.startswith("f2fs") and prop_dict.get("f2fs_compress") == "true":
447 fs_spans_partition = False
Mark Salyzyn3cd24602018-11-07 07:40:31 -0800448
449 # Get a builder for creating an image that's to be verified by Verified Boot,
450 # or None if not applicable.
451 verity_image_builder = verity_utils.CreateVerityImageBuilder(prop_dict)
452
David Anderson9e95a022021-08-31 21:32:45 -0700453 disable_sparse = "disable_sparse" in prop_dict
Huang Jiananffa1d572021-09-08 18:11:22 +0800454 mkfs_output = None
Mark Salyzyn3cd24602018-11-07 07:40:31 -0800455 if (prop_dict.get("use_dynamic_partition_size") == "true" and
456 "partition_size" not in prop_dict):
457 # If partition_size is not defined, use output of `du' + reserved_size.
Huang Jianan35f015e2020-12-04 16:58:24 +0800458 # For compressed file system, it's better to use the compressed size to avoid wasting space.
459 if fs_type.startswith("erofs"):
Huang Jiananffa1d572021-09-08 18:11:22 +0800460 mkfs_output = BuildImageMkfs(in_dir, prop_dict, out_file, target_out, fs_config)
461 if "erofs_sparse_flag" in prop_dict and not disable_sparse:
462 image_path = UnsparseImage(out_file, replace=False)
463 size = GetDiskUsage(image_path)
464 os.remove(image_path)
465 else:
466 size = GetDiskUsage(out_file)
Huang Jianan35f015e2020-12-04 16:58:24 +0800467 else:
468 size = GetDiskUsage(in_dir)
Mark Salyzyn3cd24602018-11-07 07:40:31 -0800469 logger.info(
470 "The tree size of %s is %d MB.", in_dir, size // BYTES_IN_MB)
471 # If not specified, give us 16MB margin for GetDiskUsage error ...
472 reserved_size = int(prop_dict.get("partition_reserved_size", BYTES_IN_MB * 16))
473 partition_headroom = int(prop_dict.get("partition_headroom", 0))
474 if fs_type.startswith("ext4") and partition_headroom > reserved_size:
475 reserved_size = partition_headroom
476 size += reserved_size
477 # Round this up to a multiple of 4K so that avbtool works
478 size = common.RoundUpTo4K(size)
479 if fs_type.startswith("ext"):
480 prop_dict["partition_size"] = str(size)
481 prop_dict["image_size"] = str(size)
482 if "extfs_inode_count" not in prop_dict:
483 prop_dict["extfs_inode_count"] = str(GetInodeUsage(in_dir))
484 logger.info(
485 "First Pass based on estimates of %d MB and %s inodes.",
486 size // BYTES_IN_MB, prop_dict["extfs_inode_count"])
487 BuildImageMkfs(in_dir, prop_dict, out_file, target_out, fs_config)
Mark Salyzyn6541d0a2019-01-10 14:30:51 -0800488 sparse_image = False
David Anderson9e95a022021-08-31 21:32:45 -0700489 if "extfs_sparse_flag" in prop_dict and not disable_sparse:
Mark Salyzyn6541d0a2019-01-10 14:30:51 -0800490 sparse_image = True
Jaegeuk Kim13696542021-05-22 09:47:48 -0700491 fs_dict = GetFilesystemCharacteristics(fs_type, out_file, sparse_image)
Mark Salyzyn3cd24602018-11-07 07:40:31 -0800492 os.remove(out_file)
493 block_size = int(fs_dict.get("Block size", "4096"))
494 free_size = int(fs_dict.get("Free blocks", "0")) * block_size
495 reserved_size = int(prop_dict.get("partition_reserved_size", 0))
496 partition_headroom = int(fs_dict.get("partition_headroom", 0))
497 if fs_type.startswith("ext4") and partition_headroom > reserved_size:
498 reserved_size = partition_headroom
499 if free_size <= reserved_size:
500 logger.info(
501 "Not worth reducing image %d <= %d.", free_size, reserved_size)
502 else:
503 size -= free_size
504 size += reserved_size
Mark Salyzyn60a716f2019-01-10 08:36:34 -0800505 if reserved_size == 0:
Mark Salyzync25b2bf2019-01-16 08:03:10 -0800506 # add .3% margin
507 size = size * 1003 // 1000
Mark Salyzyn60a716f2019-01-10 08:36:34 -0800508 # Use a minimum size, otherwise we will fail to calculate an AVB footer
509 # or fail to construct an ext4 image.
510 size = max(size, 256 * 1024)
Mark Salyzyn3cd24602018-11-07 07:40:31 -0800511 if block_size <= 4096:
512 size = common.RoundUpTo4K(size)
513 else:
514 size = ((size + block_size - 1) // block_size) * block_size
515 extfs_inode_count = prop_dict["extfs_inode_count"]
516 inodes = int(fs_dict.get("Inode count", extfs_inode_count))
517 inodes -= int(fs_dict.get("Free inodes", "0"))
Mark Salyzync25b2bf2019-01-16 08:03:10 -0800518 # add .2% margin or 1 inode, whichever is greater
519 spare_inodes = inodes * 2 // 1000
520 min_spare_inodes = 1
521 if spare_inodes < min_spare_inodes:
522 spare_inodes = min_spare_inodes
523 inodes += spare_inodes
Mark Salyzyn3cd24602018-11-07 07:40:31 -0800524 prop_dict["extfs_inode_count"] = str(inodes)
525 prop_dict["partition_size"] = str(size)
526 logger.info(
527 "Allocating %d Inodes for %s.", inodes, out_file)
Jaegeuk Kim13696542021-05-22 09:47:48 -0700528 elif fs_type.startswith("f2fs") and prop_dict.get("f2fs_compress") == "true":
529 prop_dict["partition_size"] = str(size)
530 prop_dict["image_size"] = str(size)
531 BuildImageMkfs(in_dir, prop_dict, out_file, target_out, fs_config)
532 sparse_image = False
David Anderson9e95a022021-08-31 21:32:45 -0700533 if "f2fs_sparse_flag" in prop_dict and not disable_sparse:
Jaegeuk Kim13696542021-05-22 09:47:48 -0700534 sparse_image = True
535 fs_dict = GetFilesystemCharacteristics(fs_type, out_file, sparse_image)
536 os.remove(out_file)
537 block_count = int(fs_dict.get("block_count", "0"))
538 log_blocksize = int(fs_dict.get("log_blocksize", "12"))
539 size = block_count << log_blocksize
540 prop_dict["partition_size"] = str(size)
Mark Salyzyn3cd24602018-11-07 07:40:31 -0800541 if verity_image_builder:
542 size = verity_image_builder.CalculateDynamicPartitionSize(size)
543 prop_dict["partition_size"] = str(size)
544 logger.info(
545 "Allocating %d MB for %s.", size // BYTES_IN_MB, out_file)
546
547 prop_dict["image_size"] = prop_dict["partition_size"]
548
549 # Adjust the image size to make room for the hashes if this is to be verified.
550 if verity_image_builder:
551 max_image_size = verity_image_builder.CalculateMaxImageSize()
552 prop_dict["image_size"] = str(max_image_size)
553
Huang Jiananffa1d572021-09-08 18:11:22 +0800554 if not mkfs_output:
555 mkfs_output = BuildImageMkfs(in_dir, prop_dict, out_file, target_out, fs_config)
Mark Salyzyn3cd24602018-11-07 07:40:31 -0800556
Tao Baod4349f22017-12-07 23:01:25 -0800557 # Check if there's enough headroom space available for ext4 image.
Tao Bao79d52f82017-12-07 14:07:44 -0800558 if "partition_headroom" in prop_dict and fs_type.startswith("ext4"):
Tao Baoc6bd70a2018-09-27 16:58:00 -0700559 CheckHeadroom(mkfs_output, prop_dict)
Tao Baoc7a6f1e2015-06-23 11:16:05 -0700560
Tao Bao7549e5e2018-10-03 14:23:59 -0700561 if not fs_spans_partition and verity_image_builder:
562 verity_image_builder.PadSparseImage(out_file)
Mohamad Ayyashdd063522015-03-24 12:42:03 -0700563
Tao Baoc72727a2017-12-07 10:33:00 -0800564 # Create the verified image if this is to be verified.
Tao Bao7549e5e2018-10-03 14:23:59 -0700565 if verity_image_builder:
566 verity_image_builder.Build(out_file)
David Zeuthen4014a9d2016-09-30 17:29:22 -0400567
Ying Wangbd93d422011-10-28 17:02:30 -0700568
569def ImagePropFromGlobalDict(glob_dict, mount_point):
570 """Build an image property dictionary from the global dictionary.
571
572 Args:
573 glob_dict: the global dictionary from the build system.
574 mount_point: such as "system", "data" etc.
575 """
Doug Zongker1ad7ade2013-12-06 11:53:27 -0800576 d = {}
Tao Bao052ae352015-09-28 13:44:13 -0700577
Tao Bao822f5842015-09-30 16:01:14 -0700578 if "build.prop" in glob_dict:
Tianjie Xu0fde41e2020-05-09 05:24:18 +0000579 timestamp = glob_dict["build.prop"].GetProp("ro.build.date.utc")
580 if timestamp:
581 d["timestamp"] = timestamp
Ying Wang9f8e8db2011-11-04 11:37:01 -0700582
583 def copy_prop(src_p, dest_p):
Patrick Tjin3f5f9932018-03-23 11:36:43 -0700584 """Copy a property from the global dictionary.
585
586 Args:
587 src_p: The source property in the global dictionary.
588 dest_p: The destination property.
589 Returns:
590 True if property was found and copied, False otherwise.
591 """
Ying Wang9f8e8db2011-11-04 11:37:01 -0700592 if src_p in glob_dict:
593 d[dest_p] = str(glob_dict[src_p])
Patrick Tjin3f5f9932018-03-23 11:36:43 -0700594 return True
595 return False
Ying Wang9f8e8db2011-11-04 11:37:01 -0700596
Ying Wangbd93d422011-10-28 17:02:30 -0700597 common_props = (
Ying Wangbd93d422011-10-28 17:02:30 -0700598 "extfs_sparse_flag",
Gao Xiang961041a2020-06-17 13:59:16 +0800599 "erofs_sparse_flag",
Todd Poynorb2a555e2015-12-15 18:00:14 -0800600 "squashfs_sparse_flag",
Jaegeuk Kim13696542021-05-22 09:47:48 -0700601 "system_f2fs_compress",
Robin Hsu3e51f422020-11-04 09:29:09 +0800602 "system_f2fs_sldc_flags",
Alistair Delva91238cc2019-10-16 10:53:41 -0700603 "f2fs_sparse_flag",
Ying Wang6a42a252013-02-27 13:54:02 -0800604 "skip_fsck",
Adrien Schildknecht9a072cc2016-11-18 17:06:29 -0800605 "ext_mkuserimg",
Geremy Condrafd6f7512013-06-16 17:26:08 -0700606 "verity",
Geremy Condrafd6f7512013-06-16 17:26:08 -0700607 "verity_key",
Sami Tolvanenf99b5312015-05-20 07:30:57 +0100608 "verity_signer_cmd",
David Zeuthen4014a9d2016-09-30 17:29:22 -0400609 "verity_fec",
Bowgo Tsai6ceeb1a2017-10-11 16:21:48 +0800610 "verity_disable",
Bowgo Tsai3e599ea2017-05-26 18:30:04 +0800611 "avb_enable",
Tao Bao2b6dfd62017-09-27 17:17:43 -0700612 "avb_avbtool",
Yifan Hong2dae5722018-07-31 12:47:27 -0700613 "use_dynamic_partition_size",
Tao Bao2b6dfd62017-09-27 17:17:43 -0700614 )
Ying Wangbd93d422011-10-28 17:02:30 -0700615 for p in common_props:
Ying Wang9f8e8db2011-11-04 11:37:01 -0700616 copy_prop(p, p)
Ying Wangbd93d422011-10-28 17:02:30 -0700617
618 d["mount_point"] = mount_point
619 if mount_point == "system":
Bowgo Tsai3e599ea2017-05-26 18:30:04 +0800620 copy_prop("avb_system_hashtree_enable", "avb_hashtree_enable")
621 copy_prop("avb_system_add_hashtree_footer_args",
622 "avb_add_hashtree_footer_args")
623 copy_prop("avb_system_key_path", "avb_key_path")
624 copy_prop("avb_system_algorithm", "avb_algorithm")
Daniel Normand5fe8622020-01-08 17:01:11 -0800625 copy_prop("avb_system_salt", "avb_salt")
Ying Wang9f8e8db2011-11-04 11:37:01 -0700626 copy_prop("fs_type", "fs_type")
Julius D'souza001c6762017-05-03 13:43:27 -0700627 # Copy the generic system fs type first, override with specific one if
Dan Albert8b72aef2015-03-23 19:13:21 -0700628 # available.
Mohamad Ayyashb97746e2015-03-03 12:30:37 -0800629 copy_prop("system_fs_type", "fs_type")
Julius D'souza001c6762017-05-03 13:43:27 -0700630 copy_prop("system_headroom", "partition_headroom")
Ying Wang9f8e8db2011-11-04 11:37:01 -0700631 copy_prop("system_size", "partition_size")
Tao Bao332a96b2018-03-31 10:27:35 -0700632 if not copy_prop("system_journal_size", "journal_size"):
633 d["journal_size"] = "0"
Daniel Rosenbergf4eabc32014-07-10 15:42:38 -0700634 copy_prop("system_verity_block_device", "verity_block_device")
Tao Baof3282b42015-04-01 11:21:55 -0700635 copy_prop("system_root_image", "system_root_image")
Tao Bao8bfd3c72018-07-20 15:20:28 -0700636 copy_prop("root_dir", "root_dir")
637 copy_prop("root_fs_config", "root_fs_config")
Jin Qianfde9f792018-01-22 13:15:46 -0800638 copy_prop("ext4_share_dup_blocks", "ext4_share_dup_blocks")
Jaegeuk Kim13696542021-05-22 09:47:48 -0700639 copy_prop("system_f2fs_compress", "f2fs_compress")
640 copy_prop("system_f2fs_sldc_flags", "f2fs_sldc_flags")
Simon Wilsonf86e7ee2015-06-17 12:35:15 -0700641 copy_prop("system_squashfs_compressor", "squashfs_compressor")
642 copy_prop("system_squashfs_compressor_opt", "squashfs_compressor_opt")
Mohamad Ayyashdfec8152016-05-24 12:59:30 -0700643 copy_prop("system_squashfs_block_size", "squashfs_block_size")
Mohamad Ayyash1b6d3482016-06-15 15:53:07 -0700644 copy_prop("system_squashfs_disable_4k_align", "squashfs_disable_4k_align")
Mohamad Ayyashf8765552016-03-02 21:07:23 -0800645 copy_prop("system_base_fs_file", "base_fs_file")
Patrick Tjina1900842016-10-20 10:58:12 -0700646 copy_prop("system_extfs_inode_count", "extfs_inode_count")
Patrick Tjin3f5f9932018-03-23 11:36:43 -0700647 if not copy_prop("system_extfs_rsv_pct", "extfs_rsv_pct"):
648 d["extfs_rsv_pct"] = "0"
Yifan Hongbbcba1e2018-06-18 16:32:35 -0700649 copy_prop("system_reserved_size", "partition_reserved_size")
Daniel Norman72c626f2019-05-13 15:58:14 -0700650 copy_prop("system_selinux_fc", "selinux_fc")
David Anderson9e95a022021-08-31 21:32:45 -0700651 copy_prop("system_disable_sparse", "disable_sparse")
Alex Light4e358ab2016-06-16 14:47:10 -0700652 elif mount_point == "system_other":
Tao Baoc72727a2017-12-07 10:33:00 -0800653 # We inherit the selinux policies of /system since we contain some of its
654 # files.
Bowgo Tsai1e04bf72019-01-23 22:19:19 +0800655 copy_prop("avb_system_other_hashtree_enable", "avb_hashtree_enable")
656 copy_prop("avb_system_other_add_hashtree_footer_args",
Bowgo Tsai3e599ea2017-05-26 18:30:04 +0800657 "avb_add_hashtree_footer_args")
Bowgo Tsai1e04bf72019-01-23 22:19:19 +0800658 copy_prop("avb_system_other_key_path", "avb_key_path")
659 copy_prop("avb_system_other_algorithm", "avb_algorithm")
Daniel Normand5fe8622020-01-08 17:01:11 -0800660 copy_prop("avb_system_other_salt", "avb_salt")
Alex Light4e358ab2016-06-16 14:47:10 -0700661 copy_prop("fs_type", "fs_type")
662 copy_prop("system_fs_type", "fs_type")
Bowgo Tsai867ab662019-01-29 13:30:18 +0800663 copy_prop("system_other_size", "partition_size")
Tao Bao332a96b2018-03-31 10:27:35 -0700664 if not copy_prop("system_journal_size", "journal_size"):
665 d["journal_size"] = "0"
Alex Light4e358ab2016-06-16 14:47:10 -0700666 copy_prop("system_verity_block_device", "verity_block_device")
Mark Salyzynf0cef8d2018-10-29 10:55:06 -0700667 copy_prop("ext4_share_dup_blocks", "ext4_share_dup_blocks")
Jaegeuk Kim13696542021-05-22 09:47:48 -0700668 copy_prop("system_f2fs_compress", "f2fs_compress")
669 copy_prop("system_f2fs_sldc_flags", "f2fs_sldc_flags")
Alex Light4e358ab2016-06-16 14:47:10 -0700670 copy_prop("system_squashfs_compressor", "squashfs_compressor")
671 copy_prop("system_squashfs_compressor_opt", "squashfs_compressor_opt")
672 copy_prop("system_squashfs_block_size", "squashfs_block_size")
Patrick Tjina1900842016-10-20 10:58:12 -0700673 copy_prop("system_extfs_inode_count", "extfs_inode_count")
Patrick Tjin3f5f9932018-03-23 11:36:43 -0700674 if not copy_prop("system_extfs_rsv_pct", "extfs_rsv_pct"):
675 d["extfs_rsv_pct"] = "0"
Yifan Hongbbcba1e2018-06-18 16:32:35 -0700676 copy_prop("system_reserved_size", "partition_reserved_size")
Daniel Norman72c626f2019-05-13 15:58:14 -0700677 copy_prop("system_selinux_fc", "selinux_fc")
David Anderson9e95a022021-08-31 21:32:45 -0700678 copy_prop("system_disable_sparse", "disable_sparse")
Ying Wangbd93d422011-10-28 17:02:30 -0700679 elif mount_point == "data":
JP Abgrall5bfed5a2014-06-16 14:17:40 -0700680 # Copy the generic fs type first, override with specific one if available.
Ying Wang9f8e8db2011-11-04 11:37:01 -0700681 copy_prop("fs_type", "fs_type")
JP Abgrall5bfed5a2014-06-16 14:17:40 -0700682 copy_prop("userdata_fs_type", "fs_type")
Ying Wang9f8e8db2011-11-04 11:37:01 -0700683 copy_prop("userdata_size", "partition_size")
Tao Baoc72727a2017-12-07 10:33:00 -0800684 copy_prop("flash_logical_block_size", "flash_logical_block_size")
Connor O'Brien20f08c32017-01-05 16:48:14 -0800685 copy_prop("flash_erase_block_size", "flash_erase_block_size")
Daniel Norman72c626f2019-05-13 15:58:14 -0700686 copy_prop("userdata_selinux_fc", "selinux_fc")
Daniel Rosenberg6cc2c812019-12-17 17:36:31 -0800687 copy_prop("needs_casefold", "needs_casefold")
688 copy_prop("needs_projid", "needs_projid")
Jaegeuk Kimed754fb2020-10-12 19:50:05 -0700689 copy_prop("needs_compress", "needs_compress")
Ying Wang9f8e8db2011-11-04 11:37:01 -0700690 elif mount_point == "cache":
691 copy_prop("cache_fs_type", "fs_type")
692 copy_prop("cache_size", "partition_size")
Daniel Norman72c626f2019-05-13 15:58:14 -0700693 copy_prop("cache_selinux_fc", "selinux_fc")
Ying Wanga0febe52013-03-20 11:02:05 -0700694 elif mount_point == "vendor":
Bowgo Tsai3e599ea2017-05-26 18:30:04 +0800695 copy_prop("avb_vendor_hashtree_enable", "avb_hashtree_enable")
696 copy_prop("avb_vendor_add_hashtree_footer_args",
697 "avb_add_hashtree_footer_args")
698 copy_prop("avb_vendor_key_path", "avb_key_path")
699 copy_prop("avb_vendor_algorithm", "avb_algorithm")
Daniel Normand5fe8622020-01-08 17:01:11 -0800700 copy_prop("avb_vendor_salt", "avb_salt")
Ying Wanga0febe52013-03-20 11:02:05 -0700701 copy_prop("vendor_fs_type", "fs_type")
702 copy_prop("vendor_size", "partition_size")
Tao Bao332a96b2018-03-31 10:27:35 -0700703 if not copy_prop("vendor_journal_size", "journal_size"):
704 d["journal_size"] = "0"
Daniel Rosenbergf4eabc32014-07-10 15:42:38 -0700705 copy_prop("vendor_verity_block_device", "verity_block_device")
Jin Qianfde9f792018-01-22 13:15:46 -0800706 copy_prop("ext4_share_dup_blocks", "ext4_share_dup_blocks")
Jaegeuk Kim13696542021-05-22 09:47:48 -0700707 copy_prop("vendor_f2fs_compress", "f2fs_compress")
708 copy_prop("vendor_f2fs_sldc_flags", "f2fs_sldc_flags")
Patrick Tjine11aa502016-02-09 15:40:38 -0800709 copy_prop("vendor_squashfs_compressor", "squashfs_compressor")
710 copy_prop("vendor_squashfs_compressor_opt", "squashfs_compressor_opt")
Mohamad Ayyashdfec8152016-05-24 12:59:30 -0700711 copy_prop("vendor_squashfs_block_size", "squashfs_block_size")
Mohamad Ayyash1b6d3482016-06-15 15:53:07 -0700712 copy_prop("vendor_squashfs_disable_4k_align", "squashfs_disable_4k_align")
Mohamad Ayyashf8765552016-03-02 21:07:23 -0800713 copy_prop("vendor_base_fs_file", "base_fs_file")
Patrick Tjina1900842016-10-20 10:58:12 -0700714 copy_prop("vendor_extfs_inode_count", "extfs_inode_count")
Patrick Tjin3f5f9932018-03-23 11:36:43 -0700715 if not copy_prop("vendor_extfs_rsv_pct", "extfs_rsv_pct"):
716 d["extfs_rsv_pct"] = "0"
Yifan Hong749062d2018-06-19 16:23:16 -0700717 copy_prop("vendor_reserved_size", "partition_reserved_size")
Daniel Norman72c626f2019-05-13 15:58:14 -0700718 copy_prop("vendor_selinux_fc", "selinux_fc")
David Anderson9e95a022021-08-31 21:32:45 -0700719 copy_prop("vendor_disable_sparse", "disable_sparse")
Jaekyun Seokb7735d82017-11-27 17:04:47 +0900720 elif mount_point == "product":
721 copy_prop("avb_product_hashtree_enable", "avb_hashtree_enable")
722 copy_prop("avb_product_add_hashtree_footer_args",
723 "avb_add_hashtree_footer_args")
724 copy_prop("avb_product_key_path", "avb_key_path")
725 copy_prop("avb_product_algorithm", "avb_algorithm")
Daniel Normand5fe8622020-01-08 17:01:11 -0800726 copy_prop("avb_product_salt", "avb_salt")
Jaekyun Seokb7735d82017-11-27 17:04:47 +0900727 copy_prop("product_fs_type", "fs_type")
728 copy_prop("product_size", "partition_size")
Tao Bao332a96b2018-03-31 10:27:35 -0700729 if not copy_prop("product_journal_size", "journal_size"):
730 d["journal_size"] = "0"
Jaekyun Seokb7735d82017-11-27 17:04:47 +0900731 copy_prop("product_verity_block_device", "verity_block_device")
Mark Salyzynf0cef8d2018-10-29 10:55:06 -0700732 copy_prop("ext4_share_dup_blocks", "ext4_share_dup_blocks")
Jaegeuk Kim13696542021-05-22 09:47:48 -0700733 copy_prop("product_f2fs_compress", "f2fs_compress")
734 copy_prop("product_f2fs_sldc_flags", "f2fs_sldc_flags")
Jaekyun Seokb7735d82017-11-27 17:04:47 +0900735 copy_prop("product_squashfs_compressor", "squashfs_compressor")
736 copy_prop("product_squashfs_compressor_opt", "squashfs_compressor_opt")
737 copy_prop("product_squashfs_block_size", "squashfs_block_size")
738 copy_prop("product_squashfs_disable_4k_align", "squashfs_disable_4k_align")
739 copy_prop("product_base_fs_file", "base_fs_file")
740 copy_prop("product_extfs_inode_count", "extfs_inode_count")
Patrick Tjin3f5f9932018-03-23 11:36:43 -0700741 if not copy_prop("product_extfs_rsv_pct", "extfs_rsv_pct"):
742 d["extfs_rsv_pct"] = "0"
Yifan Hong56a6c3b2018-07-20 15:19:34 -0700743 copy_prop("product_reserved_size", "partition_reserved_size")
Daniel Norman72c626f2019-05-13 15:58:14 -0700744 copy_prop("product_selinux_fc", "selinux_fc")
David Anderson9e95a022021-08-31 21:32:45 -0700745 copy_prop("product_disable_sparse", "disable_sparse")
Justin Yun6151e3f2019-06-25 15:58:13 +0900746 elif mount_point == "system_ext":
747 copy_prop("avb_system_ext_hashtree_enable", "avb_hashtree_enable")
748 copy_prop("avb_system_ext_add_hashtree_footer_args",
Dario Freni5f681e12018-05-29 13:09:01 +0100749 "avb_add_hashtree_footer_args")
Justin Yun6151e3f2019-06-25 15:58:13 +0900750 copy_prop("avb_system_ext_key_path", "avb_key_path")
751 copy_prop("avb_system_ext_algorithm", "avb_algorithm")
Daniel Normand5fe8622020-01-08 17:01:11 -0800752 copy_prop("avb_system_ext_salt", "avb_salt")
Justin Yun6151e3f2019-06-25 15:58:13 +0900753 copy_prop("system_ext_fs_type", "fs_type")
754 copy_prop("system_ext_size", "partition_size")
755 if not copy_prop("system_ext_journal_size", "journal_size"):
Dario Freni5f681e12018-05-29 13:09:01 +0100756 d["journal_size"] = "0"
Justin Yun6151e3f2019-06-25 15:58:13 +0900757 copy_prop("system_ext_verity_block_device", "verity_block_device")
Mark Salyzynf0cef8d2018-10-29 10:55:06 -0700758 copy_prop("ext4_share_dup_blocks", "ext4_share_dup_blocks")
Jaegeuk Kim13696542021-05-22 09:47:48 -0700759 copy_prop("system_ext_f2fs_compress", "f2fs_compress")
760 copy_prop("system_ext_f2fs_sldc_flags", "f2fs_sldc_flags")
Justin Yun6151e3f2019-06-25 15:58:13 +0900761 copy_prop("system_ext_squashfs_compressor", "squashfs_compressor")
762 copy_prop("system_ext_squashfs_compressor_opt",
Dario Freni5f681e12018-05-29 13:09:01 +0100763 "squashfs_compressor_opt")
Justin Yun6151e3f2019-06-25 15:58:13 +0900764 copy_prop("system_ext_squashfs_block_size", "squashfs_block_size")
765 copy_prop("system_ext_squashfs_disable_4k_align",
Dario Freni5f681e12018-05-29 13:09:01 +0100766 "squashfs_disable_4k_align")
Justin Yun6151e3f2019-06-25 15:58:13 +0900767 copy_prop("system_ext_base_fs_file", "base_fs_file")
768 copy_prop("system_ext_extfs_inode_count", "extfs_inode_count")
769 if not copy_prop("system_ext_extfs_rsv_pct", "extfs_rsv_pct"):
Dario Freni5f681e12018-05-29 13:09:01 +0100770 d["extfs_rsv_pct"] = "0"
Justin Yun6151e3f2019-06-25 15:58:13 +0900771 copy_prop("system_ext_reserved_size", "partition_reserved_size")
772 copy_prop("system_ext_selinux_fc", "selinux_fc")
David Anderson9e95a022021-08-31 21:32:45 -0700773 copy_prop("system_ext_disable_sparse", "disable_sparse")
Bowgo Tsaid624fa62017-11-14 23:42:30 +0800774 elif mount_point == "odm":
775 copy_prop("avb_odm_hashtree_enable", "avb_hashtree_enable")
776 copy_prop("avb_odm_add_hashtree_footer_args",
777 "avb_add_hashtree_footer_args")
778 copy_prop("avb_odm_key_path", "avb_key_path")
779 copy_prop("avb_odm_algorithm", "avb_algorithm")
Daniel Normand5fe8622020-01-08 17:01:11 -0800780 copy_prop("avb_odm_salt", "avb_salt")
Bowgo Tsaid624fa62017-11-14 23:42:30 +0800781 copy_prop("odm_fs_type", "fs_type")
782 copy_prop("odm_size", "partition_size")
783 if not copy_prop("odm_journal_size", "journal_size"):
784 d["journal_size"] = "0"
785 copy_prop("odm_verity_block_device", "verity_block_device")
Mark Salyzynf0cef8d2018-10-29 10:55:06 -0700786 copy_prop("ext4_share_dup_blocks", "ext4_share_dup_blocks")
Bowgo Tsaid624fa62017-11-14 23:42:30 +0800787 copy_prop("odm_squashfs_compressor", "squashfs_compressor")
788 copy_prop("odm_squashfs_compressor_opt", "squashfs_compressor_opt")
789 copy_prop("odm_squashfs_block_size", "squashfs_block_size")
790 copy_prop("odm_squashfs_disable_4k_align", "squashfs_disable_4k_align")
791 copy_prop("odm_base_fs_file", "base_fs_file")
792 copy_prop("odm_extfs_inode_count", "extfs_inode_count")
793 if not copy_prop("odm_extfs_rsv_pct", "extfs_rsv_pct"):
794 d["extfs_rsv_pct"] = "0"
795 copy_prop("odm_reserved_size", "partition_reserved_size")
Daniel Norman72c626f2019-05-13 15:58:14 -0700796 copy_prop("odm_selinux_fc", "selinux_fc")
David Anderson9e95a022021-08-31 21:32:45 -0700797 copy_prop("odm_disable_sparse", "disable_sparse")
Yifan Hongcfb917a2020-05-07 14:58:20 -0700798 elif mount_point == "vendor_dlkm":
799 copy_prop("avb_vendor_dlkm_hashtree_enable", "avb_hashtree_enable")
800 copy_prop("avb_vendor_dlkm_add_hashtree_footer_args",
801 "avb_add_hashtree_footer_args")
802 copy_prop("avb_vendor_dlkm_key_path", "avb_key_path")
803 copy_prop("avb_vendor_dlkm_algorithm", "avb_algorithm")
804 copy_prop("avb_vendor_dlkm_salt", "avb_salt")
805 copy_prop("vendor_dlkm_fs_type", "fs_type")
806 copy_prop("vendor_dlkm_size", "partition_size")
Jaegeuk Kim13696542021-05-22 09:47:48 -0700807 copy_prop("vendor_dlkm_f2fs_compress", "f2fs_compress")
808 copy_prop("vendor_dlkm_f2fs_sldc_flags", "f2fs_sldc_flags")
Yifan Hongcfb917a2020-05-07 14:58:20 -0700809 if not copy_prop("vendor_dlkm_journal_size", "journal_size"):
810 d["journal_size"] = "0"
811 copy_prop("vendor_dlkm_verity_block_device", "verity_block_device")
812 copy_prop("ext4_share_dup_blocks", "ext4_share_dup_blocks")
813 copy_prop("vendor_dlkm_squashfs_compressor", "squashfs_compressor")
814 copy_prop("vendor_dlkm_squashfs_compressor_opt", "squashfs_compressor_opt")
815 copy_prop("vendor_dlkm_squashfs_block_size", "squashfs_block_size")
816 copy_prop("vendor_dlkm_squashfs_disable_4k_align", "squashfs_disable_4k_align")
817 copy_prop("vendor_dlkm_base_fs_file", "base_fs_file")
818 copy_prop("vendor_dlkm_extfs_inode_count", "extfs_inode_count")
819 if not copy_prop("vendor_dlkm_extfs_rsv_pct", "extfs_rsv_pct"):
820 d["extfs_rsv_pct"] = "0"
821 copy_prop("vendor_dlkm_reserved_size", "partition_reserved_size")
822 copy_prop("vendor_dlkm_selinux_fc", "selinux_fc")
David Anderson9e95a022021-08-31 21:32:45 -0700823 copy_prop("vendor_dlkm_disable_sparse", "disable_sparse")
Yifan Hongf496f1b2020-07-15 16:52:59 -0700824 elif mount_point == "odm_dlkm":
825 copy_prop("avb_odm_dlkm_hashtree_enable", "avb_hashtree_enable")
826 copy_prop("avb_odm_dlkm_add_hashtree_footer_args",
827 "avb_add_hashtree_footer_args")
828 copy_prop("avb_odm_dlkm_key_path", "avb_key_path")
829 copy_prop("avb_odm_dlkm_algorithm", "avb_algorithm")
830 copy_prop("avb_odm_dlkm_salt", "avb_salt")
831 copy_prop("odm_dlkm_fs_type", "fs_type")
832 copy_prop("odm_dlkm_size", "partition_size")
833 if not copy_prop("odm_dlkm_journal_size", "journal_size"):
834 d["journal_size"] = "0"
835 copy_prop("odm_dlkm_verity_block_device", "verity_block_device")
836 copy_prop("ext4_share_dup_blocks", "ext4_share_dup_blocks")
837 copy_prop("odm_dlkm_squashfs_compressor", "squashfs_compressor")
838 copy_prop("odm_dlkm_squashfs_compressor_opt", "squashfs_compressor_opt")
839 copy_prop("odm_dlkm_squashfs_block_size", "squashfs_block_size")
840 copy_prop("odm_dlkm_squashfs_disable_4k_align", "squashfs_disable_4k_align")
841 copy_prop("odm_dlkm_base_fs_file", "base_fs_file")
842 copy_prop("odm_dlkm_extfs_inode_count", "extfs_inode_count")
843 if not copy_prop("odm_dlkm_extfs_rsv_pct", "extfs_rsv_pct"):
844 d["extfs_rsv_pct"] = "0"
845 copy_prop("odm_dlkm_reserved_size", "partition_reserved_size")
846 copy_prop("odm_dlkm_selinux_fc", "selinux_fc")
David Anderson9e95a022021-08-31 21:32:45 -0700847 copy_prop("odm_dlkm_disable_sparse", "disable_sparse")
Ying Wangb8888432014-03-11 17:13:27 -0700848 elif mount_point == "oem":
849 copy_prop("fs_type", "fs_type")
850 copy_prop("oem_size", "partition_size")
Tao Bao332a96b2018-03-31 10:27:35 -0700851 if not copy_prop("oem_journal_size", "journal_size"):
852 d["journal_size"] = "0"
Patrick Tjina1900842016-10-20 10:58:12 -0700853 copy_prop("oem_extfs_inode_count", "extfs_inode_count")
Mark Salyzynf0cef8d2018-10-29 10:55:06 -0700854 copy_prop("ext4_share_dup_blocks", "ext4_share_dup_blocks")
Patrick Tjin3f5f9932018-03-23 11:36:43 -0700855 if not copy_prop("oem_extfs_rsv_pct", "extfs_rsv_pct"):
856 d["extfs_rsv_pct"] = "0"
Daniel Norman72c626f2019-05-13 15:58:14 -0700857 copy_prop("oem_selinux_fc", "selinux_fc")
David Zeuthen4014a9d2016-09-30 17:29:22 -0400858 d["partition_name"] = mount_point
Ying Wangbd93d422011-10-28 17:02:30 -0700859 return d
860
861
862def LoadGlobalDict(filename):
863 """Load "name=value" pairs from filename"""
864 d = {}
865 f = open(filename)
866 for line in f:
867 line = line.strip()
868 if not line or line.startswith("#"):
869 continue
870 k, v = line.split("=", 1)
871 d[k] = v
872 f.close()
873 return d
874
875
Yifan Hongbbcba1e2018-06-18 16:32:35 -0700876def GlobalDictFromImageProp(image_prop, mount_point):
877 d = {}
878 def copy_prop(src_p, dest_p):
879 if src_p in image_prop:
880 d[dest_p] = image_prop[src_p]
881 return True
882 return False
Tao Bao4251fe92018-07-23 13:05:00 -0700883
Yifan Hongbbcba1e2018-06-18 16:32:35 -0700884 if mount_point == "system":
Tao Bao35f4ebc2018-09-27 15:31:11 -0700885 copy_prop("partition_size", "system_size")
Yifan Hongbbcba1e2018-06-18 16:32:35 -0700886 elif mount_point == "system_other":
Bowgo Tsai867ab662019-01-29 13:30:18 +0800887 copy_prop("partition_size", "system_other_size")
Yifan Hong749062d2018-06-19 16:23:16 -0700888 elif mount_point == "vendor":
Tao Bao35f4ebc2018-09-27 15:31:11 -0700889 copy_prop("partition_size", "vendor_size")
Bowgo Tsaid624fa62017-11-14 23:42:30 +0800890 elif mount_point == "odm":
Tao Bao35f4ebc2018-09-27 15:31:11 -0700891 copy_prop("partition_size", "odm_size")
Yifan Hongcfb917a2020-05-07 14:58:20 -0700892 elif mount_point == "vendor_dlkm":
893 copy_prop("partition_size", "vendor_dlkm_size")
Yifan Hongf496f1b2020-07-15 16:52:59 -0700894 elif mount_point == "odm_dlkm":
895 copy_prop("partition_size", "odm_dlkm_size")
Yifan Hong56a6c3b2018-07-20 15:19:34 -0700896 elif mount_point == "product":
Tao Bao35f4ebc2018-09-27 15:31:11 -0700897 copy_prop("partition_size", "product_size")
Justin Yun6151e3f2019-06-25 15:58:13 +0900898 elif mount_point == "system_ext":
899 copy_prop("partition_size", "system_ext_size")
Yifan Hongbbcba1e2018-06-18 16:32:35 -0700900 return d
901
902
Ying Wangbd93d422011-10-28 17:02:30 -0700903def main(argv):
Yifan Hong8c3dce02019-04-09 17:03:57 +0000904 if len(argv) != 4:
Tao Baoc72727a2017-12-07 10:33:00 -0800905 print(__doc__)
Ying Wangbd93d422011-10-28 17:02:30 -0700906 sys.exit(1)
907
Tao Bao32fcdab2018-10-12 10:30:39 -0700908 common.InitLogging()
909
Ying Wangbd93d422011-10-28 17:02:30 -0700910 in_dir = argv[0]
911 glob_dict_file = argv[1]
912 out_file = argv[2]
Thierry Strudel74a81e62015-07-09 09:54:55 -0700913 target_out = argv[3]
Ying Wangbd93d422011-10-28 17:02:30 -0700914
915 glob_dict = LoadGlobalDict(glob_dict_file)
Ying Wangae61f502015-03-12 18:30:39 -0700916 if "mount_point" in glob_dict:
Mark Salyzyn780f5952018-10-19 13:44:36 -0700917 # The caller knows the mount point and provides a dictionary needed by
Tao Baoc7a6f1e2015-06-23 11:16:05 -0700918 # BuildImage().
Ying Wangae61f502015-03-12 18:30:39 -0700919 image_properties = glob_dict
Ying Wang9f8e8db2011-11-04 11:37:01 -0700920 else:
Ying Wangae61f502015-03-12 18:30:39 -0700921 image_filename = os.path.basename(out_file)
922 mount_point = ""
923 if image_filename == "system.img":
924 mount_point = "system"
Alex Light4e358ab2016-06-16 14:47:10 -0700925 elif image_filename == "system_other.img":
926 mount_point = "system_other"
Ying Wangae61f502015-03-12 18:30:39 -0700927 elif image_filename == "userdata.img":
928 mount_point = "data"
929 elif image_filename == "cache.img":
930 mount_point = "cache"
931 elif image_filename == "vendor.img":
932 mount_point = "vendor"
Bowgo Tsaid624fa62017-11-14 23:42:30 +0800933 elif image_filename == "odm.img":
934 mount_point = "odm"
Yifan Hongcfb917a2020-05-07 14:58:20 -0700935 elif image_filename == "vendor_dlkm.img":
936 mount_point = "vendor_dlkm"
Yifan Hongf496f1b2020-07-15 16:52:59 -0700937 elif image_filename == "odm_dlkm.img":
938 mount_point = "odm_dlkm"
Ying Wangae61f502015-03-12 18:30:39 -0700939 elif image_filename == "oem.img":
940 mount_point = "oem"
Jaekyun Seokb7735d82017-11-27 17:04:47 +0900941 elif image_filename == "product.img":
942 mount_point = "product"
Justin Yun6151e3f2019-06-25 15:58:13 +0900943 elif image_filename == "system_ext.img":
944 mount_point = "system_ext"
Ying Wangae61f502015-03-12 18:30:39 -0700945 else:
Tao Bao32fcdab2018-10-12 10:30:39 -0700946 logger.error("Unknown image file name %s", image_filename)
Tao Bao1c830bf2017-12-25 10:43:47 -0800947 sys.exit(1)
Ying Wangbd93d422011-10-28 17:02:30 -0700948
Ying Wangae61f502015-03-12 18:30:39 -0700949 image_properties = ImagePropFromGlobalDict(glob_dict, mount_point)
950
Tao Baoc6bd70a2018-09-27 16:58:00 -0700951 try:
952 BuildImage(in_dir, image_properties, out_file, target_out)
953 except:
Tao Bao32fcdab2018-10-12 10:30:39 -0700954 logger.error("Failed to build %s from %s", out_file, in_dir)
Tao Baoc6bd70a2018-09-27 16:58:00 -0700955 raise
Ying Wangbd93d422011-10-28 17:02:30 -0700956
Tao Bao32fcdab2018-10-12 10:30:39 -0700957
Ying Wangbd93d422011-10-28 17:02:30 -0700958if __name__ == '__main__':
Tao Bao1c830bf2017-12-25 10:43:47 -0800959 try:
960 main(sys.argv[1:])
961 finally:
962 common.Cleanup()