blob: f1594d73223cf3b7794c6114605b34f38e52ff80 [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
Yifan Hongbbcba1e2018-06-18 16:32:35 -070021If argument generated_prop_file exists, write additional properties to the file.
22
Tao Baoc72727a2017-12-07 10:33:00 -080023Usage: build_image.py input_directory properties_file output_image \\
Yifan Hongbbcba1e2018-06-18 16:32:35 -070024 target_output_directory [generated_prop_file]
Ying Wangbd93d422011-10-28 17:02:30 -070025"""
Tao Baoc72727a2017-12-07 10:33:00 -080026
27from __future__ import print_function
28
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
David Zeuthen4014a9d2016-09-30 17:29:22 -040032import shlex
Geremy Condrafd6f7512013-06-16 17:26:08 -070033import shutil
Tao Baoc72727a2017-12-07 10:33:00 -080034import subprocess
35import sys
36
37import common
Sami Tolvanen405e71d2016-02-09 12:28:58 -080038import sparse_img
Tao Baoc72727a2017-12-07 10:33:00 -080039
Ying Wangbd93d422011-10-28 17:02:30 -070040
Baligh Uddin601ddea2015-06-09 15:48:14 -070041OPTIONS = common.OPTIONS
42
Geremy Condrae8e982a2014-05-16 19:14:30 -070043FIXED_SALT = "aee087a5be3b982978c923f566a94613496b417f2af592639bc80d141e34dfe7"
Sami Tolvanenf99b5312015-05-20 07:30:57 +010044BLOCK_SIZE = 4096
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 RunCommand(cmd, verbose=None, env=None):
Tao Baoc7a6f1e2015-06-23 11:16:05 -070056 """Echo and run the given command.
Ying Wang69e9b4d2012-11-26 18:10:23 -080057
58 Args:
59 cmd: the command represented as a list of strings.
Tianjie Xu149b7fb2017-09-01 15:36:08 -070060 verbose: show commands being executed.
Yifan Hongbbcba1e2018-06-18 16:32:35 -070061 env: a dictionary of additional environment variables.
Ying Wang69e9b4d2012-11-26 18:10:23 -080062 Returns:
Tao Baoc7a6f1e2015-06-23 11:16:05 -070063 A tuple of the output and the exit code.
Ying Wang69e9b4d2012-11-26 18:10:23 -080064 """
Yifan Hongbbcba1e2018-06-18 16:32:35 -070065 env_copy = None
66 if env is not None:
67 env_copy = os.environ.copy()
68 env_copy.update(env)
Tianjie Xu149b7fb2017-09-01 15:36:08 -070069 if verbose is None:
70 verbose = OPTIONS.verbose
71 if verbose:
72 print("Running: " + " ".join(cmd))
Yifan Hongbbcba1e2018-06-18 16:32:35 -070073 p = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.STDOUT,
74 env=env_copy)
Tao Baoc7a6f1e2015-06-23 11:16:05 -070075 output, _ = p.communicate()
Tianjie Xu149b7fb2017-09-01 15:36:08 -070076
77 if verbose:
78 print(output.rstrip())
Tao Baoc7a6f1e2015-06-23 11:16:05 -070079 return (output, p.returncode)
Ying Wangbd93d422011-10-28 17:02:30 -070080
Tao Baoc72727a2017-12-07 10:33:00 -080081
Sami Tolvanenf99b5312015-05-20 07:30:57 +010082def GetVerityFECSize(partition_size):
Tianjie Xue3ad41b2017-03-08 11:05:56 -080083 cmd = ["fec", "-s", str(partition_size)]
Tianjie Xu149b7fb2017-09-01 15:36:08 -070084 output, exit_code = RunCommand(cmd, False)
Tianjie Xue3ad41b2017-03-08 11:05:56 -080085 if exit_code != 0:
Tao Baoc6bd70a2018-09-27 16:58:00 -070086 raise BuildImageError("Failed to GetVerityFECSize:\n{}".format(output))
87 return int(output)
Sami Tolvanenf99b5312015-05-20 07:30:57 +010088
Tao Baoc72727a2017-12-07 10:33:00 -080089
Geremy Condrafd6f7512013-06-16 17:26:08 -070090def GetVerityTreeSize(partition_size):
Tianjie Xue3ad41b2017-03-08 11:05:56 -080091 cmd = ["build_verity_tree", "-s", str(partition_size)]
Tianjie Xu149b7fb2017-09-01 15:36:08 -070092 output, exit_code = RunCommand(cmd, False)
Tianjie Xue3ad41b2017-03-08 11:05:56 -080093 if exit_code != 0:
Tao Baoc6bd70a2018-09-27 16:58:00 -070094 raise BuildImageError("Failed to GetVerityTreeSize:\n{}".format(output))
95 return int(output)
Geremy Condrafd6f7512013-06-16 17:26:08 -070096
Tao Baoc72727a2017-12-07 10:33:00 -080097
Geremy Condrafd6f7512013-06-16 17:26:08 -070098def GetVerityMetadataSize(partition_size):
Tao Baob4ec6d72018-03-15 23:21:28 -070099 cmd = ["build_verity_metadata.py", "size", str(partition_size)]
Tianjie Xu149b7fb2017-09-01 15:36:08 -0700100 output, exit_code = RunCommand(cmd, False)
Tianjie Xue3ad41b2017-03-08 11:05:56 -0800101 if exit_code != 0:
Tao Baoc6bd70a2018-09-27 16:58:00 -0700102 raise BuildImageError("Failed to GetVerityMetadataSize:\n{}".format(output))
103 return int(output)
Geremy Condrafd6f7512013-06-16 17:26:08 -0700104
Tao Baoc72727a2017-12-07 10:33:00 -0800105
Sami Tolvanenf99b5312015-05-20 07:30:57 +0100106def GetVeritySize(partition_size, fec_supported):
Tao Baoc6bd70a2018-09-27 16:58:00 -0700107 verity_tree_size = GetVerityTreeSize(partition_size)
108 verity_metadata_size = GetVerityMetadataSize(partition_size)
Sami Tolvanenf99b5312015-05-20 07:30:57 +0100109 verity_size = verity_tree_size + verity_metadata_size
110 if fec_supported:
Tao Baoc6bd70a2018-09-27 16:58:00 -0700111 fec_size = GetVerityFECSize(partition_size + verity_size)
Sami Tolvanenf99b5312015-05-20 07:30:57 +0100112 return verity_size + fec_size
113 return verity_size
114
Tao Baoc72727a2017-12-07 10:33:00 -0800115
Yifan Hongbbcba1e2018-06-18 16:32:35 -0700116def GetDiskUsage(path):
Tao Baoc6bd70a2018-09-27 16:58:00 -0700117 """Returns the number of bytes that "path" occupies on host.
Yifan Hongbbcba1e2018-06-18 16:32:35 -0700118
119 Args:
120 path: The directory or file to calculate size on
Tao Baoc6bd70a2018-09-27 16:58:00 -0700121
Yifan Hongbbcba1e2018-06-18 16:32:35 -0700122 Returns:
Tao Baoc6bd70a2018-09-27 16:58:00 -0700123 The number of bytes.
124
125 Raises:
126 BuildImageError: On error.
Yifan Hongbbcba1e2018-06-18 16:32:35 -0700127 """
128 env = {"POSIXLY_CORRECT": "1"}
129 cmd = ["du", "-s", path]
130 output, exit_code = RunCommand(cmd, verbose=False, env=env)
131 if exit_code != 0:
Tao Baoc6bd70a2018-09-27 16:58:00 -0700132 raise BuildImageError("Failed to get disk usage:\n{}".format(output))
Yifan Hongbbcba1e2018-06-18 16:32:35 -0700133 # POSIX du returns number of blocks with block size 512
Tao Baoc6bd70a2018-09-27 16:58:00 -0700134 return int(output.split()[0]) * 512
Yifan Hongbbcba1e2018-06-18 16:32:35 -0700135
136
Sami Tolvanen405e71d2016-02-09 12:28:58 -0800137def GetSimgSize(image_file):
138 simg = sparse_img.SparseImage(image_file, build_map=False)
139 return simg.blocksize * simg.total_blocks
140
Tao Baoc72727a2017-12-07 10:33:00 -0800141
Sami Tolvanen405e71d2016-02-09 12:28:58 -0800142def ZeroPadSimg(image_file, pad_size):
143 blocks = pad_size // BLOCK_SIZE
144 print("Padding %d blocks (%d bytes)" % (blocks, pad_size))
145 simg = sparse_img.SparseImage(image_file, mode="r+b", build_map=False)
146 simg.AppendFillChunk(0, blocks)
147
Tao Baoc72727a2017-12-07 10:33:00 -0800148
Bowgo Tsai7ea994b2017-05-19 23:44:26 +0800149def AVBCalcMaxImageSize(avbtool, footer_type, partition_size, additional_args):
David Zeuthen4014a9d2016-09-30 17:29:22 -0400150 """Calculates max image size for a given partition size.
151
152 Args:
153 avbtool: String with path to avbtool.
Bowgo Tsai7ea994b2017-05-19 23:44:26 +0800154 footer_type: 'hash' or 'hashtree' for generating footer.
David Zeuthen4014a9d2016-09-30 17:29:22 -0400155 partition_size: The size of the partition in question.
Bowgo Tsai040410c2018-09-20 16:40:01 +0800156 additional_args: Additional arguments to pass to "avbtool add_hash_footer"
157 or "avbtool add_hashtree_footer".
158
David Zeuthen4014a9d2016-09-30 17:29:22 -0400159 Returns:
Tao Baoc6bd70a2018-09-27 16:58:00 -0700160 The maximum image size.
161
162 Raises:
163 BuildImageError: On error or getting invalid image size.
David Zeuthen4014a9d2016-09-30 17:29:22 -0400164 """
Tao Baoc72727a2017-12-07 10:33:00 -0800165 cmd = [avbtool, "add_%s_footer" % footer_type,
Bowgo Tsai040410c2018-09-20 16:40:01 +0800166 "--partition_size", str(partition_size), "--calc_max_image_size"]
Bowgo Tsai3e599ea2017-05-26 18:30:04 +0800167 cmd.extend(shlex.split(additional_args))
168
Tao Baoc6bd70a2018-09-27 16:58:00 -0700169 output, exit_code = RunCommand(cmd)
David Zeuthen4014a9d2016-09-30 17:29:22 -0400170 if exit_code != 0:
Tao Baoc6bd70a2018-09-27 16:58:00 -0700171 raise BuildImageError(
172 "Failed to calculate max image size:\n{}".format(output))
173 image_size = int(output)
174 if image_size <= 0:
175 raise BuildImageError(
176 "Invalid max image size: {}".format(output))
177 return image_size
David Zeuthen4014a9d2016-09-30 17:29:22 -0400178
Tao Baoc72727a2017-12-07 10:33:00 -0800179
Bowgo Tsai040410c2018-09-20 16:40:01 +0800180def AVBCalcMinPartitionSize(image_size, size_calculator):
181 """Calculates min partition size for a given image size.
182
183 Args:
184 image_size: The size of the image in question.
185 size_calculator: The function to calculate max image size
186 for a given partition size.
187
188 Returns:
189 The minimum partition size required to accommodate the image size.
190 """
191 # Use image size as partition size to approximate final partition size.
192 image_ratio = size_calculator(image_size) / float(image_size)
193
194 # Prepare a binary search for the optimal partition size.
195 lo = int(image_size / image_ratio) // BLOCK_SIZE * BLOCK_SIZE - BLOCK_SIZE
196
197 # Ensure lo is small enough: max_image_size should <= image_size.
198 delta = BLOCK_SIZE
199 max_image_size = size_calculator(lo)
200 while max_image_size > image_size:
201 image_ratio = max_image_size / float(lo)
202 lo = int(image_size / image_ratio) // BLOCK_SIZE * BLOCK_SIZE - delta
203 delta *= 2
204 max_image_size = size_calculator(lo)
205
206 hi = lo + BLOCK_SIZE
207
208 # Ensure hi is large enough: max_image_size should >= image_size.
209 delta = BLOCK_SIZE
210 max_image_size = size_calculator(hi)
211 while max_image_size < image_size:
212 image_ratio = max_image_size / float(hi)
213 hi = int(image_size / image_ratio) // BLOCK_SIZE * BLOCK_SIZE + delta
214 delta *= 2
215 max_image_size = size_calculator(hi)
216
217 partition_size = hi
218
219 # Start to binary search.
220 while lo < hi:
221 mid = ((lo + hi) // (2 * BLOCK_SIZE)) * BLOCK_SIZE
222 max_image_size = size_calculator(mid)
223 if max_image_size >= image_size: # if mid can accommodate image_size
224 if mid < partition_size: # if a smaller partition size is found
225 partition_size = mid
226 hi = mid
227 else:
228 lo = mid + BLOCK_SIZE
229
230 if OPTIONS.verbose:
231 print("AVBCalcMinPartitionSize({}): partition_size: {}.".format(
232 image_size, partition_size))
233
234 return partition_size
235
236
Bowgo Tsai7ea994b2017-05-19 23:44:26 +0800237def AVBAddFooter(image_path, avbtool, footer_type, partition_size,
Tao Bao2b6dfd62017-09-27 17:17:43 -0700238 partition_name, key_path, algorithm, salt,
Bowgo Tsai3e599ea2017-05-26 18:30:04 +0800239 additional_args):
David Zeuthen4014a9d2016-09-30 17:29:22 -0400240 """Adds dm-verity hashtree and AVB metadata to an image.
241
242 Args:
243 image_path: Path to image to modify.
244 avbtool: String with path to avbtool.
Bowgo Tsai7ea994b2017-05-19 23:44:26 +0800245 footer_type: 'hash' or 'hashtree' for generating footer.
David Zeuthen4014a9d2016-09-30 17:29:22 -0400246 partition_size: The size of the partition in question.
247 partition_name: The name of the partition - will be embedded in metadata.
Bowgo Tsai3e599ea2017-05-26 18:30:04 +0800248 key_path: Path to key to use or None.
249 algorithm: Name of algorithm to use or None.
Tao Bao2b6dfd62017-09-27 17:17:43 -0700250 salt: The salt to use (a hexadecimal string) or None.
Bowgo Tsai040410c2018-09-20 16:40:01 +0800251 additional_args: Additional arguments to pass to "avbtool add_hash_footer"
252 or "avbtool add_hashtree_footer".
Tao Baoc72727a2017-12-07 10:33:00 -0800253
Tao Baoc6bd70a2018-09-27 16:58:00 -0700254 Raises:
255 BuildImageError: On error.
David Zeuthen4014a9d2016-09-30 17:29:22 -0400256 """
Tao Baoc72727a2017-12-07 10:33:00 -0800257 cmd = [avbtool, "add_%s_footer" % footer_type,
258 "--partition_size", partition_size,
259 "--partition_name", partition_name,
260 "--image", image_path]
Bowgo Tsai3e599ea2017-05-26 18:30:04 +0800261
262 if key_path and algorithm:
263 cmd.extend(["--key", key_path, "--algorithm", algorithm])
Tao Bao2b6dfd62017-09-27 17:17:43 -0700264 if salt:
265 cmd.extend(["--salt", salt])
Bowgo Tsai3e599ea2017-05-26 18:30:04 +0800266
267 cmd.extend(shlex.split(additional_args))
268
Bowgo Tsai99ed1b42018-09-04 17:31:07 +0800269 output, exit_code = RunCommand(cmd)
270 if exit_code != 0:
Tao Baoc6bd70a2018-09-27 16:58:00 -0700271 raise BuildImageError(
272 "Failed to add AVB footer:\n{}".format(output))
David Zeuthen4014a9d2016-09-30 17:29:22 -0400273
Tao Baoc72727a2017-12-07 10:33:00 -0800274
Sami Tolvanenf99b5312015-05-20 07:30:57 +0100275def AdjustPartitionSizeForVerity(partition_size, fec_supported):
Geremy Condrafd6f7512013-06-16 17:26:08 -0700276 """Modifies the provided partition size to account for the verity metadata.
277
278 This information is used to size the created image appropriately.
Tao Baoc72727a2017-12-07 10:33:00 -0800279
Geremy Condrafd6f7512013-06-16 17:26:08 -0700280 Args:
281 partition_size: the size of the partition to be verified.
Tao Baoc72727a2017-12-07 10:33:00 -0800282
Geremy Condrafd6f7512013-06-16 17:26:08 -0700283 Returns:
Sami Tolvanen433905f2016-09-01 15:58:35 -0700284 A tuple of the size of the partition adjusted for verity metadata, and
285 the size of verity metadata.
Geremy Condrafd6f7512013-06-16 17:26:08 -0700286 """
Sami Tolvanenf99b5312015-05-20 07:30:57 +0100287 key = "%d %d" % (partition_size, fec_supported)
288 if key in AdjustPartitionSizeForVerity.results:
289 return AdjustPartitionSizeForVerity.results[key]
290
291 hi = partition_size
292 if hi % BLOCK_SIZE != 0:
293 hi = (hi // BLOCK_SIZE) * BLOCK_SIZE
294
295 # verity tree and fec sizes depend on the partition size, which
296 # means this estimate is always going to be unnecessarily small
Sami Tolvanen433905f2016-09-01 15:58:35 -0700297 verity_size = GetVeritySize(hi, fec_supported)
298 lo = partition_size - verity_size
Sami Tolvanenf99b5312015-05-20 07:30:57 +0100299 result = lo
300
301 # do a binary search for the optimal size
302 while lo < hi:
303 i = ((lo + hi) // (2 * BLOCK_SIZE)) * BLOCK_SIZE
Sami Tolvanen433905f2016-09-01 15:58:35 -0700304 v = GetVeritySize(i, fec_supported)
305 if i + v <= partition_size:
Sami Tolvanenf99b5312015-05-20 07:30:57 +0100306 if result < i:
307 result = i
Sami Tolvanen433905f2016-09-01 15:58:35 -0700308 verity_size = v
Sami Tolvanenf99b5312015-05-20 07:30:57 +0100309 lo = i + BLOCK_SIZE
310 else:
311 hi = i
312
Tomasz Wasilczyk29ec06b2017-11-15 10:34:01 -0800313 if OPTIONS.verbose:
314 print("Adjusted partition size for verity, partition_size: {},"
315 " verity_size: {}".format(result, verity_size))
Sami Tolvanen433905f2016-09-01 15:58:35 -0700316 AdjustPartitionSizeForVerity.results[key] = (result, verity_size)
317 return (result, verity_size)
Sami Tolvanenf99b5312015-05-20 07:30:57 +0100318
Tao Baoc72727a2017-12-07 10:33:00 -0800319
Sami Tolvanenf99b5312015-05-20 07:30:57 +0100320AdjustPartitionSizeForVerity.results = {}
321
Tao Baoc72727a2017-12-07 10:33:00 -0800322
Sami Tolvanen433905f2016-09-01 15:58:35 -0700323def BuildVerityFEC(sparse_image_path, verity_path, verity_fec_path,
324 padding_size):
Tianjie Xue3ad41b2017-03-08 11:05:56 -0800325 cmd = ["fec", "-e", "-p", str(padding_size), sparse_image_path,
326 verity_path, verity_fec_path]
327 output, exit_code = RunCommand(cmd)
328 if exit_code != 0:
Tao Baoc6bd70a2018-09-27 16:58:00 -0700329 raise BuildImageError(
330 "Failed to build FEC data:\n{}".format(output))
Geremy Condrafd6f7512013-06-16 17:26:08 -0700331
Tao Baoc72727a2017-12-07 10:33:00 -0800332
Colin Cross477cf2b2014-04-16 18:49:56 -0700333def BuildVerityTree(sparse_image_path, verity_image_path, prop_dict):
Tianjie Xue3ad41b2017-03-08 11:05:56 -0800334 cmd = ["build_verity_tree", "-A", FIXED_SALT, sparse_image_path,
335 verity_image_path]
336 output, exit_code = RunCommand(cmd)
337 if exit_code != 0:
Tao Baoc6bd70a2018-09-27 16:58:00 -0700338 raise BuildImageError(
339 "Failed to build verity tree:\n{}".format(output))
Geremy Condrafd6f7512013-06-16 17:26:08 -0700340 root, salt = output.split()
341 prop_dict["verity_root_hash"] = root
342 prop_dict["verity_salt"] = salt
Geremy Condrafd6f7512013-06-16 17:26:08 -0700343
Tao Baoc72727a2017-12-07 10:33:00 -0800344
Geremy Condrafd6f7512013-06-16 17:26:08 -0700345def BuildVerityMetadata(image_size, verity_metadata_path, root_hash, salt,
Bowgo Tsai6ceeb1a2017-10-11 16:21:48 +0800346 block_device, signer_path, key, signer_args,
347 verity_disable):
Tao Baob4ec6d72018-03-15 23:21:28 -0700348 cmd = ["build_verity_metadata.py", "build", str(image_size),
349 verity_metadata_path, root_hash, salt, block_device, signer_path, key]
Tao Bao45810422016-10-17 16:20:12 -0700350 if signer_args:
Tianjie Xue3ad41b2017-03-08 11:05:56 -0800351 cmd.append("--signer_args=\"%s\"" % (' '.join(signer_args),))
Bowgo Tsai6ceeb1a2017-10-11 16:21:48 +0800352 if verity_disable:
353 cmd.append("--verity_disable")
Tianjie Xue3ad41b2017-03-08 11:05:56 -0800354 output, exit_code = RunCommand(cmd)
355 if exit_code != 0:
Tao Baoc6bd70a2018-09-27 16:58:00 -0700356 raise BuildImageError(
357 "Failed to build verity metadata:\n{}".format(output))
Geremy Condrafd6f7512013-06-16 17:26:08 -0700358
Tao Baoc72727a2017-12-07 10:33:00 -0800359
Geremy Condrafd6f7512013-06-16 17:26:08 -0700360def Append2Simg(sparse_image_path, unsparse_image_path, error_message):
361 """Appends the unsparse image to the given sparse image.
362
363 Args:
364 sparse_image_path: the path to the (sparse) image
365 unsparse_image_path: the path to the (unsparse) image
Tao Baoc6bd70a2018-09-27 16:58:00 -0700366
367 Raises:
368 BuildImageError: On error.
Geremy Condrafd6f7512013-06-16 17:26:08 -0700369 """
Tianjie Xue3ad41b2017-03-08 11:05:56 -0800370 cmd = ["append2simg", sparse_image_path, unsparse_image_path]
371 output, exit_code = RunCommand(cmd)
372 if exit_code != 0:
Tao Baoc6bd70a2018-09-27 16:58:00 -0700373 raise BuildImageError("{}:\n{}".format(error_message, output))
Geremy Condrafd6f7512013-06-16 17:26:08 -0700374
Tao Baoc72727a2017-12-07 10:33:00 -0800375
Sami Tolvanenff914f52015-12-18 13:24:56 +0000376def Append(target, file_to_append, error_message):
Tao Baoc6bd70a2018-09-27 16:58:00 -0700377 """Appends file_to_append to target.
378
379 Raises:
380 BuildImageError: On error.
381 """
Tao Baoc72727a2017-12-07 10:33:00 -0800382 try:
383 with open(target, "a") as out_file, open(file_to_append, "r") as input_file:
Tianjie Xue3ad41b2017-03-08 11:05:56 -0800384 for line in input_file:
385 out_file.write(line)
Tao Baoc72727a2017-12-07 10:33:00 -0800386 except IOError:
Tao Baoc6bd70a2018-09-27 16:58:00 -0700387 raise BuildImageError(error_message)
Sami Tolvanenff914f52015-12-18 13:24:56 +0000388
Tao Baoc72727a2017-12-07 10:33:00 -0800389
Dan Albert8b72aef2015-03-23 19:13:21 -0700390def BuildVerifiedImage(data_image_path, verity_image_path,
Sami Tolvanen4a060042015-12-18 15:50:25 +0000391 verity_metadata_path, verity_fec_path,
Sami Tolvanen433905f2016-09-01 15:58:35 -0700392 padding_size, fec_supported):
Tao Baoc6bd70a2018-09-27 16:58:00 -0700393 Append(
394 verity_image_path, verity_metadata_path,
395 "Could not append verity metadata!")
Sami Tolvanen4a060042015-12-18 15:50:25 +0000396
397 if fec_supported:
Tao Baoc6bd70a2018-09-27 16:58:00 -0700398 # Build FEC for the entire partition, including metadata.
399 BuildVerityFEC(
400 data_image_path, verity_image_path, verity_fec_path, padding_size)
401 Append(verity_image_path, verity_fec_path, "Could not append FEC!")
Sami Tolvanen4a060042015-12-18 15:50:25 +0000402
Tao Baoc6bd70a2018-09-27 16:58:00 -0700403 Append2Simg(
404 data_image_path, verity_image_path, "Could not append verity data!")
Geremy Condrafd6f7512013-06-16 17:26:08 -0700405
Tao Baoc72727a2017-12-07 10:33:00 -0800406
Geremy Condra6e8f53c2013-12-05 17:09:18 -0800407def UnsparseImage(sparse_image_path, replace=True):
Geremy Condrafd6f7512013-06-16 17:26:08 -0700408 img_dir = os.path.dirname(sparse_image_path)
409 unsparse_image_path = "unsparse_" + os.path.basename(sparse_image_path)
410 unsparse_image_path = os.path.join(img_dir, unsparse_image_path)
411 if os.path.exists(unsparse_image_path):
Geremy Condra6e8f53c2013-12-05 17:09:18 -0800412 if replace:
413 os.unlink(unsparse_image_path)
414 else:
Tao Baoc6bd70a2018-09-27 16:58:00 -0700415 return unsparse_image_path
Geremy Condrafd6f7512013-06-16 17:26:08 -0700416 inflate_command = ["simg2img", sparse_image_path, unsparse_image_path]
Tao Baoc6bd70a2018-09-27 16:58:00 -0700417 inflate_output, exit_code = RunCommand(inflate_command)
Geremy Condrafd6f7512013-06-16 17:26:08 -0700418 if exit_code != 0:
419 os.remove(unsparse_image_path)
Tao Baoc6bd70a2018-09-27 16:58:00 -0700420 raise BuildImageError(
421 "Error: '{}' failed with exit code {}:\n{}".format(
422 inflate_command, exit_code, inflate_output))
423 return unsparse_image_path
Geremy Condrafd6f7512013-06-16 17:26:08 -0700424
Tao Baoc72727a2017-12-07 10:33:00 -0800425
Sami Tolvanenf99b5312015-05-20 07:30:57 +0100426def MakeVerityEnabledImage(out_file, fec_supported, prop_dict):
Geremy Condrafd6f7512013-06-16 17:26:08 -0700427 """Creates an image that is verifiable using dm-verity.
428
429 Args:
430 out_file: the location to write the verifiable image at
Dan Albert8b72aef2015-03-23 19:13:21 -0700431 prop_dict: a dictionary of properties required for image creation and
432 verification
Tao Baoc6bd70a2018-09-27 16:58:00 -0700433
434 Raises:
435 AssertionError: On invalid partition sizes.
436 BuildImageError: On other errors.
Geremy Condrafd6f7512013-06-16 17:26:08 -0700437 """
438 # get properties
Tao Bao35f4ebc2018-09-27 15:31:11 -0700439 image_size = int(prop_dict["image_size"])
Geremy Condrafd6f7512013-06-16 17:26:08 -0700440 block_dev = prop_dict["verity_block_device"]
Paul Lawrencea37b2bb2014-11-13 17:54:30 -0800441 signer_key = prop_dict["verity_key"] + ".pk8"
Baligh Uddin601ddea2015-06-09 15:48:14 -0700442 if OPTIONS.verity_signer_path is not None:
Tao Bao45810422016-10-17 16:20:12 -0700443 signer_path = OPTIONS.verity_signer_path
Baligh Uddin601ddea2015-06-09 15:48:14 -0700444 else:
445 signer_path = prop_dict["verity_signer_cmd"]
Tao Bao45810422016-10-17 16:20:12 -0700446 signer_args = OPTIONS.verity_signer_args
Geremy Condrafd6f7512013-06-16 17:26:08 -0700447
Tao Bao1c830bf2017-12-25 10:43:47 -0800448 tempdir_name = common.MakeTempDir(suffix="_verity_images")
Geremy Condrafd6f7512013-06-16 17:26:08 -0700449
Tao Baoc6bd70a2018-09-27 16:58:00 -0700450 # Get partial image paths.
Geremy Condrafd6f7512013-06-16 17:26:08 -0700451 verity_image_path = os.path.join(tempdir_name, "verity.img")
452 verity_metadata_path = os.path.join(tempdir_name, "verity_metadata.img")
Sami Tolvanenf99b5312015-05-20 07:30:57 +0100453 verity_fec_path = os.path.join(tempdir_name, "verity_fec.img")
Geremy Condrafd6f7512013-06-16 17:26:08 -0700454
Tao Baoc6bd70a2018-09-27 16:58:00 -0700455 # Build the verity tree and get the root hash and salt.
456 BuildVerityTree(out_file, verity_image_path, prop_dict)
Geremy Condrafd6f7512013-06-16 17:26:08 -0700457
Tao Baoc6bd70a2018-09-27 16:58:00 -0700458 # Build the metadata blocks.
Geremy Condrafd6f7512013-06-16 17:26:08 -0700459 root_hash = prop_dict["verity_root_hash"]
460 salt = prop_dict["verity_salt"]
Bowgo Tsai6ceeb1a2017-10-11 16:21:48 +0800461 verity_disable = "verity_disable" in prop_dict
Tao Baoc6bd70a2018-09-27 16:58:00 -0700462 BuildVerityMetadata(
463 image_size, verity_metadata_path, root_hash, salt, block_dev, signer_path,
464 signer_key, signer_args, verity_disable)
Geremy Condrafd6f7512013-06-16 17:26:08 -0700465
Tao Baoc6bd70a2018-09-27 16:58:00 -0700466 # Build the full verified image.
Tao Bao35f4ebc2018-09-27 15:31:11 -0700467 partition_size = int(prop_dict["partition_size"])
Sami Tolvanen433905f2016-09-01 15:58:35 -0700468 verity_size = int(prop_dict["verity_size"])
469
Tao Bao35f4ebc2018-09-27 15:31:11 -0700470 padding_size = partition_size - image_size - verity_size
Sami Tolvanen433905f2016-09-01 15:58:35 -0700471 assert padding_size >= 0
472
Tao Baoc6bd70a2018-09-27 16:58:00 -0700473 BuildVerifiedImage(
474 out_file, verity_image_path, verity_metadata_path, verity_fec_path,
475 padding_size, fec_supported)
Geremy Condrafd6f7512013-06-16 17:26:08 -0700476
Tao Baoc72727a2017-12-07 10:33:00 -0800477
Mohamad Ayyashf8765552016-03-02 21:07:23 -0800478def ConvertBlockMapToBaseFs(block_map_file):
Tao Bao1c830bf2017-12-25 10:43:47 -0800479 base_fs_file = common.MakeTempFile(prefix="script_gen_", suffix=".base_fs")
Mohamad Ayyashf8765552016-03-02 21:07:23 -0800480 convert_command = ["blk_alloc_to_base_fs", block_map_file, base_fs_file]
Tao Baoc6bd70a2018-09-27 16:58:00 -0700481 output, exit_code = RunCommand(convert_command)
482 if exit_code != 0:
483 raise BuildImageError(
484 "Failed to call blk_alloc_to_base_fs:\n{}".format(output))
485 return base_fs_file
Mohamad Ayyashf8765552016-03-02 21:07:23 -0800486
Tao Baod4349f22017-12-07 23:01:25 -0800487
Tao Baoc2606eb2018-07-20 14:44:46 -0700488def SetUpInDirAndFsConfig(origin_in, prop_dict):
489 """Returns the in_dir and fs_config that should be used for image building.
490
Tom Cherryd14b8952018-08-09 14:26:00 -0700491 When building system.img for all targets, it creates and returns a staged dir
492 that combines the contents of /system (i.e. in the given in_dir) and root.
Tao Baoc2606eb2018-07-20 14:44:46 -0700493
494 Args:
495 origin_in: Path to the input directory.
496 prop_dict: A property dict that contains info like partition size. Values
497 may be updated.
498
499 Returns:
500 A tuple of in_dir and fs_config that should be used to build the image.
501 """
502 fs_config = prop_dict.get("fs_config")
Tom Cherryd14b8952018-08-09 14:26:00 -0700503
504 if prop_dict["mount_point"] == "system_other":
505 prop_dict["mount_point"] = "system"
506 return origin_in, fs_config
507
508 if prop_dict["mount_point"] != "system":
Tao Baoc2606eb2018-07-20 14:44:46 -0700509 return origin_in, fs_config
510
511 # Construct a staging directory of the root file system.
512 in_dir = common.MakeTempDir()
513 root_dir = prop_dict.get("root_dir")
514 if root_dir:
515 shutil.rmtree(in_dir)
516 shutil.copytree(root_dir, in_dir, symlinks=True)
517 in_dir_system = os.path.join(in_dir, "system")
518 shutil.rmtree(in_dir_system, ignore_errors=True)
519 shutil.copytree(origin_in, in_dir_system, symlinks=True)
520
521 # Change the mount point to "/".
522 prop_dict["mount_point"] = "/"
523 if fs_config:
524 # We need to merge the fs_config files of system and root.
525 merged_fs_config = common.MakeTempFile(
526 prefix="merged_fs_config", suffix=".txt")
527 with open(merged_fs_config, "w") as fw:
528 if "root_fs_config" in prop_dict:
529 with open(prop_dict["root_fs_config"]) as fr:
530 fw.writelines(fr.readlines())
531 with open(fs_config) as fr:
532 fw.writelines(fr.readlines())
533 fs_config = merged_fs_config
534 return in_dir, fs_config
535
536
Tao Baod4349f22017-12-07 23:01:25 -0800537def CheckHeadroom(ext4fs_output, prop_dict):
538 """Checks if there's enough headroom space available.
539
540 Headroom is the reserved space on system image (via PRODUCT_SYSTEM_HEADROOM),
541 which is useful for devices with low disk space that have system image
542 variation between builds. The 'partition_headroom' in prop_dict is the size
543 in bytes, while the numbers in 'ext4fs_output' are for 4K-blocks.
544
545 Args:
546 ext4fs_output: The output string from mke2fs command.
547 prop_dict: The property dict.
548
Tao Baod8a953d2018-01-02 21:19:27 -0800549 Raises:
550 AssertionError: On invalid input.
Tao Baoc6bd70a2018-09-27 16:58:00 -0700551 BuildImageError: On check failure.
Tao Baod4349f22017-12-07 23:01:25 -0800552 """
Tao Baod8a953d2018-01-02 21:19:27 -0800553 assert ext4fs_output is not None
554 assert prop_dict.get('fs_type', '').startswith('ext4')
555 assert 'partition_headroom' in prop_dict
556 assert 'mount_point' in prop_dict
557
Tao Baod4349f22017-12-07 23:01:25 -0800558 ext4fs_stats = re.compile(
559 r'Created filesystem with .* (?P<used_blocks>[0-9]+)/'
560 r'(?P<total_blocks>[0-9]+) blocks')
Tao Baoc72727a2017-12-07 10:33:00 -0800561 last_line = ext4fs_output.strip().split('\n')[-1]
562 m = ext4fs_stats.match(last_line)
Tao Baod4349f22017-12-07 23:01:25 -0800563 used_blocks = int(m.groupdict().get('used_blocks'))
564 total_blocks = int(m.groupdict().get('total_blocks'))
Tao Baod8a953d2018-01-02 21:19:27 -0800565 headroom_blocks = int(prop_dict['partition_headroom']) / BLOCK_SIZE
Tao Baod4349f22017-12-07 23:01:25 -0800566 adjusted_blocks = total_blocks - headroom_blocks
567 if used_blocks > adjusted_blocks:
Tao Baod8a953d2018-01-02 21:19:27 -0800568 mount_point = prop_dict["mount_point"]
Tao Baoc6bd70a2018-09-27 16:58:00 -0700569 raise BuildImageError(
570 "Error: Not enough room on {} (total: {} blocks, used: {} blocks, "
571 "headroom: {} blocks, available: {} blocks)".format(
572 mount_point, total_blocks, used_blocks, headroom_blocks,
573 adjusted_blocks))
Tao Baod4349f22017-12-07 23:01:25 -0800574
575
Thierry Strudel74a81e62015-07-09 09:54:55 -0700576def BuildImage(in_dir, prop_dict, out_file, target_out=None):
Tao Baoc2606eb2018-07-20 14:44:46 -0700577 """Builds an image for the files under in_dir and writes it to out_file.
578
Ying Wangbd93d422011-10-28 17:02:30 -0700579 Args:
Tao Baoc2606eb2018-07-20 14:44:46 -0700580 in_dir: Path to input directory.
581 prop_dict: A property dict that contains info like partition size. Values
582 will be updated with computed values.
583 out_file: The output image file.
584 target_out: Path to the TARGET_OUT directory as in Makefile. It actually
585 points to the /system directory under PRODUCT_OUT. fs_config (the one
586 under system/core/libcutils) reads device specific FS config files from
587 there.
Ying Wangbd93d422011-10-28 17:02:30 -0700588
Tao Baoc6bd70a2018-09-27 16:58:00 -0700589 Raises:
590 BuildImageError: On build image failures.
Ying Wangbd93d422011-10-28 17:02:30 -0700591 """
Tao Baoc2606eb2018-07-20 14:44:46 -0700592 in_dir, fs_config = SetUpInDirAndFsConfig(in_dir, prop_dict)
Ying Wanga2292c92015-03-24 19:07:40 -0700593
Ying Wangbd93d422011-10-28 17:02:30 -0700594 build_command = []
595 fs_type = prop_dict.get("fs_type", "")
Tao Baoc72727a2017-12-07 10:33:00 -0800596 run_e2fsck = False
Geremy Condrafd6f7512013-06-16 17:26:08 -0700597
Mohamad Ayyashdd063522015-03-24 12:42:03 -0700598 fs_spans_partition = True
599 if fs_type.startswith("squash"):
Tao Baoc7a6f1e2015-06-23 11:16:05 -0700600 fs_spans_partition = False
Mohamad Ayyashdd063522015-03-24 12:42:03 -0700601
Daniel Rosenbergf4eabc32014-07-10 15:42:38 -0700602 is_verity_partition = "verity_block_device" in prop_dict
Geremy Condra5b5f4952014-05-05 22:19:37 -0700603 verity_supported = prop_dict.get("verity") == "true"
Sami Tolvanenf99b5312015-05-20 07:30:57 +0100604 verity_fec_supported = prop_dict.get("verity_fec") == "true"
605
Bowgo Tsai040410c2018-09-20 16:40:01 +0800606 avb_footer_type = None
607 if prop_dict.get("avb_hash_enable") == "true":
608 avb_footer_type = "hash"
609 elif prop_dict.get("avb_hashtree_enable") == "true":
610 avb_footer_type = "hashtree"
611
612 if avb_footer_type:
613 avbtool = prop_dict.get("avb_avbtool")
614 avb_signing_args = prop_dict.get(
615 "avb_add_" + avb_footer_type + "_footer_args")
616
Yifan Hong2dae5722018-07-31 12:47:27 -0700617 if (prop_dict.get("use_dynamic_partition_size") == "true" and
Yifan Hongbbcba1e2018-06-18 16:32:35 -0700618 "partition_size" not in prop_dict):
Tao Baoc6bd70a2018-09-27 16:58:00 -0700619 # If partition_size is not defined, use output of `du' + reserved_size.
620 size = GetDiskUsage(in_dir)
Yifan Hongbbcba1e2018-06-18 16:32:35 -0700621 if OPTIONS.verbose:
Tao Baoc2606eb2018-07-20 14:44:46 -0700622 print("The tree size of %s is %d MB." % (in_dir, size // BYTES_IN_MB))
Yifan Hongbbcba1e2018-06-18 16:32:35 -0700623 size += int(prop_dict.get("partition_reserved_size", 0))
624 # Round this up to a multiple of 4K so that avbtool works
625 size = common.RoundUpTo4K(size)
Bowgo Tsai040410c2018-09-20 16:40:01 +0800626 # Adjust partition_size to add more space for AVB footer, to prevent
627 # it from consuming partition_reserved_size.
628 if avb_footer_type:
629 size = AVBCalcMinPartitionSize(
630 size,
631 lambda x: AVBCalcMaxImageSize(
632 avbtool, avb_footer_type, x, avb_signing_args))
Yifan Hongbbcba1e2018-06-18 16:32:35 -0700633 prop_dict["partition_size"] = str(size)
634 if OPTIONS.verbose:
635 print("Allocating %d MB for %s." % (size // BYTES_IN_MB, out_file))
636
Tao Bao35f4ebc2018-09-27 15:31:11 -0700637 prop_dict["image_size"] = prop_dict["partition_size"]
638
639 # Adjust the image size to make room for the hashes if this is to be verified.
Sami Tolvanen405e71d2016-02-09 12:28:58 -0800640 if verity_supported and is_verity_partition:
Geremy Condrafd6f7512013-06-16 17:26:08 -0700641 partition_size = int(prop_dict.get("partition_size"))
Tao Bao35f4ebc2018-09-27 15:31:11 -0700642 image_size, verity_size = AdjustPartitionSizeForVerity(
Tao Baoc72727a2017-12-07 10:33:00 -0800643 partition_size, verity_fec_supported)
Tao Bao35f4ebc2018-09-27 15:31:11 -0700644 prop_dict["image_size"] = str(image_size)
Sami Tolvanen433905f2016-09-01 15:58:35 -0700645 prop_dict["verity_size"] = str(verity_size)
Geremy Condrafd6f7512013-06-16 17:26:08 -0700646
Tao Bao35f4ebc2018-09-27 15:31:11 -0700647 # Adjust the image size for AVB hash footer or AVB hashtree footer.
Bowgo Tsai7ea994b2017-05-19 23:44:26 +0800648 if avb_footer_type:
Bowgo Tsai3e599ea2017-05-26 18:30:04 +0800649 partition_size = prop_dict["partition_size"]
Bowgo Tsai7ea994b2017-05-19 23:44:26 +0800650 # avb_add_hash_footer_args or avb_add_hashtree_footer_args.
Tao Baoc6bd70a2018-09-27 16:58:00 -0700651 max_image_size = AVBCalcMaxImageSize(
652 avbtool, avb_footer_type, partition_size, avb_signing_args)
Tao Bao35f4ebc2018-09-27 15:31:11 -0700653 prop_dict["image_size"] = str(max_image_size)
David Zeuthen4014a9d2016-09-30 17:29:22 -0400654
Ying Wangbd93d422011-10-28 17:02:30 -0700655 if fs_type.startswith("ext"):
Adrien Schildknecht9a072cc2016-11-18 17:06:29 -0800656 build_command = [prop_dict["ext_mkuserimg"]]
Ying Wangbd93d422011-10-28 17:02:30 -0700657 if "extfs_sparse_flag" in prop_dict:
658 build_command.append(prop_dict["extfs_sparse_flag"])
Tao Baoc72727a2017-12-07 10:33:00 -0800659 run_e2fsck = True
Ying Wangbd93d422011-10-28 17:02:30 -0700660 build_command.extend([in_dir, out_file, fs_type,
661 prop_dict["mount_point"]])
Tao Bao35f4ebc2018-09-27 15:31:11 -0700662 build_command.append(prop_dict["image_size"])
Ying Wangf3b86352014-11-18 18:03:13 -0800663 if "journal_size" in prop_dict:
664 build_command.extend(["-j", prop_dict["journal_size"]])
Doug Zongker850b8072013-12-05 15:54:55 -0800665 if "timestamp" in prop_dict:
666 build_command.extend(["-T", str(prop_dict["timestamp"])])
Ying Wanga2292c92015-03-24 19:07:40 -0700667 if fs_config:
Doug Zongker82822822014-06-16 09:10:55 -0700668 build_command.extend(["-C", fs_config])
Thierry Strudel74a81e62015-07-09 09:54:55 -0700669 if target_out:
670 build_command.extend(["-D", target_out])
Ying Wanga2292c92015-03-24 19:07:40 -0700671 if "block_list" in prop_dict:
672 build_command.extend(["-B", prop_dict["block_list"]])
Mohamad Ayyashf8765552016-03-02 21:07:23 -0800673 if "base_fs_file" in prop_dict:
674 base_fs_file = ConvertBlockMapToBaseFs(prop_dict["base_fs_file"])
Mohamad Ayyashf8765552016-03-02 21:07:23 -0800675 build_command.extend(["-d", base_fs_file])
Christoffer Dall8ed01f32014-12-17 21:34:12 +0100676 build_command.extend(["-L", prop_dict["mount_point"]])
Patrick Tjina1900842016-10-20 10:58:12 -0700677 if "extfs_inode_count" in prop_dict:
678 build_command.extend(["-i", prop_dict["extfs_inode_count"]])
Patrick Tjin3f5f9932018-03-23 11:36:43 -0700679 if "extfs_rsv_pct" in prop_dict:
680 build_command.extend(["-M", prop_dict["extfs_rsv_pct"]])
Connor O'Brien20f08c32017-01-05 16:48:14 -0800681 if "flash_erase_block_size" in prop_dict:
682 build_command.extend(["-e", prop_dict["flash_erase_block_size"]])
683 if "flash_logical_block_size" in prop_dict:
684 build_command.extend(["-o", prop_dict["flash_logical_block_size"]])
Tao Baod86e3112017-09-22 15:45:33 -0700685 # Specify UUID and hash_seed if using mke2fs.
Tianjie Xu57332222018-08-15 16:16:21 -0700686 if prop_dict["ext_mkuserimg"] == "mkuserimg_mke2fs":
Tao Baod86e3112017-09-22 15:45:33 -0700687 if "uuid" in prop_dict:
688 build_command.extend(["-U", prop_dict["uuid"]])
689 if "hash_seed" in prop_dict:
690 build_command.extend(["-S", prop_dict["hash_seed"]])
Jin Qianfde9f792018-01-22 13:15:46 -0800691 if "ext4_share_dup_blocks" in prop_dict:
692 build_command.append("-c")
Ying Wanga2292c92015-03-24 19:07:40 -0700693 if "selinux_fc" in prop_dict:
Kenny Rootf32dc712012-04-08 10:42:34 -0700694 build_command.append(prop_dict["selinux_fc"])
Mohamad Ayyashb97746e2015-03-03 12:30:37 -0800695 elif fs_type.startswith("squash"):
696 build_command = ["mksquashfsimage.sh"]
697 build_command.extend([in_dir, out_file])
Todd Poynorb2a555e2015-12-15 18:00:14 -0800698 if "squashfs_sparse_flag" in prop_dict:
699 build_command.extend([prop_dict["squashfs_sparse_flag"]])
Mohamad Ayyashb97746e2015-03-03 12:30:37 -0800700 build_command.extend(["-m", prop_dict["mount_point"]])
Thierry Strudel74a81e62015-07-09 09:54:55 -0700701 if target_out:
702 build_command.extend(["-d", target_out])
Mohamad Ayyash88378822016-04-07 22:10:51 -0700703 if fs_config:
704 build_command.extend(["-C", fs_config])
Ying Wanga2292c92015-03-24 19:07:40 -0700705 if "selinux_fc" in prop_dict:
Mohamad Ayyashb97746e2015-03-03 12:30:37 -0800706 build_command.extend(["-c", prop_dict["selinux_fc"]])
Mohamad Ayyashc3484f72016-06-13 09:46:58 -0700707 if "block_list" in prop_dict:
708 build_command.extend(["-B", prop_dict["block_list"]])
Ng Zhi An9446c1d2018-01-19 15:51:46 -0800709 if "squashfs_block_size" in prop_dict:
710 build_command.extend(["-b", prop_dict["squashfs_block_size"]])
Simon Wilsonf86e7ee2015-06-17 12:35:15 -0700711 if "squashfs_compressor" in prop_dict:
712 build_command.extend(["-z", prop_dict["squashfs_compressor"]])
713 if "squashfs_compressor_opt" in prop_dict:
714 build_command.extend(["-zo", prop_dict["squashfs_compressor_opt"]])
Tao Baoc72727a2017-12-07 10:33:00 -0800715 if prop_dict.get("squashfs_disable_4k_align") == "true":
Mohamad Ayyash1b6d3482016-06-15 15:53:07 -0700716 build_command.extend(["-a"])
JP Abgrall5bfed5a2014-06-16 14:17:40 -0700717 elif fs_type.startswith("f2fs"):
718 build_command = ["mkf2fsuserimg.sh"]
Tao Bao35f4ebc2018-09-27 15:31:11 -0700719 build_command.extend([out_file, prop_dict["image_size"]])
Jaegeuk Kim2ea1eba2017-11-28 19:21:28 -0800720 if fs_config:
721 build_command.extend(["-C", fs_config])
722 build_command.extend(["-f", in_dir])
723 if target_out:
724 build_command.extend(["-D", target_out])
725 if "selinux_fc" in prop_dict:
726 build_command.extend(["-s", prop_dict["selinux_fc"]])
727 build_command.extend(["-t", prop_dict["mount_point"]])
728 if "timestamp" in prop_dict:
729 build_command.extend(["-T", str(prop_dict["timestamp"])])
730 build_command.extend(["-L", prop_dict["mount_point"]])
Ying Wangbd93d422011-10-28 17:02:30 -0700731 else:
Tao Baoc6bd70a2018-09-27 16:58:00 -0700732 raise BuildImageError(
733 "Error: unknown filesystem type: {}".format(fs_type))
Ying Wangbd93d422011-10-28 17:02:30 -0700734
Tao Baoc6bd70a2018-09-27 16:58:00 -0700735 mkfs_output, exit_code = RunCommand(build_command)
Ying Wang69e9b4d2012-11-26 18:10:23 -0800736 if exit_code != 0:
Tao Baoc6bd70a2018-09-27 16:58:00 -0700737 try:
738 du = GetDiskUsage(in_dir)
739 du_str = "{} bytes ({} MB)".format(du, du // BYTES_IN_MB)
740 except BuildImageError as e:
741 print(e, file=sys.stderr)
742 du_str = "unknown"
Tao Bao4251fe92018-07-23 13:05:00 -0700743 print(
744 "Out of space? The tree size of {} is {}, with reserved space of {} "
745 "bytes ({} MB).".format(
Tao Baoc2606eb2018-07-20 14:44:46 -0700746 in_dir, du_str,
Tao Bao4251fe92018-07-23 13:05:00 -0700747 int(prop_dict.get("partition_reserved_size", 0)),
748 int(prop_dict.get("partition_reserved_size", 0)) // BYTES_IN_MB))
Tao Bao35f4ebc2018-09-27 15:31:11 -0700749 print(
750 "The max image size for filsystem files is {} bytes ({} MB), out of a "
751 "total partition size of {} bytes ({} MB).".format(
752 int(prop_dict["image_size"]),
753 int(prop_dict["image_size"]) // BYTES_IN_MB,
754 int(prop_dict["partition_size"]),
755 int(prop_dict["partition_size"]) // BYTES_IN_MB))
Tao Baoc6bd70a2018-09-27 16:58:00 -0700756
757 raise BuildImageError(
758 "Error: '{}' failed with exit code {}:\n{}".format(
759 build_command, exit_code, mkfs_output))
Ying Wang69e9b4d2012-11-26 18:10:23 -0800760
Tao Baod4349f22017-12-07 23:01:25 -0800761 # Check if there's enough headroom space available for ext4 image.
Tao Bao79d52f82017-12-07 14:07:44 -0800762 if "partition_headroom" in prop_dict and fs_type.startswith("ext4"):
Tao Baoc6bd70a2018-09-27 16:58:00 -0700763 CheckHeadroom(mkfs_output, prop_dict)
Tao Baoc7a6f1e2015-06-23 11:16:05 -0700764
Mohamad Ayyashdd063522015-03-24 12:42:03 -0700765 if not fs_spans_partition:
766 mount_point = prop_dict.get("mount_point")
Tao Bao35f4ebc2018-09-27 15:31:11 -0700767 image_size = int(prop_dict["image_size"])
768 sparse_image_size = GetSimgSize(out_file)
769 if sparse_image_size > image_size:
Tao Baoc6bd70a2018-09-27 16:58:00 -0700770 raise BuildImageError(
771 "Error: {} image size of {} is larger than partition size of "
772 "{}".format(mount_point, sparse_image_size, image_size))
Mohamad Ayyashdd063522015-03-24 12:42:03 -0700773 if verity_supported and is_verity_partition:
Tao Bao35f4ebc2018-09-27 15:31:11 -0700774 ZeroPadSimg(out_file, image_size - sparse_image_size)
Mohamad Ayyashdd063522015-03-24 12:42:03 -0700775
Tao Baoc72727a2017-12-07 10:33:00 -0800776 # Create the verified image if this is to be verified.
Geremy Condra5b5f4952014-05-05 22:19:37 -0700777 if verity_supported and is_verity_partition:
Tao Baoc6bd70a2018-09-27 16:58:00 -0700778 MakeVerityEnabledImage(out_file, verity_fec_supported, prop_dict)
Geremy Condrafd6f7512013-06-16 17:26:08 -0700779
Bowgo Tsai7ea994b2017-05-19 23:44:26 +0800780 # Add AVB HASH or HASHTREE footer (metadata).
781 if avb_footer_type:
Tao Bao35f4ebc2018-09-27 15:31:11 -0700782 partition_size = prop_dict["partition_size"]
David Zeuthen4014a9d2016-09-30 17:29:22 -0400783 partition_name = prop_dict["partition_name"]
Bowgo Tsai3e599ea2017-05-26 18:30:04 +0800784 # key_path and algorithm are only available when chain partition is used.
785 key_path = prop_dict.get("avb_key_path")
786 algorithm = prop_dict.get("avb_algorithm")
Tao Bao2b6dfd62017-09-27 17:17:43 -0700787 salt = prop_dict.get("avb_salt")
Tao Baoc6bd70a2018-09-27 16:58:00 -0700788 AVBAddFooter(
789 out_file, avbtool, avb_footer_type, partition_size, partition_name,
790 key_path, algorithm, salt, avb_signing_args)
David Zeuthen4014a9d2016-09-30 17:29:22 -0400791
Tao Baoc72727a2017-12-07 10:33:00 -0800792 if run_e2fsck and prop_dict.get("skip_fsck") != "true":
Tao Baoc6bd70a2018-09-27 16:58:00 -0700793 unsparse_image = UnsparseImage(out_file, replace=False)
Ying Wang69e9b4d2012-11-26 18:10:23 -0800794
795 # Run e2fsck on the inflated image file
796 e2fsck_command = ["e2fsck", "-f", "-n", unsparse_image]
Isaac Chenec7fa1c2018-08-02 14:02:56 +0800797 # TODO(b/112062612): work around e2fsck failure with SANITIZE_HOST=address
798 env4e2fsck = {"ASAN_OPTIONS": "detect_odr_violation=0"}
Tao Baoc6bd70a2018-09-27 16:58:00 -0700799 e2fsck_output, exit_code = RunCommand(e2fsck_command, env=env4e2fsck)
Ying Wang69e9b4d2012-11-26 18:10:23 -0800800
801 os.remove(unsparse_image)
802
Elliott Hughes73ff57f2017-12-06 12:16:39 -0800803 if exit_code != 0:
Tao Baoc6bd70a2018-09-27 16:58:00 -0700804 raise BuildImageError(
805 "Error: '{}' failed with exit code {}:\n{}".format(
806 e2fsck_command, exit_code, e2fsck_output))
Ying Wangbd93d422011-10-28 17:02:30 -0700807
808
809def ImagePropFromGlobalDict(glob_dict, mount_point):
810 """Build an image property dictionary from the global dictionary.
811
812 Args:
813 glob_dict: the global dictionary from the build system.
814 mount_point: such as "system", "data" etc.
815 """
Doug Zongker1ad7ade2013-12-06 11:53:27 -0800816 d = {}
Tao Bao052ae352015-09-28 13:44:13 -0700817
Tao Bao822f5842015-09-30 16:01:14 -0700818 if "build.prop" in glob_dict:
819 bp = glob_dict["build.prop"]
820 if "ro.build.date.utc" in bp:
821 d["timestamp"] = bp["ro.build.date.utc"]
Ying Wang9f8e8db2011-11-04 11:37:01 -0700822
823 def copy_prop(src_p, dest_p):
Patrick Tjin3f5f9932018-03-23 11:36:43 -0700824 """Copy a property from the global dictionary.
825
826 Args:
827 src_p: The source property in the global dictionary.
828 dest_p: The destination property.
829 Returns:
830 True if property was found and copied, False otherwise.
831 """
Ying Wang9f8e8db2011-11-04 11:37:01 -0700832 if src_p in glob_dict:
833 d[dest_p] = str(glob_dict[src_p])
Patrick Tjin3f5f9932018-03-23 11:36:43 -0700834 return True
835 return False
Ying Wang9f8e8db2011-11-04 11:37:01 -0700836
Ying Wangbd93d422011-10-28 17:02:30 -0700837 common_props = (
Ying Wangbd93d422011-10-28 17:02:30 -0700838 "extfs_sparse_flag",
Todd Poynorb2a555e2015-12-15 18:00:14 -0800839 "squashfs_sparse_flag",
Kenny Rootf32dc712012-04-08 10:42:34 -0700840 "selinux_fc",
Ying Wang6a42a252013-02-27 13:54:02 -0800841 "skip_fsck",
Adrien Schildknecht9a072cc2016-11-18 17:06:29 -0800842 "ext_mkuserimg",
Geremy Condrafd6f7512013-06-16 17:26:08 -0700843 "verity",
Geremy Condrafd6f7512013-06-16 17:26:08 -0700844 "verity_key",
Sami Tolvanenf99b5312015-05-20 07:30:57 +0100845 "verity_signer_cmd",
David Zeuthen4014a9d2016-09-30 17:29:22 -0400846 "verity_fec",
Bowgo Tsai6ceeb1a2017-10-11 16:21:48 +0800847 "verity_disable",
Bowgo Tsai3e599ea2017-05-26 18:30:04 +0800848 "avb_enable",
Tao Bao2b6dfd62017-09-27 17:17:43 -0700849 "avb_avbtool",
850 "avb_salt",
Yifan Hong2dae5722018-07-31 12:47:27 -0700851 "use_dynamic_partition_size",
Tao Bao2b6dfd62017-09-27 17:17:43 -0700852 )
Ying Wangbd93d422011-10-28 17:02:30 -0700853 for p in common_props:
Ying Wang9f8e8db2011-11-04 11:37:01 -0700854 copy_prop(p, p)
Ying Wangbd93d422011-10-28 17:02:30 -0700855
856 d["mount_point"] = mount_point
857 if mount_point == "system":
Bowgo Tsai3e599ea2017-05-26 18:30:04 +0800858 copy_prop("avb_system_hashtree_enable", "avb_hashtree_enable")
859 copy_prop("avb_system_add_hashtree_footer_args",
860 "avb_add_hashtree_footer_args")
861 copy_prop("avb_system_key_path", "avb_key_path")
862 copy_prop("avb_system_algorithm", "avb_algorithm")
Ying Wang9f8e8db2011-11-04 11:37:01 -0700863 copy_prop("fs_type", "fs_type")
Julius D'souza001c6762017-05-03 13:43:27 -0700864 # Copy the generic system fs type first, override with specific one if
Dan Albert8b72aef2015-03-23 19:13:21 -0700865 # available.
Mohamad Ayyashb97746e2015-03-03 12:30:37 -0800866 copy_prop("system_fs_type", "fs_type")
Julius D'souza001c6762017-05-03 13:43:27 -0700867 copy_prop("system_headroom", "partition_headroom")
Ying Wang9f8e8db2011-11-04 11:37:01 -0700868 copy_prop("system_size", "partition_size")
Tao Bao332a96b2018-03-31 10:27:35 -0700869 if not copy_prop("system_journal_size", "journal_size"):
870 d["journal_size"] = "0"
Daniel Rosenbergf4eabc32014-07-10 15:42:38 -0700871 copy_prop("system_verity_block_device", "verity_block_device")
Tao Baof3282b42015-04-01 11:21:55 -0700872 copy_prop("system_root_image", "system_root_image")
Tao Bao8bfd3c72018-07-20 15:20:28 -0700873 copy_prop("root_dir", "root_dir")
874 copy_prop("root_fs_config", "root_fs_config")
Jin Qianfde9f792018-01-22 13:15:46 -0800875 copy_prop("ext4_share_dup_blocks", "ext4_share_dup_blocks")
Simon Wilsonf86e7ee2015-06-17 12:35:15 -0700876 copy_prop("system_squashfs_compressor", "squashfs_compressor")
877 copy_prop("system_squashfs_compressor_opt", "squashfs_compressor_opt")
Mohamad Ayyashdfec8152016-05-24 12:59:30 -0700878 copy_prop("system_squashfs_block_size", "squashfs_block_size")
Mohamad Ayyash1b6d3482016-06-15 15:53:07 -0700879 copy_prop("system_squashfs_disable_4k_align", "squashfs_disable_4k_align")
Mohamad Ayyashf8765552016-03-02 21:07:23 -0800880 copy_prop("system_base_fs_file", "base_fs_file")
Patrick Tjina1900842016-10-20 10:58:12 -0700881 copy_prop("system_extfs_inode_count", "extfs_inode_count")
Patrick Tjin3f5f9932018-03-23 11:36:43 -0700882 if not copy_prop("system_extfs_rsv_pct", "extfs_rsv_pct"):
883 d["extfs_rsv_pct"] = "0"
Yifan Hongbbcba1e2018-06-18 16:32:35 -0700884 copy_prop("system_reserved_size", "partition_reserved_size")
Alex Light4e358ab2016-06-16 14:47:10 -0700885 elif mount_point == "system_other":
Tao Baoc72727a2017-12-07 10:33:00 -0800886 # We inherit the selinux policies of /system since we contain some of its
887 # files.
Bowgo Tsai3e599ea2017-05-26 18:30:04 +0800888 copy_prop("avb_system_hashtree_enable", "avb_hashtree_enable")
889 copy_prop("avb_system_add_hashtree_footer_args",
890 "avb_add_hashtree_footer_args")
891 copy_prop("avb_system_key_path", "avb_key_path")
892 copy_prop("avb_system_algorithm", "avb_algorithm")
Alex Light4e358ab2016-06-16 14:47:10 -0700893 copy_prop("fs_type", "fs_type")
894 copy_prop("system_fs_type", "fs_type")
895 copy_prop("system_size", "partition_size")
Tao Bao332a96b2018-03-31 10:27:35 -0700896 if not copy_prop("system_journal_size", "journal_size"):
897 d["journal_size"] = "0"
Alex Light4e358ab2016-06-16 14:47:10 -0700898 copy_prop("system_verity_block_device", "verity_block_device")
Alex Light4e358ab2016-06-16 14:47:10 -0700899 copy_prop("system_squashfs_compressor", "squashfs_compressor")
900 copy_prop("system_squashfs_compressor_opt", "squashfs_compressor_opt")
901 copy_prop("system_squashfs_block_size", "squashfs_block_size")
902 copy_prop("system_base_fs_file", "base_fs_file")
Patrick Tjina1900842016-10-20 10:58:12 -0700903 copy_prop("system_extfs_inode_count", "extfs_inode_count")
Patrick Tjin3f5f9932018-03-23 11:36:43 -0700904 if not copy_prop("system_extfs_rsv_pct", "extfs_rsv_pct"):
905 d["extfs_rsv_pct"] = "0"
Yifan Hongbbcba1e2018-06-18 16:32:35 -0700906 copy_prop("system_reserved_size", "partition_reserved_size")
Ying Wangbd93d422011-10-28 17:02:30 -0700907 elif mount_point == "data":
JP Abgrall5bfed5a2014-06-16 14:17:40 -0700908 # Copy the generic fs type first, override with specific one if available.
Ying Wang9f8e8db2011-11-04 11:37:01 -0700909 copy_prop("fs_type", "fs_type")
JP Abgrall5bfed5a2014-06-16 14:17:40 -0700910 copy_prop("userdata_fs_type", "fs_type")
Ying Wang9f8e8db2011-11-04 11:37:01 -0700911 copy_prop("userdata_size", "partition_size")
Tao Baoc72727a2017-12-07 10:33:00 -0800912 copy_prop("flash_logical_block_size", "flash_logical_block_size")
Connor O'Brien20f08c32017-01-05 16:48:14 -0800913 copy_prop("flash_erase_block_size", "flash_erase_block_size")
Ying Wang9f8e8db2011-11-04 11:37:01 -0700914 elif mount_point == "cache":
915 copy_prop("cache_fs_type", "fs_type")
916 copy_prop("cache_size", "partition_size")
Ying Wanga0febe52013-03-20 11:02:05 -0700917 elif mount_point == "vendor":
Bowgo Tsai3e599ea2017-05-26 18:30:04 +0800918 copy_prop("avb_vendor_hashtree_enable", "avb_hashtree_enable")
919 copy_prop("avb_vendor_add_hashtree_footer_args",
920 "avb_add_hashtree_footer_args")
921 copy_prop("avb_vendor_key_path", "avb_key_path")
922 copy_prop("avb_vendor_algorithm", "avb_algorithm")
Ying Wanga0febe52013-03-20 11:02:05 -0700923 copy_prop("vendor_fs_type", "fs_type")
924 copy_prop("vendor_size", "partition_size")
Tao Bao332a96b2018-03-31 10:27:35 -0700925 if not copy_prop("vendor_journal_size", "journal_size"):
926 d["journal_size"] = "0"
Daniel Rosenbergf4eabc32014-07-10 15:42:38 -0700927 copy_prop("vendor_verity_block_device", "verity_block_device")
Jin Qianfde9f792018-01-22 13:15:46 -0800928 copy_prop("ext4_share_dup_blocks", "ext4_share_dup_blocks")
Patrick Tjine11aa502016-02-09 15:40:38 -0800929 copy_prop("vendor_squashfs_compressor", "squashfs_compressor")
930 copy_prop("vendor_squashfs_compressor_opt", "squashfs_compressor_opt")
Mohamad Ayyashdfec8152016-05-24 12:59:30 -0700931 copy_prop("vendor_squashfs_block_size", "squashfs_block_size")
Mohamad Ayyash1b6d3482016-06-15 15:53:07 -0700932 copy_prop("vendor_squashfs_disable_4k_align", "squashfs_disable_4k_align")
Mohamad Ayyashf8765552016-03-02 21:07:23 -0800933 copy_prop("vendor_base_fs_file", "base_fs_file")
Patrick Tjina1900842016-10-20 10:58:12 -0700934 copy_prop("vendor_extfs_inode_count", "extfs_inode_count")
Patrick Tjin3f5f9932018-03-23 11:36:43 -0700935 if not copy_prop("vendor_extfs_rsv_pct", "extfs_rsv_pct"):
936 d["extfs_rsv_pct"] = "0"
Yifan Hong749062d2018-06-19 16:23:16 -0700937 copy_prop("vendor_reserved_size", "partition_reserved_size")
Jaekyun Seokb7735d82017-11-27 17:04:47 +0900938 elif mount_point == "product":
939 copy_prop("avb_product_hashtree_enable", "avb_hashtree_enable")
940 copy_prop("avb_product_add_hashtree_footer_args",
941 "avb_add_hashtree_footer_args")
942 copy_prop("avb_product_key_path", "avb_key_path")
943 copy_prop("avb_product_algorithm", "avb_algorithm")
944 copy_prop("product_fs_type", "fs_type")
945 copy_prop("product_size", "partition_size")
Tao Bao332a96b2018-03-31 10:27:35 -0700946 if not copy_prop("product_journal_size", "journal_size"):
947 d["journal_size"] = "0"
Jaekyun Seokb7735d82017-11-27 17:04:47 +0900948 copy_prop("product_verity_block_device", "verity_block_device")
949 copy_prop("product_squashfs_compressor", "squashfs_compressor")
950 copy_prop("product_squashfs_compressor_opt", "squashfs_compressor_opt")
951 copy_prop("product_squashfs_block_size", "squashfs_block_size")
952 copy_prop("product_squashfs_disable_4k_align", "squashfs_disable_4k_align")
953 copy_prop("product_base_fs_file", "base_fs_file")
954 copy_prop("product_extfs_inode_count", "extfs_inode_count")
Patrick Tjin3f5f9932018-03-23 11:36:43 -0700955 if not copy_prop("product_extfs_rsv_pct", "extfs_rsv_pct"):
956 d["extfs_rsv_pct"] = "0"
Yifan Hong56a6c3b2018-07-20 15:19:34 -0700957 copy_prop("product_reserved_size", "partition_reserved_size")
Dario Freni924af7d2018-08-17 00:56:14 +0100958 elif mount_point == "product_services":
Yifan Hongebc041a2018-07-26 16:02:52 -0700959 copy_prop("avb_product_services_hashtree_enable", "avb_hashtree_enable")
960 copy_prop("avb_product_services_add_hashtree_footer_args",
Dario Freni5f681e12018-05-29 13:09:01 +0100961 "avb_add_hashtree_footer_args")
Yifan Hongebc041a2018-07-26 16:02:52 -0700962 copy_prop("avb_product_services_key_path", "avb_key_path")
963 copy_prop("avb_product_services_algorithm", "avb_algorithm")
964 copy_prop("product_services_fs_type", "fs_type")
965 copy_prop("product_services_size", "partition_size")
966 if not copy_prop("product_services_journal_size", "journal_size"):
Dario Freni5f681e12018-05-29 13:09:01 +0100967 d["journal_size"] = "0"
Yifan Hongebc041a2018-07-26 16:02:52 -0700968 copy_prop("product_services_verity_block_device", "verity_block_device")
969 copy_prop("product_services_squashfs_compressor", "squashfs_compressor")
970 copy_prop("product_services_squashfs_compressor_opt",
Dario Freni5f681e12018-05-29 13:09:01 +0100971 "squashfs_compressor_opt")
Yifan Hongebc041a2018-07-26 16:02:52 -0700972 copy_prop("product_services_squashfs_block_size", "squashfs_block_size")
973 copy_prop("product_services_squashfs_disable_4k_align",
Dario Freni5f681e12018-05-29 13:09:01 +0100974 "squashfs_disable_4k_align")
Yifan Hongebc041a2018-07-26 16:02:52 -0700975 copy_prop("product_services_base_fs_file", "base_fs_file")
976 copy_prop("product_services_extfs_inode_count", "extfs_inode_count")
977 if not copy_prop("product_services_extfs_rsv_pct", "extfs_rsv_pct"):
Dario Freni5f681e12018-05-29 13:09:01 +0100978 d["extfs_rsv_pct"] = "0"
Yifan Hongebc041a2018-07-26 16:02:52 -0700979 copy_prop("product_services_reserved_size", "partition_reserved_size")
Bowgo Tsaid624fa62017-11-14 23:42:30 +0800980 elif mount_point == "odm":
981 copy_prop("avb_odm_hashtree_enable", "avb_hashtree_enable")
982 copy_prop("avb_odm_add_hashtree_footer_args",
983 "avb_add_hashtree_footer_args")
984 copy_prop("avb_odm_key_path", "avb_key_path")
985 copy_prop("avb_odm_algorithm", "avb_algorithm")
986 copy_prop("odm_fs_type", "fs_type")
987 copy_prop("odm_size", "partition_size")
988 if not copy_prop("odm_journal_size", "journal_size"):
989 d["journal_size"] = "0"
990 copy_prop("odm_verity_block_device", "verity_block_device")
991 copy_prop("odm_squashfs_compressor", "squashfs_compressor")
992 copy_prop("odm_squashfs_compressor_opt", "squashfs_compressor_opt")
993 copy_prop("odm_squashfs_block_size", "squashfs_block_size")
994 copy_prop("odm_squashfs_disable_4k_align", "squashfs_disable_4k_align")
995 copy_prop("odm_base_fs_file", "base_fs_file")
996 copy_prop("odm_extfs_inode_count", "extfs_inode_count")
997 if not copy_prop("odm_extfs_rsv_pct", "extfs_rsv_pct"):
998 d["extfs_rsv_pct"] = "0"
999 copy_prop("odm_reserved_size", "partition_reserved_size")
Ying Wangb8888432014-03-11 17:13:27 -07001000 elif mount_point == "oem":
1001 copy_prop("fs_type", "fs_type")
1002 copy_prop("oem_size", "partition_size")
Tao Bao332a96b2018-03-31 10:27:35 -07001003 if not copy_prop("oem_journal_size", "journal_size"):
1004 d["journal_size"] = "0"
Patrick Tjina1900842016-10-20 10:58:12 -07001005 copy_prop("oem_extfs_inode_count", "extfs_inode_count")
Patrick Tjin3f5f9932018-03-23 11:36:43 -07001006 if not copy_prop("oem_extfs_rsv_pct", "extfs_rsv_pct"):
1007 d["extfs_rsv_pct"] = "0"
David Zeuthen4014a9d2016-09-30 17:29:22 -04001008 d["partition_name"] = mount_point
Ying Wangbd93d422011-10-28 17:02:30 -07001009 return d
1010
1011
1012def LoadGlobalDict(filename):
1013 """Load "name=value" pairs from filename"""
1014 d = {}
1015 f = open(filename)
1016 for line in f:
1017 line = line.strip()
1018 if not line or line.startswith("#"):
1019 continue
1020 k, v = line.split("=", 1)
1021 d[k] = v
1022 f.close()
1023 return d
1024
1025
Yifan Hongbbcba1e2018-06-18 16:32:35 -07001026def GlobalDictFromImageProp(image_prop, mount_point):
1027 d = {}
1028 def copy_prop(src_p, dest_p):
1029 if src_p in image_prop:
1030 d[dest_p] = image_prop[src_p]
1031 return True
1032 return False
Tao Bao4251fe92018-07-23 13:05:00 -07001033
Yifan Hongbbcba1e2018-06-18 16:32:35 -07001034 if mount_point == "system":
Tao Bao35f4ebc2018-09-27 15:31:11 -07001035 copy_prop("partition_size", "system_size")
Yifan Hongbbcba1e2018-06-18 16:32:35 -07001036 elif mount_point == "system_other":
Tao Bao35f4ebc2018-09-27 15:31:11 -07001037 copy_prop("partition_size", "system_size")
Yifan Hong749062d2018-06-19 16:23:16 -07001038 elif mount_point == "vendor":
Tao Bao35f4ebc2018-09-27 15:31:11 -07001039 copy_prop("partition_size", "vendor_size")
Bowgo Tsaid624fa62017-11-14 23:42:30 +08001040 elif mount_point == "odm":
Tao Bao35f4ebc2018-09-27 15:31:11 -07001041 copy_prop("partition_size", "odm_size")
Yifan Hong56a6c3b2018-07-20 15:19:34 -07001042 elif mount_point == "product":
Tao Bao35f4ebc2018-09-27 15:31:11 -07001043 copy_prop("partition_size", "product_size")
Dario Freni924af7d2018-08-17 00:56:14 +01001044 elif mount_point == "product_services":
Tao Bao35f4ebc2018-09-27 15:31:11 -07001045 copy_prop("partition_size", "product_services_size")
Yifan Hongbbcba1e2018-06-18 16:32:35 -07001046 return d
1047
1048
1049def SaveGlobalDict(filename, glob_dict):
1050 with open(filename, "w") as f:
1051 f.writelines(["%s=%s" % (key, value) for (key, value) in glob_dict.items()])
1052
1053
Ying Wangbd93d422011-10-28 17:02:30 -07001054def main(argv):
Yifan Hongbbcba1e2018-06-18 16:32:35 -07001055 if len(argv) < 4 or len(argv) > 5:
Tao Baoc72727a2017-12-07 10:33:00 -08001056 print(__doc__)
Ying Wangbd93d422011-10-28 17:02:30 -07001057 sys.exit(1)
1058
1059 in_dir = argv[0]
1060 glob_dict_file = argv[1]
1061 out_file = argv[2]
Thierry Strudel74a81e62015-07-09 09:54:55 -07001062 target_out = argv[3]
Yifan Hongbbcba1e2018-06-18 16:32:35 -07001063 prop_file_out = argv[4] if len(argv) >= 5 else None
Ying Wangbd93d422011-10-28 17:02:30 -07001064
1065 glob_dict = LoadGlobalDict(glob_dict_file)
Ying Wangae61f502015-03-12 18:30:39 -07001066 if "mount_point" in glob_dict:
Tao Baoc7a6f1e2015-06-23 11:16:05 -07001067 # The caller knows the mount point and provides a dictionay needed by
1068 # BuildImage().
Ying Wangae61f502015-03-12 18:30:39 -07001069 image_properties = glob_dict
Ying Wang9f8e8db2011-11-04 11:37:01 -07001070 else:
Ying Wangae61f502015-03-12 18:30:39 -07001071 image_filename = os.path.basename(out_file)
1072 mount_point = ""
1073 if image_filename == "system.img":
1074 mount_point = "system"
Alex Light4e358ab2016-06-16 14:47:10 -07001075 elif image_filename == "system_other.img":
1076 mount_point = "system_other"
Ying Wangae61f502015-03-12 18:30:39 -07001077 elif image_filename == "userdata.img":
1078 mount_point = "data"
1079 elif image_filename == "cache.img":
1080 mount_point = "cache"
1081 elif image_filename == "vendor.img":
1082 mount_point = "vendor"
Bowgo Tsaid624fa62017-11-14 23:42:30 +08001083 elif image_filename == "odm.img":
1084 mount_point = "odm"
Ying Wangae61f502015-03-12 18:30:39 -07001085 elif image_filename == "oem.img":
1086 mount_point = "oem"
Jaekyun Seokb7735d82017-11-27 17:04:47 +09001087 elif image_filename == "product.img":
1088 mount_point = "product"
Dario Freni924af7d2018-08-17 00:56:14 +01001089 elif image_filename == "product_services.img":
1090 mount_point = "product_services"
Ying Wangae61f502015-03-12 18:30:39 -07001091 else:
Tao Baoc72727a2017-12-07 10:33:00 -08001092 print("error: unknown image file name ", image_filename, file=sys.stderr)
Tao Bao1c830bf2017-12-25 10:43:47 -08001093 sys.exit(1)
Ying Wangbd93d422011-10-28 17:02:30 -07001094
Ying Wangae61f502015-03-12 18:30:39 -07001095 image_properties = ImagePropFromGlobalDict(glob_dict, mount_point)
1096
Tao Baoc6bd70a2018-09-27 16:58:00 -07001097 try:
1098 BuildImage(in_dir, image_properties, out_file, target_out)
1099 except:
1100 print("Error: Failed to build {} from {}".format(out_file, in_dir),
Tao Baoc72727a2017-12-07 10:33:00 -08001101 file=sys.stderr)
Tao Baoc6bd70a2018-09-27 16:58:00 -07001102 raise
Ying Wangbd93d422011-10-28 17:02:30 -07001103
Yifan Hongbbcba1e2018-06-18 16:32:35 -07001104 if prop_file_out:
1105 glob_dict_out = GlobalDictFromImageProp(image_properties, mount_point)
1106 SaveGlobalDict(prop_file_out, glob_dict_out)
Ying Wangbd93d422011-10-28 17:02:30 -07001107
1108if __name__ == '__main__':
Tao Bao1c830bf2017-12-25 10:43:47 -08001109 try:
1110 main(sys.argv[1:])
1111 finally:
1112 common.Cleanup()