blob: d5ab05525e1267dd67c6ac8ed1475e91ab215f81 [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
Tao Bao2f057462018-10-03 16:31:18 -0700333def BuildVerityTree(sparse_image_path, verity_image_path):
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()
Tao Bao2f057462018-10-03 16:31:18 -0700341 return root, salt
Geremy Condrafd6f7512013-06-16 17:26:08 -0700342
Tao Baoc72727a2017-12-07 10:33:00 -0800343
Geremy Condrafd6f7512013-06-16 17:26:08 -0700344def BuildVerityMetadata(image_size, verity_metadata_path, root_hash, salt,
Bowgo Tsai6ceeb1a2017-10-11 16:21:48 +0800345 block_device, signer_path, key, signer_args,
346 verity_disable):
Tao Baob4ec6d72018-03-15 23:21:28 -0700347 cmd = ["build_verity_metadata.py", "build", str(image_size),
348 verity_metadata_path, root_hash, salt, block_device, signer_path, key]
Tao Bao45810422016-10-17 16:20:12 -0700349 if signer_args:
Tianjie Xue3ad41b2017-03-08 11:05:56 -0800350 cmd.append("--signer_args=\"%s\"" % (' '.join(signer_args),))
Bowgo Tsai6ceeb1a2017-10-11 16:21:48 +0800351 if verity_disable:
352 cmd.append("--verity_disable")
Tianjie Xue3ad41b2017-03-08 11:05:56 -0800353 output, exit_code = RunCommand(cmd)
354 if exit_code != 0:
Tao Baoc6bd70a2018-09-27 16:58:00 -0700355 raise BuildImageError(
356 "Failed to build verity metadata:\n{}".format(output))
Geremy Condrafd6f7512013-06-16 17:26:08 -0700357
Tao Baoc72727a2017-12-07 10:33:00 -0800358
Geremy Condrafd6f7512013-06-16 17:26:08 -0700359def Append2Simg(sparse_image_path, unsparse_image_path, error_message):
360 """Appends the unsparse image to the given sparse image.
361
362 Args:
363 sparse_image_path: the path to the (sparse) image
364 unsparse_image_path: the path to the (unsparse) image
Tao Baoc6bd70a2018-09-27 16:58:00 -0700365
366 Raises:
367 BuildImageError: On error.
Geremy Condrafd6f7512013-06-16 17:26:08 -0700368 """
Tianjie Xue3ad41b2017-03-08 11:05:56 -0800369 cmd = ["append2simg", sparse_image_path, unsparse_image_path]
370 output, exit_code = RunCommand(cmd)
371 if exit_code != 0:
Tao Baoc6bd70a2018-09-27 16:58:00 -0700372 raise BuildImageError("{}:\n{}".format(error_message, output))
Geremy Condrafd6f7512013-06-16 17:26:08 -0700373
Tao Baoc72727a2017-12-07 10:33:00 -0800374
Sami Tolvanenff914f52015-12-18 13:24:56 +0000375def Append(target, file_to_append, error_message):
Tao Baoc6bd70a2018-09-27 16:58:00 -0700376 """Appends file_to_append to target.
377
378 Raises:
379 BuildImageError: On error.
380 """
Tao Baoc72727a2017-12-07 10:33:00 -0800381 try:
382 with open(target, "a") as out_file, open(file_to_append, "r") as input_file:
Tianjie Xue3ad41b2017-03-08 11:05:56 -0800383 for line in input_file:
384 out_file.write(line)
Tao Baoc72727a2017-12-07 10:33:00 -0800385 except IOError:
Tao Baoc6bd70a2018-09-27 16:58:00 -0700386 raise BuildImageError(error_message)
Sami Tolvanenff914f52015-12-18 13:24:56 +0000387
Tao Baoc72727a2017-12-07 10:33:00 -0800388
Dan Albert8b72aef2015-03-23 19:13:21 -0700389def BuildVerifiedImage(data_image_path, verity_image_path,
Sami Tolvanen4a060042015-12-18 15:50:25 +0000390 verity_metadata_path, verity_fec_path,
Sami Tolvanen433905f2016-09-01 15:58:35 -0700391 padding_size, fec_supported):
Tao Baoc6bd70a2018-09-27 16:58:00 -0700392 Append(
393 verity_image_path, verity_metadata_path,
394 "Could not append verity metadata!")
Sami Tolvanen4a060042015-12-18 15:50:25 +0000395
396 if fec_supported:
Tao Baoc6bd70a2018-09-27 16:58:00 -0700397 # Build FEC for the entire partition, including metadata.
398 BuildVerityFEC(
399 data_image_path, verity_image_path, verity_fec_path, padding_size)
400 Append(verity_image_path, verity_fec_path, "Could not append FEC!")
Sami Tolvanen4a060042015-12-18 15:50:25 +0000401
Tao Baoc6bd70a2018-09-27 16:58:00 -0700402 Append2Simg(
403 data_image_path, verity_image_path, "Could not append verity data!")
Geremy Condrafd6f7512013-06-16 17:26:08 -0700404
Tao Baoc72727a2017-12-07 10:33:00 -0800405
Geremy Condra6e8f53c2013-12-05 17:09:18 -0800406def UnsparseImage(sparse_image_path, replace=True):
Geremy Condrafd6f7512013-06-16 17:26:08 -0700407 img_dir = os.path.dirname(sparse_image_path)
408 unsparse_image_path = "unsparse_" + os.path.basename(sparse_image_path)
409 unsparse_image_path = os.path.join(img_dir, unsparse_image_path)
410 if os.path.exists(unsparse_image_path):
Geremy Condra6e8f53c2013-12-05 17:09:18 -0800411 if replace:
412 os.unlink(unsparse_image_path)
413 else:
Tao Baoc6bd70a2018-09-27 16:58:00 -0700414 return unsparse_image_path
Geremy Condrafd6f7512013-06-16 17:26:08 -0700415 inflate_command = ["simg2img", sparse_image_path, unsparse_image_path]
Tao Baoc6bd70a2018-09-27 16:58:00 -0700416 inflate_output, exit_code = RunCommand(inflate_command)
Geremy Condrafd6f7512013-06-16 17:26:08 -0700417 if exit_code != 0:
418 os.remove(unsparse_image_path)
Tao Baoc6bd70a2018-09-27 16:58:00 -0700419 raise BuildImageError(
420 "Error: '{}' failed with exit code {}:\n{}".format(
421 inflate_command, exit_code, inflate_output))
422 return unsparse_image_path
Geremy Condrafd6f7512013-06-16 17:26:08 -0700423
Tao Baoc72727a2017-12-07 10:33:00 -0800424
Sami Tolvanenf99b5312015-05-20 07:30:57 +0100425def MakeVerityEnabledImage(out_file, fec_supported, prop_dict):
Geremy Condrafd6f7512013-06-16 17:26:08 -0700426 """Creates an image that is verifiable using dm-verity.
427
428 Args:
429 out_file: the location to write the verifiable image at
Dan Albert8b72aef2015-03-23 19:13:21 -0700430 prop_dict: a dictionary of properties required for image creation and
431 verification
Tao Baoc6bd70a2018-09-27 16:58:00 -0700432
433 Raises:
434 AssertionError: On invalid partition sizes.
435 BuildImageError: On other errors.
Geremy Condrafd6f7512013-06-16 17:26:08 -0700436 """
437 # get properties
Tao Bao35f4ebc2018-09-27 15:31:11 -0700438 image_size = int(prop_dict["image_size"])
Geremy Condrafd6f7512013-06-16 17:26:08 -0700439 block_dev = prop_dict["verity_block_device"]
Paul Lawrencea37b2bb2014-11-13 17:54:30 -0800440 signer_key = prop_dict["verity_key"] + ".pk8"
Baligh Uddin601ddea2015-06-09 15:48:14 -0700441 if OPTIONS.verity_signer_path is not None:
Tao Bao45810422016-10-17 16:20:12 -0700442 signer_path = OPTIONS.verity_signer_path
Baligh Uddin601ddea2015-06-09 15:48:14 -0700443 else:
444 signer_path = prop_dict["verity_signer_cmd"]
Tao Bao45810422016-10-17 16:20:12 -0700445 signer_args = OPTIONS.verity_signer_args
Geremy Condrafd6f7512013-06-16 17:26:08 -0700446
Tao Bao1c830bf2017-12-25 10:43:47 -0800447 tempdir_name = common.MakeTempDir(suffix="_verity_images")
Geremy Condrafd6f7512013-06-16 17:26:08 -0700448
Tao Baoc6bd70a2018-09-27 16:58:00 -0700449 # Get partial image paths.
Geremy Condrafd6f7512013-06-16 17:26:08 -0700450 verity_image_path = os.path.join(tempdir_name, "verity.img")
451 verity_metadata_path = os.path.join(tempdir_name, "verity_metadata.img")
Sami Tolvanenf99b5312015-05-20 07:30:57 +0100452 verity_fec_path = os.path.join(tempdir_name, "verity_fec.img")
Geremy Condrafd6f7512013-06-16 17:26:08 -0700453
Tao Baoc6bd70a2018-09-27 16:58:00 -0700454 # Build the verity tree and get the root hash and salt.
Tao Bao2f057462018-10-03 16:31:18 -0700455 root_hash, salt = BuildVerityTree(out_file, verity_image_path)
Geremy Condrafd6f7512013-06-16 17:26:08 -0700456
Tao Baoc6bd70a2018-09-27 16:58:00 -0700457 # Build the metadata blocks.
Bowgo Tsai6ceeb1a2017-10-11 16:21:48 +0800458 verity_disable = "verity_disable" in prop_dict
Tao Baoc6bd70a2018-09-27 16:58:00 -0700459 BuildVerityMetadata(
460 image_size, verity_metadata_path, root_hash, salt, block_dev, signer_path,
461 signer_key, signer_args, verity_disable)
Geremy Condrafd6f7512013-06-16 17:26:08 -0700462
Tao Baoc6bd70a2018-09-27 16:58:00 -0700463 # Build the full verified image.
Tao Bao35f4ebc2018-09-27 15:31:11 -0700464 partition_size = int(prop_dict["partition_size"])
Sami Tolvanen433905f2016-09-01 15:58:35 -0700465 verity_size = int(prop_dict["verity_size"])
466
Tao Bao35f4ebc2018-09-27 15:31:11 -0700467 padding_size = partition_size - image_size - verity_size
Sami Tolvanen433905f2016-09-01 15:58:35 -0700468 assert padding_size >= 0
469
Tao Baoc6bd70a2018-09-27 16:58:00 -0700470 BuildVerifiedImage(
471 out_file, verity_image_path, verity_metadata_path, verity_fec_path,
472 padding_size, fec_supported)
Geremy Condrafd6f7512013-06-16 17:26:08 -0700473
Tao Baoc72727a2017-12-07 10:33:00 -0800474
Mohamad Ayyashf8765552016-03-02 21:07:23 -0800475def ConvertBlockMapToBaseFs(block_map_file):
Tao Bao1c830bf2017-12-25 10:43:47 -0800476 base_fs_file = common.MakeTempFile(prefix="script_gen_", suffix=".base_fs")
Mohamad Ayyashf8765552016-03-02 21:07:23 -0800477 convert_command = ["blk_alloc_to_base_fs", block_map_file, base_fs_file]
Tao Baoc6bd70a2018-09-27 16:58:00 -0700478 output, exit_code = RunCommand(convert_command)
479 if exit_code != 0:
480 raise BuildImageError(
481 "Failed to call blk_alloc_to_base_fs:\n{}".format(output))
482 return base_fs_file
Mohamad Ayyashf8765552016-03-02 21:07:23 -0800483
Tao Baod4349f22017-12-07 23:01:25 -0800484
Tao Baoc2606eb2018-07-20 14:44:46 -0700485def SetUpInDirAndFsConfig(origin_in, prop_dict):
486 """Returns the in_dir and fs_config that should be used for image building.
487
Tom Cherryd14b8952018-08-09 14:26:00 -0700488 When building system.img for all targets, it creates and returns a staged dir
489 that combines the contents of /system (i.e. in the given in_dir) and root.
Tao Baoc2606eb2018-07-20 14:44:46 -0700490
491 Args:
492 origin_in: Path to the input directory.
493 prop_dict: A property dict that contains info like partition size. Values
494 may be updated.
495
496 Returns:
497 A tuple of in_dir and fs_config that should be used to build the image.
498 """
499 fs_config = prop_dict.get("fs_config")
Tom Cherryd14b8952018-08-09 14:26:00 -0700500
501 if prop_dict["mount_point"] == "system_other":
502 prop_dict["mount_point"] = "system"
503 return origin_in, fs_config
504
505 if prop_dict["mount_point"] != "system":
Tao Baoc2606eb2018-07-20 14:44:46 -0700506 return origin_in, fs_config
507
508 # Construct a staging directory of the root file system.
509 in_dir = common.MakeTempDir()
510 root_dir = prop_dict.get("root_dir")
511 if root_dir:
512 shutil.rmtree(in_dir)
513 shutil.copytree(root_dir, in_dir, symlinks=True)
514 in_dir_system = os.path.join(in_dir, "system")
515 shutil.rmtree(in_dir_system, ignore_errors=True)
516 shutil.copytree(origin_in, in_dir_system, symlinks=True)
517
518 # Change the mount point to "/".
519 prop_dict["mount_point"] = "/"
520 if fs_config:
521 # We need to merge the fs_config files of system and root.
522 merged_fs_config = common.MakeTempFile(
523 prefix="merged_fs_config", suffix=".txt")
524 with open(merged_fs_config, "w") as fw:
525 if "root_fs_config" in prop_dict:
526 with open(prop_dict["root_fs_config"]) as fr:
527 fw.writelines(fr.readlines())
528 with open(fs_config) as fr:
529 fw.writelines(fr.readlines())
530 fs_config = merged_fs_config
531 return in_dir, fs_config
532
533
Tao Baod4349f22017-12-07 23:01:25 -0800534def CheckHeadroom(ext4fs_output, prop_dict):
535 """Checks if there's enough headroom space available.
536
537 Headroom is the reserved space on system image (via PRODUCT_SYSTEM_HEADROOM),
538 which is useful for devices with low disk space that have system image
539 variation between builds. The 'partition_headroom' in prop_dict is the size
540 in bytes, while the numbers in 'ext4fs_output' are for 4K-blocks.
541
542 Args:
543 ext4fs_output: The output string from mke2fs command.
544 prop_dict: The property dict.
545
Tao Baod8a953d2018-01-02 21:19:27 -0800546 Raises:
547 AssertionError: On invalid input.
Tao Baoc6bd70a2018-09-27 16:58:00 -0700548 BuildImageError: On check failure.
Tao Baod4349f22017-12-07 23:01:25 -0800549 """
Tao Baod8a953d2018-01-02 21:19:27 -0800550 assert ext4fs_output is not None
551 assert prop_dict.get('fs_type', '').startswith('ext4')
552 assert 'partition_headroom' in prop_dict
553 assert 'mount_point' in prop_dict
554
Tao Baod4349f22017-12-07 23:01:25 -0800555 ext4fs_stats = re.compile(
556 r'Created filesystem with .* (?P<used_blocks>[0-9]+)/'
557 r'(?P<total_blocks>[0-9]+) blocks')
Tao Baoc72727a2017-12-07 10:33:00 -0800558 last_line = ext4fs_output.strip().split('\n')[-1]
559 m = ext4fs_stats.match(last_line)
Tao Baod4349f22017-12-07 23:01:25 -0800560 used_blocks = int(m.groupdict().get('used_blocks'))
561 total_blocks = int(m.groupdict().get('total_blocks'))
Tao Baod8a953d2018-01-02 21:19:27 -0800562 headroom_blocks = int(prop_dict['partition_headroom']) / BLOCK_SIZE
Tao Baod4349f22017-12-07 23:01:25 -0800563 adjusted_blocks = total_blocks - headroom_blocks
564 if used_blocks > adjusted_blocks:
Tao Baod8a953d2018-01-02 21:19:27 -0800565 mount_point = prop_dict["mount_point"]
Tao Baoc6bd70a2018-09-27 16:58:00 -0700566 raise BuildImageError(
567 "Error: Not enough room on {} (total: {} blocks, used: {} blocks, "
568 "headroom: {} blocks, available: {} blocks)".format(
569 mount_point, total_blocks, used_blocks, headroom_blocks,
570 adjusted_blocks))
Tao Baod4349f22017-12-07 23:01:25 -0800571
572
Thierry Strudel74a81e62015-07-09 09:54:55 -0700573def BuildImage(in_dir, prop_dict, out_file, target_out=None):
Tao Baoc2606eb2018-07-20 14:44:46 -0700574 """Builds an image for the files under in_dir and writes it to out_file.
575
Ying Wangbd93d422011-10-28 17:02:30 -0700576 Args:
Tao Baoc2606eb2018-07-20 14:44:46 -0700577 in_dir: Path to input directory.
578 prop_dict: A property dict that contains info like partition size. Values
579 will be updated with computed values.
580 out_file: The output image file.
581 target_out: Path to the TARGET_OUT directory as in Makefile. It actually
582 points to the /system directory under PRODUCT_OUT. fs_config (the one
583 under system/core/libcutils) reads device specific FS config files from
584 there.
Ying Wangbd93d422011-10-28 17:02:30 -0700585
Tao Baoc6bd70a2018-09-27 16:58:00 -0700586 Raises:
587 BuildImageError: On build image failures.
Ying Wangbd93d422011-10-28 17:02:30 -0700588 """
Tao Baoc2606eb2018-07-20 14:44:46 -0700589 in_dir, fs_config = SetUpInDirAndFsConfig(in_dir, prop_dict)
Ying Wanga2292c92015-03-24 19:07:40 -0700590
Ying Wangbd93d422011-10-28 17:02:30 -0700591 build_command = []
592 fs_type = prop_dict.get("fs_type", "")
Tao Baoc72727a2017-12-07 10:33:00 -0800593 run_e2fsck = False
Geremy Condrafd6f7512013-06-16 17:26:08 -0700594
Mohamad Ayyashdd063522015-03-24 12:42:03 -0700595 fs_spans_partition = True
596 if fs_type.startswith("squash"):
Tao Baoc7a6f1e2015-06-23 11:16:05 -0700597 fs_spans_partition = False
Mohamad Ayyashdd063522015-03-24 12:42:03 -0700598
Daniel Rosenbergf4eabc32014-07-10 15:42:38 -0700599 is_verity_partition = "verity_block_device" in prop_dict
Geremy Condra5b5f4952014-05-05 22:19:37 -0700600 verity_supported = prop_dict.get("verity") == "true"
Sami Tolvanenf99b5312015-05-20 07:30:57 +0100601 verity_fec_supported = prop_dict.get("verity_fec") == "true"
602
Bowgo Tsai040410c2018-09-20 16:40:01 +0800603 avb_footer_type = None
604 if prop_dict.get("avb_hash_enable") == "true":
605 avb_footer_type = "hash"
606 elif prop_dict.get("avb_hashtree_enable") == "true":
607 avb_footer_type = "hashtree"
608
609 if avb_footer_type:
610 avbtool = prop_dict.get("avb_avbtool")
611 avb_signing_args = prop_dict.get(
612 "avb_add_" + avb_footer_type + "_footer_args")
613
Yifan Hong2dae5722018-07-31 12:47:27 -0700614 if (prop_dict.get("use_dynamic_partition_size") == "true" and
Yifan Hongbbcba1e2018-06-18 16:32:35 -0700615 "partition_size" not in prop_dict):
Tao Baoc6bd70a2018-09-27 16:58:00 -0700616 # If partition_size is not defined, use output of `du' + reserved_size.
617 size = GetDiskUsage(in_dir)
Yifan Hongbbcba1e2018-06-18 16:32:35 -0700618 if OPTIONS.verbose:
Tao Baoc2606eb2018-07-20 14:44:46 -0700619 print("The tree size of %s is %d MB." % (in_dir, size // BYTES_IN_MB))
Yifan Hongbbcba1e2018-06-18 16:32:35 -0700620 size += int(prop_dict.get("partition_reserved_size", 0))
621 # Round this up to a multiple of 4K so that avbtool works
622 size = common.RoundUpTo4K(size)
Bowgo Tsai040410c2018-09-20 16:40:01 +0800623 # Adjust partition_size to add more space for AVB footer, to prevent
624 # it from consuming partition_reserved_size.
625 if avb_footer_type:
626 size = AVBCalcMinPartitionSize(
627 size,
628 lambda x: AVBCalcMaxImageSize(
629 avbtool, avb_footer_type, x, avb_signing_args))
Yifan Hongbbcba1e2018-06-18 16:32:35 -0700630 prop_dict["partition_size"] = str(size)
631 if OPTIONS.verbose:
632 print("Allocating %d MB for %s." % (size // BYTES_IN_MB, out_file))
633
Tao Bao35f4ebc2018-09-27 15:31:11 -0700634 prop_dict["image_size"] = prop_dict["partition_size"]
635
636 # Adjust the image size to make room for the hashes if this is to be verified.
Sami Tolvanen405e71d2016-02-09 12:28:58 -0800637 if verity_supported and is_verity_partition:
Geremy Condrafd6f7512013-06-16 17:26:08 -0700638 partition_size = int(prop_dict.get("partition_size"))
Tao Bao35f4ebc2018-09-27 15:31:11 -0700639 image_size, verity_size = AdjustPartitionSizeForVerity(
Tao Baoc72727a2017-12-07 10:33:00 -0800640 partition_size, verity_fec_supported)
Tao Bao35f4ebc2018-09-27 15:31:11 -0700641 prop_dict["image_size"] = str(image_size)
Sami Tolvanen433905f2016-09-01 15:58:35 -0700642 prop_dict["verity_size"] = str(verity_size)
Geremy Condrafd6f7512013-06-16 17:26:08 -0700643
Tao Bao35f4ebc2018-09-27 15:31:11 -0700644 # Adjust the image size for AVB hash footer or AVB hashtree footer.
Bowgo Tsai7ea994b2017-05-19 23:44:26 +0800645 if avb_footer_type:
Bowgo Tsai3e599ea2017-05-26 18:30:04 +0800646 partition_size = prop_dict["partition_size"]
Bowgo Tsai7ea994b2017-05-19 23:44:26 +0800647 # avb_add_hash_footer_args or avb_add_hashtree_footer_args.
Tao Baoc6bd70a2018-09-27 16:58:00 -0700648 max_image_size = AVBCalcMaxImageSize(
649 avbtool, avb_footer_type, partition_size, avb_signing_args)
Tao Bao35f4ebc2018-09-27 15:31:11 -0700650 prop_dict["image_size"] = str(max_image_size)
David Zeuthen4014a9d2016-09-30 17:29:22 -0400651
Ying Wangbd93d422011-10-28 17:02:30 -0700652 if fs_type.startswith("ext"):
Adrien Schildknecht9a072cc2016-11-18 17:06:29 -0800653 build_command = [prop_dict["ext_mkuserimg"]]
Ying Wangbd93d422011-10-28 17:02:30 -0700654 if "extfs_sparse_flag" in prop_dict:
655 build_command.append(prop_dict["extfs_sparse_flag"])
Tao Baoc72727a2017-12-07 10:33:00 -0800656 run_e2fsck = True
Ying Wangbd93d422011-10-28 17:02:30 -0700657 build_command.extend([in_dir, out_file, fs_type,
658 prop_dict["mount_point"]])
Tao Bao35f4ebc2018-09-27 15:31:11 -0700659 build_command.append(prop_dict["image_size"])
Ying Wangf3b86352014-11-18 18:03:13 -0800660 if "journal_size" in prop_dict:
661 build_command.extend(["-j", prop_dict["journal_size"]])
Doug Zongker850b8072013-12-05 15:54:55 -0800662 if "timestamp" in prop_dict:
663 build_command.extend(["-T", str(prop_dict["timestamp"])])
Ying Wanga2292c92015-03-24 19:07:40 -0700664 if fs_config:
Doug Zongker82822822014-06-16 09:10:55 -0700665 build_command.extend(["-C", fs_config])
Thierry Strudel74a81e62015-07-09 09:54:55 -0700666 if target_out:
667 build_command.extend(["-D", target_out])
Ying Wanga2292c92015-03-24 19:07:40 -0700668 if "block_list" in prop_dict:
669 build_command.extend(["-B", prop_dict["block_list"]])
Mohamad Ayyashf8765552016-03-02 21:07:23 -0800670 if "base_fs_file" in prop_dict:
671 base_fs_file = ConvertBlockMapToBaseFs(prop_dict["base_fs_file"])
Mohamad Ayyashf8765552016-03-02 21:07:23 -0800672 build_command.extend(["-d", base_fs_file])
Christoffer Dall8ed01f32014-12-17 21:34:12 +0100673 build_command.extend(["-L", prop_dict["mount_point"]])
Patrick Tjina1900842016-10-20 10:58:12 -0700674 if "extfs_inode_count" in prop_dict:
675 build_command.extend(["-i", prop_dict["extfs_inode_count"]])
Patrick Tjin3f5f9932018-03-23 11:36:43 -0700676 if "extfs_rsv_pct" in prop_dict:
677 build_command.extend(["-M", prop_dict["extfs_rsv_pct"]])
Connor O'Brien20f08c32017-01-05 16:48:14 -0800678 if "flash_erase_block_size" in prop_dict:
679 build_command.extend(["-e", prop_dict["flash_erase_block_size"]])
680 if "flash_logical_block_size" in prop_dict:
681 build_command.extend(["-o", prop_dict["flash_logical_block_size"]])
Tao Baod86e3112017-09-22 15:45:33 -0700682 # Specify UUID and hash_seed if using mke2fs.
Tianjie Xu57332222018-08-15 16:16:21 -0700683 if prop_dict["ext_mkuserimg"] == "mkuserimg_mke2fs":
Tao Baod86e3112017-09-22 15:45:33 -0700684 if "uuid" in prop_dict:
685 build_command.extend(["-U", prop_dict["uuid"]])
686 if "hash_seed" in prop_dict:
687 build_command.extend(["-S", prop_dict["hash_seed"]])
Jin Qianfde9f792018-01-22 13:15:46 -0800688 if "ext4_share_dup_blocks" in prop_dict:
689 build_command.append("-c")
Ying Wanga2292c92015-03-24 19:07:40 -0700690 if "selinux_fc" in prop_dict:
Kenny Rootf32dc712012-04-08 10:42:34 -0700691 build_command.append(prop_dict["selinux_fc"])
Mohamad Ayyashb97746e2015-03-03 12:30:37 -0800692 elif fs_type.startswith("squash"):
693 build_command = ["mksquashfsimage.sh"]
694 build_command.extend([in_dir, out_file])
Todd Poynorb2a555e2015-12-15 18:00:14 -0800695 if "squashfs_sparse_flag" in prop_dict:
696 build_command.extend([prop_dict["squashfs_sparse_flag"]])
Mohamad Ayyashb97746e2015-03-03 12:30:37 -0800697 build_command.extend(["-m", prop_dict["mount_point"]])
Thierry Strudel74a81e62015-07-09 09:54:55 -0700698 if target_out:
699 build_command.extend(["-d", target_out])
Mohamad Ayyash88378822016-04-07 22:10:51 -0700700 if fs_config:
701 build_command.extend(["-C", fs_config])
Ying Wanga2292c92015-03-24 19:07:40 -0700702 if "selinux_fc" in prop_dict:
Mohamad Ayyashb97746e2015-03-03 12:30:37 -0800703 build_command.extend(["-c", prop_dict["selinux_fc"]])
Mohamad Ayyashc3484f72016-06-13 09:46:58 -0700704 if "block_list" in prop_dict:
705 build_command.extend(["-B", prop_dict["block_list"]])
Ng Zhi An9446c1d2018-01-19 15:51:46 -0800706 if "squashfs_block_size" in prop_dict:
707 build_command.extend(["-b", prop_dict["squashfs_block_size"]])
Simon Wilsonf86e7ee2015-06-17 12:35:15 -0700708 if "squashfs_compressor" in prop_dict:
709 build_command.extend(["-z", prop_dict["squashfs_compressor"]])
710 if "squashfs_compressor_opt" in prop_dict:
711 build_command.extend(["-zo", prop_dict["squashfs_compressor_opt"]])
Tao Baoc72727a2017-12-07 10:33:00 -0800712 if prop_dict.get("squashfs_disable_4k_align") == "true":
Mohamad Ayyash1b6d3482016-06-15 15:53:07 -0700713 build_command.extend(["-a"])
JP Abgrall5bfed5a2014-06-16 14:17:40 -0700714 elif fs_type.startswith("f2fs"):
715 build_command = ["mkf2fsuserimg.sh"]
Tao Bao35f4ebc2018-09-27 15:31:11 -0700716 build_command.extend([out_file, prop_dict["image_size"]])
Jaegeuk Kim2ea1eba2017-11-28 19:21:28 -0800717 if fs_config:
718 build_command.extend(["-C", fs_config])
719 build_command.extend(["-f", in_dir])
720 if target_out:
721 build_command.extend(["-D", target_out])
722 if "selinux_fc" in prop_dict:
723 build_command.extend(["-s", prop_dict["selinux_fc"]])
724 build_command.extend(["-t", prop_dict["mount_point"]])
725 if "timestamp" in prop_dict:
726 build_command.extend(["-T", str(prop_dict["timestamp"])])
727 build_command.extend(["-L", prop_dict["mount_point"]])
Ying Wangbd93d422011-10-28 17:02:30 -0700728 else:
Tao Baoc6bd70a2018-09-27 16:58:00 -0700729 raise BuildImageError(
730 "Error: unknown filesystem type: {}".format(fs_type))
Ying Wangbd93d422011-10-28 17:02:30 -0700731
Tao Baoc6bd70a2018-09-27 16:58:00 -0700732 mkfs_output, exit_code = RunCommand(build_command)
Ying Wang69e9b4d2012-11-26 18:10:23 -0800733 if exit_code != 0:
Tao Baoc6bd70a2018-09-27 16:58:00 -0700734 try:
735 du = GetDiskUsage(in_dir)
736 du_str = "{} bytes ({} MB)".format(du, du // BYTES_IN_MB)
737 except BuildImageError as e:
738 print(e, file=sys.stderr)
739 du_str = "unknown"
Tao Bao4251fe92018-07-23 13:05:00 -0700740 print(
741 "Out of space? The tree size of {} is {}, with reserved space of {} "
742 "bytes ({} MB).".format(
Tao Baoc2606eb2018-07-20 14:44:46 -0700743 in_dir, du_str,
Tao Bao4251fe92018-07-23 13:05:00 -0700744 int(prop_dict.get("partition_reserved_size", 0)),
745 int(prop_dict.get("partition_reserved_size", 0)) // BYTES_IN_MB))
Tao Bao35f4ebc2018-09-27 15:31:11 -0700746 print(
747 "The max image size for filsystem files is {} bytes ({} MB), out of a "
748 "total partition size of {} bytes ({} MB).".format(
749 int(prop_dict["image_size"]),
750 int(prop_dict["image_size"]) // BYTES_IN_MB,
751 int(prop_dict["partition_size"]),
752 int(prop_dict["partition_size"]) // BYTES_IN_MB))
Tao Baoc6bd70a2018-09-27 16:58:00 -0700753
754 raise BuildImageError(
755 "Error: '{}' failed with exit code {}:\n{}".format(
756 build_command, exit_code, mkfs_output))
Ying Wang69e9b4d2012-11-26 18:10:23 -0800757
Tao Baod4349f22017-12-07 23:01:25 -0800758 # Check if there's enough headroom space available for ext4 image.
Tao Bao79d52f82017-12-07 14:07:44 -0800759 if "partition_headroom" in prop_dict and fs_type.startswith("ext4"):
Tao Baoc6bd70a2018-09-27 16:58:00 -0700760 CheckHeadroom(mkfs_output, prop_dict)
Tao Baoc7a6f1e2015-06-23 11:16:05 -0700761
Mohamad Ayyashdd063522015-03-24 12:42:03 -0700762 if not fs_spans_partition:
763 mount_point = prop_dict.get("mount_point")
Tao Bao35f4ebc2018-09-27 15:31:11 -0700764 image_size = int(prop_dict["image_size"])
765 sparse_image_size = GetSimgSize(out_file)
766 if sparse_image_size > image_size:
Tao Baoc6bd70a2018-09-27 16:58:00 -0700767 raise BuildImageError(
768 "Error: {} image size of {} is larger than partition size of "
769 "{}".format(mount_point, sparse_image_size, image_size))
Mohamad Ayyashdd063522015-03-24 12:42:03 -0700770 if verity_supported and is_verity_partition:
Tao Bao35f4ebc2018-09-27 15:31:11 -0700771 ZeroPadSimg(out_file, image_size - sparse_image_size)
Mohamad Ayyashdd063522015-03-24 12:42:03 -0700772
Tao Baoc72727a2017-12-07 10:33:00 -0800773 # Create the verified image if this is to be verified.
Geremy Condra5b5f4952014-05-05 22:19:37 -0700774 if verity_supported and is_verity_partition:
Tao Baoc6bd70a2018-09-27 16:58:00 -0700775 MakeVerityEnabledImage(out_file, verity_fec_supported, prop_dict)
Geremy Condrafd6f7512013-06-16 17:26:08 -0700776
Bowgo Tsai7ea994b2017-05-19 23:44:26 +0800777 # Add AVB HASH or HASHTREE footer (metadata).
778 if avb_footer_type:
Tao Bao35f4ebc2018-09-27 15:31:11 -0700779 partition_size = prop_dict["partition_size"]
David Zeuthen4014a9d2016-09-30 17:29:22 -0400780 partition_name = prop_dict["partition_name"]
Bowgo Tsai3e599ea2017-05-26 18:30:04 +0800781 # key_path and algorithm are only available when chain partition is used.
782 key_path = prop_dict.get("avb_key_path")
783 algorithm = prop_dict.get("avb_algorithm")
Tao Bao2b6dfd62017-09-27 17:17:43 -0700784 salt = prop_dict.get("avb_salt")
Tao Baoc6bd70a2018-09-27 16:58:00 -0700785 AVBAddFooter(
786 out_file, avbtool, avb_footer_type, partition_size, partition_name,
787 key_path, algorithm, salt, avb_signing_args)
David Zeuthen4014a9d2016-09-30 17:29:22 -0400788
Tao Baoc72727a2017-12-07 10:33:00 -0800789 if run_e2fsck and prop_dict.get("skip_fsck") != "true":
Tao Baoc6bd70a2018-09-27 16:58:00 -0700790 unsparse_image = UnsparseImage(out_file, replace=False)
Ying Wang69e9b4d2012-11-26 18:10:23 -0800791
792 # Run e2fsck on the inflated image file
793 e2fsck_command = ["e2fsck", "-f", "-n", unsparse_image]
Isaac Chenec7fa1c2018-08-02 14:02:56 +0800794 # TODO(b/112062612): work around e2fsck failure with SANITIZE_HOST=address
795 env4e2fsck = {"ASAN_OPTIONS": "detect_odr_violation=0"}
Tao Baoc6bd70a2018-09-27 16:58:00 -0700796 e2fsck_output, exit_code = RunCommand(e2fsck_command, env=env4e2fsck)
Ying Wang69e9b4d2012-11-26 18:10:23 -0800797
798 os.remove(unsparse_image)
799
Elliott Hughes73ff57f2017-12-06 12:16:39 -0800800 if exit_code != 0:
Tao Baoc6bd70a2018-09-27 16:58:00 -0700801 raise BuildImageError(
802 "Error: '{}' failed with exit code {}:\n{}".format(
803 e2fsck_command, exit_code, e2fsck_output))
Ying Wangbd93d422011-10-28 17:02:30 -0700804
805
806def ImagePropFromGlobalDict(glob_dict, mount_point):
807 """Build an image property dictionary from the global dictionary.
808
809 Args:
810 glob_dict: the global dictionary from the build system.
811 mount_point: such as "system", "data" etc.
812 """
Doug Zongker1ad7ade2013-12-06 11:53:27 -0800813 d = {}
Tao Bao052ae352015-09-28 13:44:13 -0700814
Tao Bao822f5842015-09-30 16:01:14 -0700815 if "build.prop" in glob_dict:
816 bp = glob_dict["build.prop"]
817 if "ro.build.date.utc" in bp:
818 d["timestamp"] = bp["ro.build.date.utc"]
Ying Wang9f8e8db2011-11-04 11:37:01 -0700819
820 def copy_prop(src_p, dest_p):
Patrick Tjin3f5f9932018-03-23 11:36:43 -0700821 """Copy a property from the global dictionary.
822
823 Args:
824 src_p: The source property in the global dictionary.
825 dest_p: The destination property.
826 Returns:
827 True if property was found and copied, False otherwise.
828 """
Ying Wang9f8e8db2011-11-04 11:37:01 -0700829 if src_p in glob_dict:
830 d[dest_p] = str(glob_dict[src_p])
Patrick Tjin3f5f9932018-03-23 11:36:43 -0700831 return True
832 return False
Ying Wang9f8e8db2011-11-04 11:37:01 -0700833
Ying Wangbd93d422011-10-28 17:02:30 -0700834 common_props = (
Ying Wangbd93d422011-10-28 17:02:30 -0700835 "extfs_sparse_flag",
Todd Poynorb2a555e2015-12-15 18:00:14 -0800836 "squashfs_sparse_flag",
Kenny Rootf32dc712012-04-08 10:42:34 -0700837 "selinux_fc",
Ying Wang6a42a252013-02-27 13:54:02 -0800838 "skip_fsck",
Adrien Schildknecht9a072cc2016-11-18 17:06:29 -0800839 "ext_mkuserimg",
Geremy Condrafd6f7512013-06-16 17:26:08 -0700840 "verity",
Geremy Condrafd6f7512013-06-16 17:26:08 -0700841 "verity_key",
Sami Tolvanenf99b5312015-05-20 07:30:57 +0100842 "verity_signer_cmd",
David Zeuthen4014a9d2016-09-30 17:29:22 -0400843 "verity_fec",
Bowgo Tsai6ceeb1a2017-10-11 16:21:48 +0800844 "verity_disable",
Bowgo Tsai3e599ea2017-05-26 18:30:04 +0800845 "avb_enable",
Tao Bao2b6dfd62017-09-27 17:17:43 -0700846 "avb_avbtool",
847 "avb_salt",
Yifan Hong2dae5722018-07-31 12:47:27 -0700848 "use_dynamic_partition_size",
Tao Bao2b6dfd62017-09-27 17:17:43 -0700849 )
Ying Wangbd93d422011-10-28 17:02:30 -0700850 for p in common_props:
Ying Wang9f8e8db2011-11-04 11:37:01 -0700851 copy_prop(p, p)
Ying Wangbd93d422011-10-28 17:02:30 -0700852
853 d["mount_point"] = mount_point
854 if mount_point == "system":
Bowgo Tsai3e599ea2017-05-26 18:30:04 +0800855 copy_prop("avb_system_hashtree_enable", "avb_hashtree_enable")
856 copy_prop("avb_system_add_hashtree_footer_args",
857 "avb_add_hashtree_footer_args")
858 copy_prop("avb_system_key_path", "avb_key_path")
859 copy_prop("avb_system_algorithm", "avb_algorithm")
Ying Wang9f8e8db2011-11-04 11:37:01 -0700860 copy_prop("fs_type", "fs_type")
Julius D'souza001c6762017-05-03 13:43:27 -0700861 # Copy the generic system fs type first, override with specific one if
Dan Albert8b72aef2015-03-23 19:13:21 -0700862 # available.
Mohamad Ayyashb97746e2015-03-03 12:30:37 -0800863 copy_prop("system_fs_type", "fs_type")
Julius D'souza001c6762017-05-03 13:43:27 -0700864 copy_prop("system_headroom", "partition_headroom")
Ying Wang9f8e8db2011-11-04 11:37:01 -0700865 copy_prop("system_size", "partition_size")
Tao Bao332a96b2018-03-31 10:27:35 -0700866 if not copy_prop("system_journal_size", "journal_size"):
867 d["journal_size"] = "0"
Daniel Rosenbergf4eabc32014-07-10 15:42:38 -0700868 copy_prop("system_verity_block_device", "verity_block_device")
Tao Baof3282b42015-04-01 11:21:55 -0700869 copy_prop("system_root_image", "system_root_image")
Tao Bao8bfd3c72018-07-20 15:20:28 -0700870 copy_prop("root_dir", "root_dir")
871 copy_prop("root_fs_config", "root_fs_config")
Jin Qianfde9f792018-01-22 13:15:46 -0800872 copy_prop("ext4_share_dup_blocks", "ext4_share_dup_blocks")
Simon Wilsonf86e7ee2015-06-17 12:35:15 -0700873 copy_prop("system_squashfs_compressor", "squashfs_compressor")
874 copy_prop("system_squashfs_compressor_opt", "squashfs_compressor_opt")
Mohamad Ayyashdfec8152016-05-24 12:59:30 -0700875 copy_prop("system_squashfs_block_size", "squashfs_block_size")
Mohamad Ayyash1b6d3482016-06-15 15:53:07 -0700876 copy_prop("system_squashfs_disable_4k_align", "squashfs_disable_4k_align")
Mohamad Ayyashf8765552016-03-02 21:07:23 -0800877 copy_prop("system_base_fs_file", "base_fs_file")
Patrick Tjina1900842016-10-20 10:58:12 -0700878 copy_prop("system_extfs_inode_count", "extfs_inode_count")
Patrick Tjin3f5f9932018-03-23 11:36:43 -0700879 if not copy_prop("system_extfs_rsv_pct", "extfs_rsv_pct"):
880 d["extfs_rsv_pct"] = "0"
Yifan Hongbbcba1e2018-06-18 16:32:35 -0700881 copy_prop("system_reserved_size", "partition_reserved_size")
Alex Light4e358ab2016-06-16 14:47:10 -0700882 elif mount_point == "system_other":
Tao Baoc72727a2017-12-07 10:33:00 -0800883 # We inherit the selinux policies of /system since we contain some of its
884 # files.
Bowgo Tsai3e599ea2017-05-26 18:30:04 +0800885 copy_prop("avb_system_hashtree_enable", "avb_hashtree_enable")
886 copy_prop("avb_system_add_hashtree_footer_args",
887 "avb_add_hashtree_footer_args")
888 copy_prop("avb_system_key_path", "avb_key_path")
889 copy_prop("avb_system_algorithm", "avb_algorithm")
Alex Light4e358ab2016-06-16 14:47:10 -0700890 copy_prop("fs_type", "fs_type")
891 copy_prop("system_fs_type", "fs_type")
892 copy_prop("system_size", "partition_size")
Tao Bao332a96b2018-03-31 10:27:35 -0700893 if not copy_prop("system_journal_size", "journal_size"):
894 d["journal_size"] = "0"
Alex Light4e358ab2016-06-16 14:47:10 -0700895 copy_prop("system_verity_block_device", "verity_block_device")
Alex Light4e358ab2016-06-16 14:47:10 -0700896 copy_prop("system_squashfs_compressor", "squashfs_compressor")
897 copy_prop("system_squashfs_compressor_opt", "squashfs_compressor_opt")
898 copy_prop("system_squashfs_block_size", "squashfs_block_size")
899 copy_prop("system_base_fs_file", "base_fs_file")
Patrick Tjina1900842016-10-20 10:58:12 -0700900 copy_prop("system_extfs_inode_count", "extfs_inode_count")
Patrick Tjin3f5f9932018-03-23 11:36:43 -0700901 if not copy_prop("system_extfs_rsv_pct", "extfs_rsv_pct"):
902 d["extfs_rsv_pct"] = "0"
Yifan Hongbbcba1e2018-06-18 16:32:35 -0700903 copy_prop("system_reserved_size", "partition_reserved_size")
Ying Wangbd93d422011-10-28 17:02:30 -0700904 elif mount_point == "data":
JP Abgrall5bfed5a2014-06-16 14:17:40 -0700905 # Copy the generic fs type first, override with specific one if available.
Ying Wang9f8e8db2011-11-04 11:37:01 -0700906 copy_prop("fs_type", "fs_type")
JP Abgrall5bfed5a2014-06-16 14:17:40 -0700907 copy_prop("userdata_fs_type", "fs_type")
Ying Wang9f8e8db2011-11-04 11:37:01 -0700908 copy_prop("userdata_size", "partition_size")
Tao Baoc72727a2017-12-07 10:33:00 -0800909 copy_prop("flash_logical_block_size", "flash_logical_block_size")
Connor O'Brien20f08c32017-01-05 16:48:14 -0800910 copy_prop("flash_erase_block_size", "flash_erase_block_size")
Ying Wang9f8e8db2011-11-04 11:37:01 -0700911 elif mount_point == "cache":
912 copy_prop("cache_fs_type", "fs_type")
913 copy_prop("cache_size", "partition_size")
Ying Wanga0febe52013-03-20 11:02:05 -0700914 elif mount_point == "vendor":
Bowgo Tsai3e599ea2017-05-26 18:30:04 +0800915 copy_prop("avb_vendor_hashtree_enable", "avb_hashtree_enable")
916 copy_prop("avb_vendor_add_hashtree_footer_args",
917 "avb_add_hashtree_footer_args")
918 copy_prop("avb_vendor_key_path", "avb_key_path")
919 copy_prop("avb_vendor_algorithm", "avb_algorithm")
Ying Wanga0febe52013-03-20 11:02:05 -0700920 copy_prop("vendor_fs_type", "fs_type")
921 copy_prop("vendor_size", "partition_size")
Tao Bao332a96b2018-03-31 10:27:35 -0700922 if not copy_prop("vendor_journal_size", "journal_size"):
923 d["journal_size"] = "0"
Daniel Rosenbergf4eabc32014-07-10 15:42:38 -0700924 copy_prop("vendor_verity_block_device", "verity_block_device")
Jin Qianfde9f792018-01-22 13:15:46 -0800925 copy_prop("ext4_share_dup_blocks", "ext4_share_dup_blocks")
Patrick Tjine11aa502016-02-09 15:40:38 -0800926 copy_prop("vendor_squashfs_compressor", "squashfs_compressor")
927 copy_prop("vendor_squashfs_compressor_opt", "squashfs_compressor_opt")
Mohamad Ayyashdfec8152016-05-24 12:59:30 -0700928 copy_prop("vendor_squashfs_block_size", "squashfs_block_size")
Mohamad Ayyash1b6d3482016-06-15 15:53:07 -0700929 copy_prop("vendor_squashfs_disable_4k_align", "squashfs_disable_4k_align")
Mohamad Ayyashf8765552016-03-02 21:07:23 -0800930 copy_prop("vendor_base_fs_file", "base_fs_file")
Patrick Tjina1900842016-10-20 10:58:12 -0700931 copy_prop("vendor_extfs_inode_count", "extfs_inode_count")
Patrick Tjin3f5f9932018-03-23 11:36:43 -0700932 if not copy_prop("vendor_extfs_rsv_pct", "extfs_rsv_pct"):
933 d["extfs_rsv_pct"] = "0"
Yifan Hong749062d2018-06-19 16:23:16 -0700934 copy_prop("vendor_reserved_size", "partition_reserved_size")
Jaekyun Seokb7735d82017-11-27 17:04:47 +0900935 elif mount_point == "product":
936 copy_prop("avb_product_hashtree_enable", "avb_hashtree_enable")
937 copy_prop("avb_product_add_hashtree_footer_args",
938 "avb_add_hashtree_footer_args")
939 copy_prop("avb_product_key_path", "avb_key_path")
940 copy_prop("avb_product_algorithm", "avb_algorithm")
941 copy_prop("product_fs_type", "fs_type")
942 copy_prop("product_size", "partition_size")
Tao Bao332a96b2018-03-31 10:27:35 -0700943 if not copy_prop("product_journal_size", "journal_size"):
944 d["journal_size"] = "0"
Jaekyun Seokb7735d82017-11-27 17:04:47 +0900945 copy_prop("product_verity_block_device", "verity_block_device")
946 copy_prop("product_squashfs_compressor", "squashfs_compressor")
947 copy_prop("product_squashfs_compressor_opt", "squashfs_compressor_opt")
948 copy_prop("product_squashfs_block_size", "squashfs_block_size")
949 copy_prop("product_squashfs_disable_4k_align", "squashfs_disable_4k_align")
950 copy_prop("product_base_fs_file", "base_fs_file")
951 copy_prop("product_extfs_inode_count", "extfs_inode_count")
Patrick Tjin3f5f9932018-03-23 11:36:43 -0700952 if not copy_prop("product_extfs_rsv_pct", "extfs_rsv_pct"):
953 d["extfs_rsv_pct"] = "0"
Yifan Hong56a6c3b2018-07-20 15:19:34 -0700954 copy_prop("product_reserved_size", "partition_reserved_size")
Dario Freni924af7d2018-08-17 00:56:14 +0100955 elif mount_point == "product_services":
Yifan Hongebc041a2018-07-26 16:02:52 -0700956 copy_prop("avb_product_services_hashtree_enable", "avb_hashtree_enable")
957 copy_prop("avb_product_services_add_hashtree_footer_args",
Dario Freni5f681e12018-05-29 13:09:01 +0100958 "avb_add_hashtree_footer_args")
Yifan Hongebc041a2018-07-26 16:02:52 -0700959 copy_prop("avb_product_services_key_path", "avb_key_path")
960 copy_prop("avb_product_services_algorithm", "avb_algorithm")
961 copy_prop("product_services_fs_type", "fs_type")
962 copy_prop("product_services_size", "partition_size")
963 if not copy_prop("product_services_journal_size", "journal_size"):
Dario Freni5f681e12018-05-29 13:09:01 +0100964 d["journal_size"] = "0"
Yifan Hongebc041a2018-07-26 16:02:52 -0700965 copy_prop("product_services_verity_block_device", "verity_block_device")
966 copy_prop("product_services_squashfs_compressor", "squashfs_compressor")
967 copy_prop("product_services_squashfs_compressor_opt",
Dario Freni5f681e12018-05-29 13:09:01 +0100968 "squashfs_compressor_opt")
Yifan Hongebc041a2018-07-26 16:02:52 -0700969 copy_prop("product_services_squashfs_block_size", "squashfs_block_size")
970 copy_prop("product_services_squashfs_disable_4k_align",
Dario Freni5f681e12018-05-29 13:09:01 +0100971 "squashfs_disable_4k_align")
Yifan Hongebc041a2018-07-26 16:02:52 -0700972 copy_prop("product_services_base_fs_file", "base_fs_file")
973 copy_prop("product_services_extfs_inode_count", "extfs_inode_count")
974 if not copy_prop("product_services_extfs_rsv_pct", "extfs_rsv_pct"):
Dario Freni5f681e12018-05-29 13:09:01 +0100975 d["extfs_rsv_pct"] = "0"
Yifan Hongebc041a2018-07-26 16:02:52 -0700976 copy_prop("product_services_reserved_size", "partition_reserved_size")
Bowgo Tsaid624fa62017-11-14 23:42:30 +0800977 elif mount_point == "odm":
978 copy_prop("avb_odm_hashtree_enable", "avb_hashtree_enable")
979 copy_prop("avb_odm_add_hashtree_footer_args",
980 "avb_add_hashtree_footer_args")
981 copy_prop("avb_odm_key_path", "avb_key_path")
982 copy_prop("avb_odm_algorithm", "avb_algorithm")
983 copy_prop("odm_fs_type", "fs_type")
984 copy_prop("odm_size", "partition_size")
985 if not copy_prop("odm_journal_size", "journal_size"):
986 d["journal_size"] = "0"
987 copy_prop("odm_verity_block_device", "verity_block_device")
988 copy_prop("odm_squashfs_compressor", "squashfs_compressor")
989 copy_prop("odm_squashfs_compressor_opt", "squashfs_compressor_opt")
990 copy_prop("odm_squashfs_block_size", "squashfs_block_size")
991 copy_prop("odm_squashfs_disable_4k_align", "squashfs_disable_4k_align")
992 copy_prop("odm_base_fs_file", "base_fs_file")
993 copy_prop("odm_extfs_inode_count", "extfs_inode_count")
994 if not copy_prop("odm_extfs_rsv_pct", "extfs_rsv_pct"):
995 d["extfs_rsv_pct"] = "0"
996 copy_prop("odm_reserved_size", "partition_reserved_size")
Ying Wangb8888432014-03-11 17:13:27 -0700997 elif mount_point == "oem":
998 copy_prop("fs_type", "fs_type")
999 copy_prop("oem_size", "partition_size")
Tao Bao332a96b2018-03-31 10:27:35 -07001000 if not copy_prop("oem_journal_size", "journal_size"):
1001 d["journal_size"] = "0"
Patrick Tjina1900842016-10-20 10:58:12 -07001002 copy_prop("oem_extfs_inode_count", "extfs_inode_count")
Patrick Tjin3f5f9932018-03-23 11:36:43 -07001003 if not copy_prop("oem_extfs_rsv_pct", "extfs_rsv_pct"):
1004 d["extfs_rsv_pct"] = "0"
David Zeuthen4014a9d2016-09-30 17:29:22 -04001005 d["partition_name"] = mount_point
Ying Wangbd93d422011-10-28 17:02:30 -07001006 return d
1007
1008
1009def LoadGlobalDict(filename):
1010 """Load "name=value" pairs from filename"""
1011 d = {}
1012 f = open(filename)
1013 for line in f:
1014 line = line.strip()
1015 if not line or line.startswith("#"):
1016 continue
1017 k, v = line.split("=", 1)
1018 d[k] = v
1019 f.close()
1020 return d
1021
1022
Yifan Hongbbcba1e2018-06-18 16:32:35 -07001023def GlobalDictFromImageProp(image_prop, mount_point):
1024 d = {}
1025 def copy_prop(src_p, dest_p):
1026 if src_p in image_prop:
1027 d[dest_p] = image_prop[src_p]
1028 return True
1029 return False
Tao Bao4251fe92018-07-23 13:05:00 -07001030
Yifan Hongbbcba1e2018-06-18 16:32:35 -07001031 if mount_point == "system":
Tao Bao35f4ebc2018-09-27 15:31:11 -07001032 copy_prop("partition_size", "system_size")
Yifan Hongbbcba1e2018-06-18 16:32:35 -07001033 elif mount_point == "system_other":
Tao Bao35f4ebc2018-09-27 15:31:11 -07001034 copy_prop("partition_size", "system_size")
Yifan Hong749062d2018-06-19 16:23:16 -07001035 elif mount_point == "vendor":
Tao Bao35f4ebc2018-09-27 15:31:11 -07001036 copy_prop("partition_size", "vendor_size")
Bowgo Tsaid624fa62017-11-14 23:42:30 +08001037 elif mount_point == "odm":
Tao Bao35f4ebc2018-09-27 15:31:11 -07001038 copy_prop("partition_size", "odm_size")
Yifan Hong56a6c3b2018-07-20 15:19:34 -07001039 elif mount_point == "product":
Tao Bao35f4ebc2018-09-27 15:31:11 -07001040 copy_prop("partition_size", "product_size")
Dario Freni924af7d2018-08-17 00:56:14 +01001041 elif mount_point == "product_services":
Tao Bao35f4ebc2018-09-27 15:31:11 -07001042 copy_prop("partition_size", "product_services_size")
Yifan Hongbbcba1e2018-06-18 16:32:35 -07001043 return d
1044
1045
1046def SaveGlobalDict(filename, glob_dict):
1047 with open(filename, "w") as f:
1048 f.writelines(["%s=%s" % (key, value) for (key, value) in glob_dict.items()])
1049
1050
Ying Wangbd93d422011-10-28 17:02:30 -07001051def main(argv):
Yifan Hongbbcba1e2018-06-18 16:32:35 -07001052 if len(argv) < 4 or len(argv) > 5:
Tao Baoc72727a2017-12-07 10:33:00 -08001053 print(__doc__)
Ying Wangbd93d422011-10-28 17:02:30 -07001054 sys.exit(1)
1055
1056 in_dir = argv[0]
1057 glob_dict_file = argv[1]
1058 out_file = argv[2]
Thierry Strudel74a81e62015-07-09 09:54:55 -07001059 target_out = argv[3]
Yifan Hongbbcba1e2018-06-18 16:32:35 -07001060 prop_file_out = argv[4] if len(argv) >= 5 else None
Ying Wangbd93d422011-10-28 17:02:30 -07001061
1062 glob_dict = LoadGlobalDict(glob_dict_file)
Ying Wangae61f502015-03-12 18:30:39 -07001063 if "mount_point" in glob_dict:
Tao Baoc7a6f1e2015-06-23 11:16:05 -07001064 # The caller knows the mount point and provides a dictionay needed by
1065 # BuildImage().
Ying Wangae61f502015-03-12 18:30:39 -07001066 image_properties = glob_dict
Ying Wang9f8e8db2011-11-04 11:37:01 -07001067 else:
Ying Wangae61f502015-03-12 18:30:39 -07001068 image_filename = os.path.basename(out_file)
1069 mount_point = ""
1070 if image_filename == "system.img":
1071 mount_point = "system"
Alex Light4e358ab2016-06-16 14:47:10 -07001072 elif image_filename == "system_other.img":
1073 mount_point = "system_other"
Ying Wangae61f502015-03-12 18:30:39 -07001074 elif image_filename == "userdata.img":
1075 mount_point = "data"
1076 elif image_filename == "cache.img":
1077 mount_point = "cache"
1078 elif image_filename == "vendor.img":
1079 mount_point = "vendor"
Bowgo Tsaid624fa62017-11-14 23:42:30 +08001080 elif image_filename == "odm.img":
1081 mount_point = "odm"
Ying Wangae61f502015-03-12 18:30:39 -07001082 elif image_filename == "oem.img":
1083 mount_point = "oem"
Jaekyun Seokb7735d82017-11-27 17:04:47 +09001084 elif image_filename == "product.img":
1085 mount_point = "product"
Dario Freni924af7d2018-08-17 00:56:14 +01001086 elif image_filename == "product_services.img":
1087 mount_point = "product_services"
Ying Wangae61f502015-03-12 18:30:39 -07001088 else:
Tao Baoc72727a2017-12-07 10:33:00 -08001089 print("error: unknown image file name ", image_filename, file=sys.stderr)
Tao Bao1c830bf2017-12-25 10:43:47 -08001090 sys.exit(1)
Ying Wangbd93d422011-10-28 17:02:30 -07001091
Ying Wangae61f502015-03-12 18:30:39 -07001092 image_properties = ImagePropFromGlobalDict(glob_dict, mount_point)
1093
Tao Baoc6bd70a2018-09-27 16:58:00 -07001094 try:
1095 BuildImage(in_dir, image_properties, out_file, target_out)
1096 except:
1097 print("Error: Failed to build {} from {}".format(out_file, in_dir),
Tao Baoc72727a2017-12-07 10:33:00 -08001098 file=sys.stderr)
Tao Baoc6bd70a2018-09-27 16:58:00 -07001099 raise
Ying Wangbd93d422011-10-28 17:02:30 -07001100
Yifan Hongbbcba1e2018-06-18 16:32:35 -07001101 if prop_file_out:
1102 glob_dict_out = GlobalDictFromImageProp(image_properties, mount_point)
1103 SaveGlobalDict(prop_file_out, glob_dict_out)
Ying Wangbd93d422011-10-28 17:02:30 -07001104
1105if __name__ == '__main__':
Tao Bao1c830bf2017-12-25 10:43:47 -08001106 try:
1107 main(sys.argv[1:])
1108 finally:
1109 common.Cleanup()