blob: 4e690fe7797b99ffe2ca368f4caad5395ed38e9d [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
Yifan Hongbbcba1e2018-06-18 16:32:35 -070048def RunCommand(cmd, verbose=None, env=None):
Tao Baoc7a6f1e2015-06-23 11:16:05 -070049 """Echo and run the given command.
Ying Wang69e9b4d2012-11-26 18:10:23 -080050
51 Args:
52 cmd: the command represented as a list of strings.
Tianjie Xu149b7fb2017-09-01 15:36:08 -070053 verbose: show commands being executed.
Yifan Hongbbcba1e2018-06-18 16:32:35 -070054 env: a dictionary of additional environment variables.
Ying Wang69e9b4d2012-11-26 18:10:23 -080055 Returns:
Tao Baoc7a6f1e2015-06-23 11:16:05 -070056 A tuple of the output and the exit code.
Ying Wang69e9b4d2012-11-26 18:10:23 -080057 """
Yifan Hongbbcba1e2018-06-18 16:32:35 -070058 env_copy = None
59 if env is not None:
60 env_copy = os.environ.copy()
61 env_copy.update(env)
Tianjie Xu149b7fb2017-09-01 15:36:08 -070062 if verbose is None:
63 verbose = OPTIONS.verbose
64 if verbose:
65 print("Running: " + " ".join(cmd))
Yifan Hongbbcba1e2018-06-18 16:32:35 -070066 p = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.STDOUT,
67 env=env_copy)
Tao Baoc7a6f1e2015-06-23 11:16:05 -070068 output, _ = p.communicate()
Tianjie Xu149b7fb2017-09-01 15:36:08 -070069
70 if verbose:
71 print(output.rstrip())
Tao Baoc7a6f1e2015-06-23 11:16:05 -070072 return (output, p.returncode)
Ying Wangbd93d422011-10-28 17:02:30 -070073
Tao Baoc72727a2017-12-07 10:33:00 -080074
Sami Tolvanenf99b5312015-05-20 07:30:57 +010075def GetVerityFECSize(partition_size):
Tianjie Xue3ad41b2017-03-08 11:05:56 -080076 cmd = ["fec", "-s", str(partition_size)]
Tianjie Xu149b7fb2017-09-01 15:36:08 -070077 output, exit_code = RunCommand(cmd, False)
Tianjie Xue3ad41b2017-03-08 11:05:56 -080078 if exit_code != 0:
Sami Tolvanenf99b5312015-05-20 07:30:57 +010079 return False, 0
80 return True, int(output)
81
Tao Baoc72727a2017-12-07 10:33:00 -080082
Geremy Condrafd6f7512013-06-16 17:26:08 -070083def GetVerityTreeSize(partition_size):
Tianjie Xue3ad41b2017-03-08 11:05:56 -080084 cmd = ["build_verity_tree", "-s", str(partition_size)]
Tianjie Xu149b7fb2017-09-01 15:36:08 -070085 output, exit_code = RunCommand(cmd, False)
Tianjie Xue3ad41b2017-03-08 11:05:56 -080086 if exit_code != 0:
Geremy Condrafd6f7512013-06-16 17:26:08 -070087 return False, 0
88 return True, int(output)
89
Tao Baoc72727a2017-12-07 10:33:00 -080090
Geremy Condrafd6f7512013-06-16 17:26:08 -070091def GetVerityMetadataSize(partition_size):
Tao Baob4ec6d72018-03-15 23:21:28 -070092 cmd = ["build_verity_metadata.py", "size", str(partition_size)]
Tianjie Xu149b7fb2017-09-01 15:36:08 -070093 output, exit_code = RunCommand(cmd, False)
Tianjie Xue3ad41b2017-03-08 11:05:56 -080094 if exit_code != 0:
Geremy Condrafd6f7512013-06-16 17:26:08 -070095 return False, 0
96 return True, int(output)
97
Tao Baoc72727a2017-12-07 10:33:00 -080098
Sami Tolvanenf99b5312015-05-20 07:30:57 +010099def GetVeritySize(partition_size, fec_supported):
100 success, verity_tree_size = GetVerityTreeSize(partition_size)
101 if not success:
102 return 0
103 success, verity_metadata_size = GetVerityMetadataSize(partition_size)
104 if not success:
105 return 0
106 verity_size = verity_tree_size + verity_metadata_size
107 if fec_supported:
108 success, fec_size = GetVerityFECSize(partition_size + verity_size)
109 if not success:
110 return 0
111 return verity_size + fec_size
112 return verity_size
113
Tao Baoc72727a2017-12-07 10:33:00 -0800114
Yifan Hongbbcba1e2018-06-18 16:32:35 -0700115def GetDiskUsage(path):
116 """Return number of bytes that "path" occupies on host.
117
118 Args:
119 path: The directory or file to calculate size on
120 Returns:
121 True and the number of bytes if successful,
122 False and 0 otherwise.
123 """
124 env = {"POSIXLY_CORRECT": "1"}
125 cmd = ["du", "-s", path]
126 output, exit_code = RunCommand(cmd, verbose=False, env=env)
127 if exit_code != 0:
128 return False, 0
129 # POSIX du returns number of blocks with block size 512
130 return True, int(output.split()[0]) * 512
131
132
Sami Tolvanen405e71d2016-02-09 12:28:58 -0800133def GetSimgSize(image_file):
134 simg = sparse_img.SparseImage(image_file, build_map=False)
135 return simg.blocksize * simg.total_blocks
136
Tao Baoc72727a2017-12-07 10:33:00 -0800137
Sami Tolvanen405e71d2016-02-09 12:28:58 -0800138def ZeroPadSimg(image_file, pad_size):
139 blocks = pad_size // BLOCK_SIZE
140 print("Padding %d blocks (%d bytes)" % (blocks, pad_size))
141 simg = sparse_img.SparseImage(image_file, mode="r+b", build_map=False)
142 simg.AppendFillChunk(0, blocks)
143
Tao Baoc72727a2017-12-07 10:33:00 -0800144
Bowgo Tsai7ea994b2017-05-19 23:44:26 +0800145def AVBCalcMaxImageSize(avbtool, footer_type, partition_size, additional_args):
David Zeuthen4014a9d2016-09-30 17:29:22 -0400146 """Calculates max image size for a given partition size.
147
148 Args:
149 avbtool: String with path to avbtool.
Bowgo Tsai7ea994b2017-05-19 23:44:26 +0800150 footer_type: 'hash' or 'hashtree' for generating footer.
David Zeuthen4014a9d2016-09-30 17:29:22 -0400151 partition_size: The size of the partition in question.
152 additional_args: Additional arguments to pass to 'avbtool
153 add_hashtree_image'.
154 Returns:
155 The maximum image size or 0 if an error occurred.
156 """
Tao Baoc72727a2017-12-07 10:33:00 -0800157 cmd = [avbtool, "add_%s_footer" % footer_type,
158 "--partition_size", partition_size, "--calc_max_image_size"]
Bowgo Tsai3e599ea2017-05-26 18:30:04 +0800159 cmd.extend(shlex.split(additional_args))
160
161 (output, exit_code) = RunCommand(cmd)
David Zeuthen4014a9d2016-09-30 17:29:22 -0400162 if exit_code != 0:
163 return 0
164 else:
165 return int(output)
166
Tao Baoc72727a2017-12-07 10:33:00 -0800167
Bowgo Tsai7ea994b2017-05-19 23:44:26 +0800168def AVBAddFooter(image_path, avbtool, footer_type, partition_size,
Tao Bao2b6dfd62017-09-27 17:17:43 -0700169 partition_name, key_path, algorithm, salt,
Bowgo Tsai3e599ea2017-05-26 18:30:04 +0800170 additional_args):
David Zeuthen4014a9d2016-09-30 17:29:22 -0400171 """Adds dm-verity hashtree and AVB metadata to an image.
172
173 Args:
174 image_path: Path to image to modify.
175 avbtool: String with path to avbtool.
Bowgo Tsai7ea994b2017-05-19 23:44:26 +0800176 footer_type: 'hash' or 'hashtree' for generating footer.
David Zeuthen4014a9d2016-09-30 17:29:22 -0400177 partition_size: The size of the partition in question.
178 partition_name: The name of the partition - will be embedded in metadata.
Bowgo Tsai3e599ea2017-05-26 18:30:04 +0800179 key_path: Path to key to use or None.
180 algorithm: Name of algorithm to use or None.
Tao Bao2b6dfd62017-09-27 17:17:43 -0700181 salt: The salt to use (a hexadecimal string) or None.
David Zeuthen4014a9d2016-09-30 17:29:22 -0400182 additional_args: Additional arguments to pass to 'avbtool
Tao Baoc72727a2017-12-07 10:33:00 -0800183 add_hashtree_image'.
184
David Zeuthen4014a9d2016-09-30 17:29:22 -0400185 Returns:
186 True if the operation succeeded.
187 """
Tao Baoc72727a2017-12-07 10:33:00 -0800188 cmd = [avbtool, "add_%s_footer" % footer_type,
189 "--partition_size", partition_size,
190 "--partition_name", partition_name,
191 "--image", image_path]
Bowgo Tsai3e599ea2017-05-26 18:30:04 +0800192
193 if key_path and algorithm:
194 cmd.extend(["--key", key_path, "--algorithm", algorithm])
Tao Bao2b6dfd62017-09-27 17:17:43 -0700195 if salt:
196 cmd.extend(["--salt", salt])
Bowgo Tsai3e599ea2017-05-26 18:30:04 +0800197
198 cmd.extend(shlex.split(additional_args))
199
200 (_, exit_code) = RunCommand(cmd)
David Zeuthen4014a9d2016-09-30 17:29:22 -0400201 return exit_code == 0
202
Tao Baoc72727a2017-12-07 10:33:00 -0800203
Sami Tolvanenf99b5312015-05-20 07:30:57 +0100204def AdjustPartitionSizeForVerity(partition_size, fec_supported):
Geremy Condrafd6f7512013-06-16 17:26:08 -0700205 """Modifies the provided partition size to account for the verity metadata.
206
207 This information is used to size the created image appropriately.
Tao Baoc72727a2017-12-07 10:33:00 -0800208
Geremy Condrafd6f7512013-06-16 17:26:08 -0700209 Args:
210 partition_size: the size of the partition to be verified.
Tao Baoc72727a2017-12-07 10:33:00 -0800211
Geremy Condrafd6f7512013-06-16 17:26:08 -0700212 Returns:
Sami Tolvanen433905f2016-09-01 15:58:35 -0700213 A tuple of the size of the partition adjusted for verity metadata, and
214 the size of verity metadata.
Geremy Condrafd6f7512013-06-16 17:26:08 -0700215 """
Sami Tolvanenf99b5312015-05-20 07:30:57 +0100216 key = "%d %d" % (partition_size, fec_supported)
217 if key in AdjustPartitionSizeForVerity.results:
218 return AdjustPartitionSizeForVerity.results[key]
219
220 hi = partition_size
221 if hi % BLOCK_SIZE != 0:
222 hi = (hi // BLOCK_SIZE) * BLOCK_SIZE
223
224 # verity tree and fec sizes depend on the partition size, which
225 # means this estimate is always going to be unnecessarily small
Sami Tolvanen433905f2016-09-01 15:58:35 -0700226 verity_size = GetVeritySize(hi, fec_supported)
227 lo = partition_size - verity_size
Sami Tolvanenf99b5312015-05-20 07:30:57 +0100228 result = lo
229
230 # do a binary search for the optimal size
231 while lo < hi:
232 i = ((lo + hi) // (2 * BLOCK_SIZE)) * BLOCK_SIZE
Sami Tolvanen433905f2016-09-01 15:58:35 -0700233 v = GetVeritySize(i, fec_supported)
234 if i + v <= partition_size:
Sami Tolvanenf99b5312015-05-20 07:30:57 +0100235 if result < i:
236 result = i
Sami Tolvanen433905f2016-09-01 15:58:35 -0700237 verity_size = v
Sami Tolvanenf99b5312015-05-20 07:30:57 +0100238 lo = i + BLOCK_SIZE
239 else:
240 hi = i
241
Tomasz Wasilczyk29ec06b2017-11-15 10:34:01 -0800242 if OPTIONS.verbose:
243 print("Adjusted partition size for verity, partition_size: {},"
244 " verity_size: {}".format(result, verity_size))
Sami Tolvanen433905f2016-09-01 15:58:35 -0700245 AdjustPartitionSizeForVerity.results[key] = (result, verity_size)
246 return (result, verity_size)
Sami Tolvanenf99b5312015-05-20 07:30:57 +0100247
Tao Baoc72727a2017-12-07 10:33:00 -0800248
Sami Tolvanenf99b5312015-05-20 07:30:57 +0100249AdjustPartitionSizeForVerity.results = {}
250
Tao Baoc72727a2017-12-07 10:33:00 -0800251
Sami Tolvanen433905f2016-09-01 15:58:35 -0700252def BuildVerityFEC(sparse_image_path, verity_path, verity_fec_path,
253 padding_size):
Tianjie Xue3ad41b2017-03-08 11:05:56 -0800254 cmd = ["fec", "-e", "-p", str(padding_size), sparse_image_path,
255 verity_path, verity_fec_path]
256 output, exit_code = RunCommand(cmd)
257 if exit_code != 0:
Tao Baoc72727a2017-12-07 10:33:00 -0800258 print("Could not build FEC data! Error: %s" % output)
Sami Tolvanenf99b5312015-05-20 07:30:57 +0100259 return False
260 return True
Geremy Condrafd6f7512013-06-16 17:26:08 -0700261
Tao Baoc72727a2017-12-07 10:33:00 -0800262
Colin Cross477cf2b2014-04-16 18:49:56 -0700263def BuildVerityTree(sparse_image_path, verity_image_path, prop_dict):
Tianjie Xue3ad41b2017-03-08 11:05:56 -0800264 cmd = ["build_verity_tree", "-A", FIXED_SALT, sparse_image_path,
265 verity_image_path]
266 output, exit_code = RunCommand(cmd)
267 if exit_code != 0:
Tao Baoc72727a2017-12-07 10:33:00 -0800268 print("Could not build verity tree! Error: %s" % output)
Geremy Condrafd6f7512013-06-16 17:26:08 -0700269 return False
270 root, salt = output.split()
271 prop_dict["verity_root_hash"] = root
272 prop_dict["verity_salt"] = salt
273 return True
274
Tao Baoc72727a2017-12-07 10:33:00 -0800275
Geremy Condrafd6f7512013-06-16 17:26:08 -0700276def BuildVerityMetadata(image_size, verity_metadata_path, root_hash, salt,
Bowgo Tsai6ceeb1a2017-10-11 16:21:48 +0800277 block_device, signer_path, key, signer_args,
278 verity_disable):
Tao Baob4ec6d72018-03-15 23:21:28 -0700279 cmd = ["build_verity_metadata.py", "build", str(image_size),
280 verity_metadata_path, root_hash, salt, block_device, signer_path, key]
Tao Bao45810422016-10-17 16:20:12 -0700281 if signer_args:
Tianjie Xue3ad41b2017-03-08 11:05:56 -0800282 cmd.append("--signer_args=\"%s\"" % (' '.join(signer_args),))
Bowgo Tsai6ceeb1a2017-10-11 16:21:48 +0800283 if verity_disable:
284 cmd.append("--verity_disable")
Tianjie Xue3ad41b2017-03-08 11:05:56 -0800285 output, exit_code = RunCommand(cmd)
286 if exit_code != 0:
Tao Baoc72727a2017-12-07 10:33:00 -0800287 print("Could not build verity metadata! Error: %s" % output)
Geremy Condrafd6f7512013-06-16 17:26:08 -0700288 return False
289 return True
290
Tao Baoc72727a2017-12-07 10:33:00 -0800291
Geremy Condrafd6f7512013-06-16 17:26:08 -0700292def Append2Simg(sparse_image_path, unsparse_image_path, error_message):
293 """Appends the unsparse image to the given sparse image.
294
295 Args:
296 sparse_image_path: the path to the (sparse) image
297 unsparse_image_path: the path to the (unsparse) image
298 Returns:
299 True on success, False on failure.
300 """
Tianjie Xue3ad41b2017-03-08 11:05:56 -0800301 cmd = ["append2simg", sparse_image_path, unsparse_image_path]
302 output, exit_code = RunCommand(cmd)
303 if exit_code != 0:
Tao Baoc72727a2017-12-07 10:33:00 -0800304 print("%s: %s" % (error_message, output))
Geremy Condrafd6f7512013-06-16 17:26:08 -0700305 return False
306 return True
307
Tao Baoc72727a2017-12-07 10:33:00 -0800308
Sami Tolvanenff914f52015-12-18 13:24:56 +0000309def Append(target, file_to_append, error_message):
Tao Baoc72727a2017-12-07 10:33:00 -0800310 """Appends file_to_append to target."""
311 try:
312 with open(target, "a") as out_file, open(file_to_append, "r") as input_file:
Tianjie Xue3ad41b2017-03-08 11:05:56 -0800313 for line in input_file:
314 out_file.write(line)
Tao Baoc72727a2017-12-07 10:33:00 -0800315 except IOError:
316 print(error_message)
317 return False
Sami Tolvanenff914f52015-12-18 13:24:56 +0000318 return True
319
Tao Baoc72727a2017-12-07 10:33:00 -0800320
Dan Albert8b72aef2015-03-23 19:13:21 -0700321def BuildVerifiedImage(data_image_path, verity_image_path,
Sami Tolvanen4a060042015-12-18 15:50:25 +0000322 verity_metadata_path, verity_fec_path,
Sami Tolvanen433905f2016-09-01 15:58:35 -0700323 padding_size, fec_supported):
Sami Tolvanenff914f52015-12-18 13:24:56 +0000324 if not Append(verity_image_path, verity_metadata_path,
325 "Could not append verity metadata!"):
Geremy Condrafd6f7512013-06-16 17:26:08 -0700326 return False
Sami Tolvanen4a060042015-12-18 15:50:25 +0000327
328 if fec_supported:
329 # build FEC for the entire partition, including metadata
330 if not BuildVerityFEC(data_image_path, verity_image_path,
Sami Tolvanen433905f2016-09-01 15:58:35 -0700331 verity_fec_path, padding_size):
Sami Tolvanen4a060042015-12-18 15:50:25 +0000332 return False
333
334 if not Append(verity_image_path, verity_fec_path, "Could not append FEC!"):
335 return False
336
Sami Tolvanenff914f52015-12-18 13:24:56 +0000337 if not Append2Simg(data_image_path, verity_image_path,
338 "Could not append verity data!"):
Sami Tolvanenf99b5312015-05-20 07:30:57 +0100339 return False
Geremy Condrafd6f7512013-06-16 17:26:08 -0700340 return True
341
Tao Baoc72727a2017-12-07 10:33:00 -0800342
Geremy Condra6e8f53c2013-12-05 17:09:18 -0800343def UnsparseImage(sparse_image_path, replace=True):
Geremy Condrafd6f7512013-06-16 17:26:08 -0700344 img_dir = os.path.dirname(sparse_image_path)
345 unsparse_image_path = "unsparse_" + os.path.basename(sparse_image_path)
346 unsparse_image_path = os.path.join(img_dir, unsparse_image_path)
347 if os.path.exists(unsparse_image_path):
Geremy Condra6e8f53c2013-12-05 17:09:18 -0800348 if replace:
349 os.unlink(unsparse_image_path)
350 else:
351 return True, unsparse_image_path
Geremy Condrafd6f7512013-06-16 17:26:08 -0700352 inflate_command = ["simg2img", sparse_image_path, unsparse_image_path]
Tao Baocd53a892018-01-19 10:29:52 -0800353 (inflate_output, exit_code) = RunCommand(inflate_command)
Geremy Condrafd6f7512013-06-16 17:26:08 -0700354 if exit_code != 0:
Tao Baocd53a892018-01-19 10:29:52 -0800355 print("Error: '%s' failed with exit code %d:\n%s" % (
356 inflate_command, exit_code, inflate_output))
Geremy Condrafd6f7512013-06-16 17:26:08 -0700357 os.remove(unsparse_image_path)
358 return False, None
359 return True, unsparse_image_path
360
Tao Baoc72727a2017-12-07 10:33:00 -0800361
Sami Tolvanenf99b5312015-05-20 07:30:57 +0100362def MakeVerityEnabledImage(out_file, fec_supported, prop_dict):
Geremy Condrafd6f7512013-06-16 17:26:08 -0700363 """Creates an image that is verifiable using dm-verity.
364
365 Args:
366 out_file: the location to write the verifiable image at
Dan Albert8b72aef2015-03-23 19:13:21 -0700367 prop_dict: a dictionary of properties required for image creation and
368 verification
Geremy Condrafd6f7512013-06-16 17:26:08 -0700369 Returns:
370 True on success, False otherwise.
371 """
372 # get properties
Sami Tolvanen433905f2016-09-01 15:58:35 -0700373 image_size = int(prop_dict["partition_size"])
Geremy Condrafd6f7512013-06-16 17:26:08 -0700374 block_dev = prop_dict["verity_block_device"]
Paul Lawrencea37b2bb2014-11-13 17:54:30 -0800375 signer_key = prop_dict["verity_key"] + ".pk8"
Baligh Uddin601ddea2015-06-09 15:48:14 -0700376 if OPTIONS.verity_signer_path is not None:
Tao Bao45810422016-10-17 16:20:12 -0700377 signer_path = OPTIONS.verity_signer_path
Baligh Uddin601ddea2015-06-09 15:48:14 -0700378 else:
379 signer_path = prop_dict["verity_signer_cmd"]
Tao Bao45810422016-10-17 16:20:12 -0700380 signer_args = OPTIONS.verity_signer_args
Geremy Condrafd6f7512013-06-16 17:26:08 -0700381
382 # make a tempdir
Tao Bao1c830bf2017-12-25 10:43:47 -0800383 tempdir_name = common.MakeTempDir(suffix="_verity_images")
Geremy Condrafd6f7512013-06-16 17:26:08 -0700384
385 # get partial image paths
386 verity_image_path = os.path.join(tempdir_name, "verity.img")
387 verity_metadata_path = os.path.join(tempdir_name, "verity_metadata.img")
Sami Tolvanenf99b5312015-05-20 07:30:57 +0100388 verity_fec_path = os.path.join(tempdir_name, "verity_fec.img")
Geremy Condrafd6f7512013-06-16 17:26:08 -0700389
390 # build the verity tree and get the root hash and salt
Colin Cross477cf2b2014-04-16 18:49:56 -0700391 if not BuildVerityTree(out_file, verity_image_path, prop_dict):
Geremy Condrafd6f7512013-06-16 17:26:08 -0700392 return False
393
394 # build the metadata blocks
395 root_hash = prop_dict["verity_root_hash"]
396 salt = prop_dict["verity_salt"]
Bowgo Tsai6ceeb1a2017-10-11 16:21:48 +0800397 verity_disable = "verity_disable" in prop_dict
Dan Albert8b72aef2015-03-23 19:13:21 -0700398 if not BuildVerityMetadata(image_size, verity_metadata_path, root_hash, salt,
Bowgo Tsai6ceeb1a2017-10-11 16:21:48 +0800399 block_dev, signer_path, signer_key, signer_args,
400 verity_disable):
Geremy Condrafd6f7512013-06-16 17:26:08 -0700401 return False
402
403 # build the full verified image
Sami Tolvanen433905f2016-09-01 15:58:35 -0700404 target_size = int(prop_dict["original_partition_size"])
405 verity_size = int(prop_dict["verity_size"])
406
407 padding_size = target_size - image_size - verity_size
408 assert padding_size >= 0
409
Geremy Condrafd6f7512013-06-16 17:26:08 -0700410 if not BuildVerifiedImage(out_file,
411 verity_image_path,
Sami Tolvanen4a060042015-12-18 15:50:25 +0000412 verity_metadata_path,
413 verity_fec_path,
Sami Tolvanen433905f2016-09-01 15:58:35 -0700414 padding_size,
Sami Tolvanen4a060042015-12-18 15:50:25 +0000415 fec_supported):
Geremy Condrafd6f7512013-06-16 17:26:08 -0700416 return False
417
Geremy Condrafd6f7512013-06-16 17:26:08 -0700418 return True
419
Tao Baoc72727a2017-12-07 10:33:00 -0800420
Mohamad Ayyashf8765552016-03-02 21:07:23 -0800421def ConvertBlockMapToBaseFs(block_map_file):
Tao Bao1c830bf2017-12-25 10:43:47 -0800422 base_fs_file = common.MakeTempFile(prefix="script_gen_", suffix=".base_fs")
Mohamad Ayyashf8765552016-03-02 21:07:23 -0800423 convert_command = ["blk_alloc_to_base_fs", block_map_file, base_fs_file]
424 (_, exit_code) = RunCommand(convert_command)
Tao Baoc72727a2017-12-07 10:33:00 -0800425 return base_fs_file if exit_code == 0 else None
Mohamad Ayyashf8765552016-03-02 21:07:23 -0800426
Tao Baod4349f22017-12-07 23:01:25 -0800427
428def CheckHeadroom(ext4fs_output, prop_dict):
429 """Checks if there's enough headroom space available.
430
431 Headroom is the reserved space on system image (via PRODUCT_SYSTEM_HEADROOM),
432 which is useful for devices with low disk space that have system image
433 variation between builds. The 'partition_headroom' in prop_dict is the size
434 in bytes, while the numbers in 'ext4fs_output' are for 4K-blocks.
435
436 Args:
437 ext4fs_output: The output string from mke2fs command.
438 prop_dict: The property dict.
439
440 Returns:
441 The check result.
Tao Baod8a953d2018-01-02 21:19:27 -0800442
443 Raises:
444 AssertionError: On invalid input.
Tao Baod4349f22017-12-07 23:01:25 -0800445 """
Tao Baod8a953d2018-01-02 21:19:27 -0800446 assert ext4fs_output is not None
447 assert prop_dict.get('fs_type', '').startswith('ext4')
448 assert 'partition_headroom' in prop_dict
449 assert 'mount_point' in prop_dict
450
Tao Baod4349f22017-12-07 23:01:25 -0800451 ext4fs_stats = re.compile(
452 r'Created filesystem with .* (?P<used_blocks>[0-9]+)/'
453 r'(?P<total_blocks>[0-9]+) blocks')
Tao Baoc72727a2017-12-07 10:33:00 -0800454 last_line = ext4fs_output.strip().split('\n')[-1]
455 m = ext4fs_stats.match(last_line)
Tao Baod4349f22017-12-07 23:01:25 -0800456 used_blocks = int(m.groupdict().get('used_blocks'))
457 total_blocks = int(m.groupdict().get('total_blocks'))
Tao Baod8a953d2018-01-02 21:19:27 -0800458 headroom_blocks = int(prop_dict['partition_headroom']) / BLOCK_SIZE
Tao Baod4349f22017-12-07 23:01:25 -0800459 adjusted_blocks = total_blocks - headroom_blocks
460 if used_blocks > adjusted_blocks:
Tao Baod8a953d2018-01-02 21:19:27 -0800461 mount_point = prop_dict["mount_point"]
Tao Baod4349f22017-12-07 23:01:25 -0800462 print("Error: Not enough room on %s (total: %d blocks, used: %d blocks, "
463 "headroom: %d blocks, available: %d blocks)" % (
464 mount_point, total_blocks, used_blocks, headroom_blocks,
465 adjusted_blocks))
466 return False
467 return True
468
469
Thierry Strudel74a81e62015-07-09 09:54:55 -0700470def BuildImage(in_dir, prop_dict, out_file, target_out=None):
Ying Wangbd93d422011-10-28 17:02:30 -0700471 """Build an image to out_file from in_dir with property prop_dict.
Yifan Hongbbcba1e2018-06-18 16:32:35 -0700472 After the function call, values in prop_dict is updated with
473 computed values.
Ying Wangbd93d422011-10-28 17:02:30 -0700474
475 Args:
476 in_dir: path of input directory.
477 prop_dict: property dictionary.
478 out_file: path of the output image file.
Tao Baoc72727a2017-12-07 10:33:00 -0800479 target_out: path of the product out directory to read device specific FS
480 config files.
Ying Wangbd93d422011-10-28 17:02:30 -0700481
482 Returns:
483 True iff the image is built successfully.
484 """
Tao Baof3282b42015-04-01 11:21:55 -0700485 # system_root_image=true: build a system.img that combines the contents of
486 # /system and the ramdisk, and can be mounted at the root of the file system.
Ying Wanga2292c92015-03-24 19:07:40 -0700487 origin_in = in_dir
488 fs_config = prop_dict.get("fs_config")
Tao Baoc72727a2017-12-07 10:33:00 -0800489 if (prop_dict.get("system_root_image") == "true" and
490 prop_dict["mount_point"] == "system"):
Tao Bao1c830bf2017-12-25 10:43:47 -0800491 in_dir = common.MakeTempDir()
Tao Baoc72727a2017-12-07 10:33:00 -0800492 # Change the mount point to "/".
Ying Wanga2292c92015-03-24 19:07:40 -0700493 prop_dict["mount_point"] = "/"
494 if fs_config:
495 # We need to merge the fs_config files of system and ramdisk.
Tao Bao1c830bf2017-12-25 10:43:47 -0800496 merged_fs_config = common.MakeTempFile(prefix="root_fs_config",
497 suffix=".txt")
Ying Wanga2292c92015-03-24 19:07:40 -0700498 with open(merged_fs_config, "w") as fw:
499 if "ramdisk_fs_config" in prop_dict:
500 with open(prop_dict["ramdisk_fs_config"]) as fr:
501 fw.writelines(fr.readlines())
502 with open(fs_config) as fr:
503 fw.writelines(fr.readlines())
504 fs_config = merged_fs_config
505
Ying Wangbd93d422011-10-28 17:02:30 -0700506 build_command = []
507 fs_type = prop_dict.get("fs_type", "")
Tao Baoc72727a2017-12-07 10:33:00 -0800508 run_e2fsck = False
Geremy Condrafd6f7512013-06-16 17:26:08 -0700509
Mohamad Ayyashdd063522015-03-24 12:42:03 -0700510 fs_spans_partition = True
511 if fs_type.startswith("squash"):
Tao Baoc7a6f1e2015-06-23 11:16:05 -0700512 fs_spans_partition = False
Mohamad Ayyashdd063522015-03-24 12:42:03 -0700513
Daniel Rosenbergf4eabc32014-07-10 15:42:38 -0700514 is_verity_partition = "verity_block_device" in prop_dict
Geremy Condra5b5f4952014-05-05 22:19:37 -0700515 verity_supported = prop_dict.get("verity") == "true"
Sami Tolvanenf99b5312015-05-20 07:30:57 +0100516 verity_fec_supported = prop_dict.get("verity_fec") == "true"
517
Yifan Hongbbcba1e2018-06-18 16:32:35 -0700518 if (prop_dict.get("use_logical_partitions") == "true" and
519 "partition_size" not in prop_dict):
520 # if partition_size is not defined, use output of `du' + reserved_size
521 success, size = GetDiskUsage(origin_in)
522 if not success:
523 return False
524 if OPTIONS.verbose:
525 print("The tree size of %s is %d MB." % (origin_in, size // BYTES_IN_MB))
526 size += int(prop_dict.get("partition_reserved_size", 0))
527 # Round this up to a multiple of 4K so that avbtool works
528 size = common.RoundUpTo4K(size)
529 prop_dict["partition_size"] = str(size)
530 if OPTIONS.verbose:
531 print("Allocating %d MB for %s." % (size // BYTES_IN_MB, out_file))
532
Tao Baoc7a6f1e2015-06-23 11:16:05 -0700533 # Adjust the partition size to make room for the hashes if this is to be
534 # verified.
Sami Tolvanen405e71d2016-02-09 12:28:58 -0800535 if verity_supported and is_verity_partition:
Geremy Condrafd6f7512013-06-16 17:26:08 -0700536 partition_size = int(prop_dict.get("partition_size"))
Tao Baoc72727a2017-12-07 10:33:00 -0800537 (adjusted_size, verity_size) = AdjustPartitionSizeForVerity(
538 partition_size, verity_fec_supported)
Geremy Condrafd6f7512013-06-16 17:26:08 -0700539 if not adjusted_size:
540 return False
541 prop_dict["partition_size"] = str(adjusted_size)
542 prop_dict["original_partition_size"] = str(partition_size)
Sami Tolvanen433905f2016-09-01 15:58:35 -0700543 prop_dict["verity_size"] = str(verity_size)
Geremy Condrafd6f7512013-06-16 17:26:08 -0700544
Bowgo Tsai7ea994b2017-05-19 23:44:26 +0800545 # Adjust partition size for AVB hash footer or AVB hashtree footer.
546 avb_footer_type = ''
547 if prop_dict.get("avb_hash_enable") == "true":
548 avb_footer_type = 'hash'
549 elif prop_dict.get("avb_hashtree_enable") == "true":
550 avb_footer_type = 'hashtree'
551
552 if avb_footer_type:
Bowgo Tsai3e599ea2017-05-26 18:30:04 +0800553 avbtool = prop_dict["avb_avbtool"]
554 partition_size = prop_dict["partition_size"]
Bowgo Tsai7ea994b2017-05-19 23:44:26 +0800555 # avb_add_hash_footer_args or avb_add_hashtree_footer_args.
556 additional_args = prop_dict["avb_add_" + avb_footer_type + "_footer_args"]
Tao Baoc72727a2017-12-07 10:33:00 -0800557 max_image_size = AVBCalcMaxImageSize(avbtool, avb_footer_type,
558 partition_size, additional_args)
David Zeuthen4014a9d2016-09-30 17:29:22 -0400559 if max_image_size == 0:
560 return False
561 prop_dict["partition_size"] = str(max_image_size)
Bowgo Tsai3e599ea2017-05-26 18:30:04 +0800562 prop_dict["original_partition_size"] = partition_size
David Zeuthen4014a9d2016-09-30 17:29:22 -0400563
Ying Wangbd93d422011-10-28 17:02:30 -0700564 if fs_type.startswith("ext"):
Adrien Schildknecht9a072cc2016-11-18 17:06:29 -0800565 build_command = [prop_dict["ext_mkuserimg"]]
Ying Wangbd93d422011-10-28 17:02:30 -0700566 if "extfs_sparse_flag" in prop_dict:
567 build_command.append(prop_dict["extfs_sparse_flag"])
Tao Baoc72727a2017-12-07 10:33:00 -0800568 run_e2fsck = True
Ying Wangbd93d422011-10-28 17:02:30 -0700569 build_command.extend([in_dir, out_file, fs_type,
570 prop_dict["mount_point"]])
Doug Zongker850b8072013-12-05 15:54:55 -0800571 build_command.append(prop_dict["partition_size"])
Ying Wangf3b86352014-11-18 18:03:13 -0800572 if "journal_size" in prop_dict:
573 build_command.extend(["-j", prop_dict["journal_size"]])
Doug Zongker850b8072013-12-05 15:54:55 -0800574 if "timestamp" in prop_dict:
575 build_command.extend(["-T", str(prop_dict["timestamp"])])
Ying Wanga2292c92015-03-24 19:07:40 -0700576 if fs_config:
Doug Zongker82822822014-06-16 09:10:55 -0700577 build_command.extend(["-C", fs_config])
Thierry Strudel74a81e62015-07-09 09:54:55 -0700578 if target_out:
579 build_command.extend(["-D", target_out])
Ying Wanga2292c92015-03-24 19:07:40 -0700580 if "block_list" in prop_dict:
581 build_command.extend(["-B", prop_dict["block_list"]])
Mohamad Ayyashf8765552016-03-02 21:07:23 -0800582 if "base_fs_file" in prop_dict:
583 base_fs_file = ConvertBlockMapToBaseFs(prop_dict["base_fs_file"])
584 if base_fs_file is None:
585 return False
586 build_command.extend(["-d", base_fs_file])
Christoffer Dall8ed01f32014-12-17 21:34:12 +0100587 build_command.extend(["-L", prop_dict["mount_point"]])
Patrick Tjina1900842016-10-20 10:58:12 -0700588 if "extfs_inode_count" in prop_dict:
589 build_command.extend(["-i", prop_dict["extfs_inode_count"]])
Patrick Tjin3f5f9932018-03-23 11:36:43 -0700590 if "extfs_rsv_pct" in prop_dict:
591 build_command.extend(["-M", prop_dict["extfs_rsv_pct"]])
Connor O'Brien20f08c32017-01-05 16:48:14 -0800592 if "flash_erase_block_size" in prop_dict:
593 build_command.extend(["-e", prop_dict["flash_erase_block_size"]])
594 if "flash_logical_block_size" in prop_dict:
595 build_command.extend(["-o", prop_dict["flash_logical_block_size"]])
Tao Baod86e3112017-09-22 15:45:33 -0700596 # Specify UUID and hash_seed if using mke2fs.
597 if prop_dict["ext_mkuserimg"] == "mkuserimg_mke2fs.sh":
598 if "uuid" in prop_dict:
599 build_command.extend(["-U", prop_dict["uuid"]])
600 if "hash_seed" in prop_dict:
601 build_command.extend(["-S", prop_dict["hash_seed"]])
Jin Qianfde9f792018-01-22 13:15:46 -0800602 if "ext4_share_dup_blocks" in prop_dict:
603 build_command.append("-c")
Ying Wanga2292c92015-03-24 19:07:40 -0700604 if "selinux_fc" in prop_dict:
Kenny Rootf32dc712012-04-08 10:42:34 -0700605 build_command.append(prop_dict["selinux_fc"])
Mohamad Ayyashb97746e2015-03-03 12:30:37 -0800606 elif fs_type.startswith("squash"):
607 build_command = ["mksquashfsimage.sh"]
608 build_command.extend([in_dir, out_file])
Todd Poynorb2a555e2015-12-15 18:00:14 -0800609 if "squashfs_sparse_flag" in prop_dict:
610 build_command.extend([prop_dict["squashfs_sparse_flag"]])
Mohamad Ayyashb97746e2015-03-03 12:30:37 -0800611 build_command.extend(["-m", prop_dict["mount_point"]])
Thierry Strudel74a81e62015-07-09 09:54:55 -0700612 if target_out:
613 build_command.extend(["-d", target_out])
Mohamad Ayyash88378822016-04-07 22:10:51 -0700614 if fs_config:
615 build_command.extend(["-C", fs_config])
Ying Wanga2292c92015-03-24 19:07:40 -0700616 if "selinux_fc" in prop_dict:
Mohamad Ayyashb97746e2015-03-03 12:30:37 -0800617 build_command.extend(["-c", prop_dict["selinux_fc"]])
Mohamad Ayyashc3484f72016-06-13 09:46:58 -0700618 if "block_list" in prop_dict:
619 build_command.extend(["-B", prop_dict["block_list"]])
Ng Zhi An9446c1d2018-01-19 15:51:46 -0800620 if "squashfs_block_size" in prop_dict:
621 build_command.extend(["-b", prop_dict["squashfs_block_size"]])
Simon Wilsonf86e7ee2015-06-17 12:35:15 -0700622 if "squashfs_compressor" in prop_dict:
623 build_command.extend(["-z", prop_dict["squashfs_compressor"]])
624 if "squashfs_compressor_opt" in prop_dict:
625 build_command.extend(["-zo", prop_dict["squashfs_compressor_opt"]])
Tao Baoc72727a2017-12-07 10:33:00 -0800626 if prop_dict.get("squashfs_disable_4k_align") == "true":
Mohamad Ayyash1b6d3482016-06-15 15:53:07 -0700627 build_command.extend(["-a"])
JP Abgrall5bfed5a2014-06-16 14:17:40 -0700628 elif fs_type.startswith("f2fs"):
629 build_command = ["mkf2fsuserimg.sh"]
630 build_command.extend([out_file, prop_dict["partition_size"]])
Jaegeuk Kim2ea1eba2017-11-28 19:21:28 -0800631 if fs_config:
632 build_command.extend(["-C", fs_config])
633 build_command.extend(["-f", in_dir])
634 if target_out:
635 build_command.extend(["-D", target_out])
636 if "selinux_fc" in prop_dict:
637 build_command.extend(["-s", prop_dict["selinux_fc"]])
638 build_command.extend(["-t", prop_dict["mount_point"]])
639 if "timestamp" in prop_dict:
640 build_command.extend(["-T", str(prop_dict["timestamp"])])
641 build_command.extend(["-L", prop_dict["mount_point"]])
Ying Wangbd93d422011-10-28 17:02:30 -0700642 else:
Elliott Hughes305b0882016-06-15 17:04:54 -0700643 print("Error: unknown filesystem type '%s'" % (fs_type))
644 return False
Ying Wangbd93d422011-10-28 17:02:30 -0700645
Ying Wanga2292c92015-03-24 19:07:40 -0700646 if in_dir != origin_in:
647 # Construct a staging directory of the root file system.
648 ramdisk_dir = prop_dict.get("ramdisk_dir")
649 if ramdisk_dir:
650 shutil.rmtree(in_dir)
651 shutil.copytree(ramdisk_dir, in_dir, symlinks=True)
652 staging_system = os.path.join(in_dir, "system")
653 shutil.rmtree(staging_system, ignore_errors=True)
654 shutil.copytree(origin_in, staging_system, symlinks=True)
Tao Baoc7a6f1e2015-06-23 11:16:05 -0700655
Tao Baoc72727a2017-12-07 10:33:00 -0800656 (mkfs_output, exit_code) = RunCommand(build_command)
Ying Wang69e9b4d2012-11-26 18:10:23 -0800657 if exit_code != 0:
Tao Baocd53a892018-01-19 10:29:52 -0800658 print("Error: '%s' failed with exit code %d:\n%s" % (
659 build_command, exit_code, mkfs_output))
Yifan Hongbbcba1e2018-06-18 16:32:35 -0700660 success, du = GetDiskUsage(origin_in)
661 du_str = ("%d bytes (%d MB)" % (du, du // BYTES_IN_MB)
662 ) if success else "unknown"
663 print("Out of space? The tree size of %s is %s.\n" % (
664 origin_in, du_str))
665 print("The max is %d bytes (%d MB).\n" % (
666 int(prop_dict["partition_size"]),
667 int(prop_dict["partition_size"]) // BYTES_IN_MB))
668 print("Reserved space is %d bytes (%d MB).\n" % (
669 int(prop_dict.get("partition_reserved_size", 0)),
670 int(prop_dict.get("partition_reserved_size", 0)) // BYTES_IN_MB))
Ying Wang69e9b4d2012-11-26 18:10:23 -0800671 return False
672
Tao Baod4349f22017-12-07 23:01:25 -0800673 # Check if there's enough headroom space available for ext4 image.
Tao Bao79d52f82017-12-07 14:07:44 -0800674 if "partition_headroom" in prop_dict and fs_type.startswith("ext4"):
Tao Baoc72727a2017-12-07 10:33:00 -0800675 if not CheckHeadroom(mkfs_output, prop_dict):
Tao Baoc7a6f1e2015-06-23 11:16:05 -0700676 return False
677
Mohamad Ayyashdd063522015-03-24 12:42:03 -0700678 if not fs_spans_partition:
679 mount_point = prop_dict.get("mount_point")
680 partition_size = int(prop_dict.get("partition_size"))
Sami Tolvanen405e71d2016-02-09 12:28:58 -0800681 image_size = GetSimgSize(out_file)
Mohamad Ayyashdd063522015-03-24 12:42:03 -0700682 if image_size > partition_size:
Tao Baoc7a6f1e2015-06-23 11:16:05 -0700683 print("Error: %s image size of %d is larger than partition size of "
684 "%d" % (mount_point, image_size, partition_size))
685 return False
Mohamad Ayyashdd063522015-03-24 12:42:03 -0700686 if verity_supported and is_verity_partition:
Sami Tolvanen405e71d2016-02-09 12:28:58 -0800687 ZeroPadSimg(out_file, partition_size - image_size)
Mohamad Ayyashdd063522015-03-24 12:42:03 -0700688
Tao Baoc72727a2017-12-07 10:33:00 -0800689 # Create the verified image if this is to be verified.
Geremy Condra5b5f4952014-05-05 22:19:37 -0700690 if verity_supported and is_verity_partition:
Sami Tolvanenf99b5312015-05-20 07:30:57 +0100691 if not MakeVerityEnabledImage(out_file, verity_fec_supported, prop_dict):
Geremy Condrafd6f7512013-06-16 17:26:08 -0700692 return False
693
Bowgo Tsai7ea994b2017-05-19 23:44:26 +0800694 # Add AVB HASH or HASHTREE footer (metadata).
695 if avb_footer_type:
Bowgo Tsai3e599ea2017-05-26 18:30:04 +0800696 avbtool = prop_dict["avb_avbtool"]
697 original_partition_size = prop_dict["original_partition_size"]
David Zeuthen4014a9d2016-09-30 17:29:22 -0400698 partition_name = prop_dict["partition_name"]
Bowgo Tsai3e599ea2017-05-26 18:30:04 +0800699 # key_path and algorithm are only available when chain partition is used.
700 key_path = prop_dict.get("avb_key_path")
701 algorithm = prop_dict.get("avb_algorithm")
Tao Bao2b6dfd62017-09-27 17:17:43 -0700702 salt = prop_dict.get("avb_salt")
Bowgo Tsai7ea994b2017-05-19 23:44:26 +0800703 # avb_add_hash_footer_args or avb_add_hashtree_footer_args
704 additional_args = prop_dict["avb_add_" + avb_footer_type + "_footer_args"]
Tao Baoc72727a2017-12-07 10:33:00 -0800705 if not AVBAddFooter(out_file, avbtool, avb_footer_type,
706 original_partition_size, partition_name, key_path,
707 algorithm, salt, additional_args):
David Zeuthen4014a9d2016-09-30 17:29:22 -0400708 return False
709
Tao Baoc72727a2017-12-07 10:33:00 -0800710 if run_e2fsck and prop_dict.get("skip_fsck") != "true":
Geremy Condra6e8f53c2013-12-05 17:09:18 -0800711 success, unsparse_image = UnsparseImage(out_file, replace=False)
Geremy Condrafd6f7512013-06-16 17:26:08 -0700712 if not success:
Ying Wang69e9b4d2012-11-26 18:10:23 -0800713 return False
714
715 # Run e2fsck on the inflated image file
716 e2fsck_command = ["e2fsck", "-f", "-n", unsparse_image]
Tao Baocd53a892018-01-19 10:29:52 -0800717 (e2fsck_output, exit_code) = RunCommand(e2fsck_command)
Ying Wang69e9b4d2012-11-26 18:10:23 -0800718
719 os.remove(unsparse_image)
720
Elliott Hughes73ff57f2017-12-06 12:16:39 -0800721 if exit_code != 0:
Tao Baocd53a892018-01-19 10:29:52 -0800722 print("Error: '%s' failed with exit code %d:\n%s" % (
723 e2fsck_command, exit_code, e2fsck_output))
Elliott Hughes73ff57f2017-12-06 12:16:39 -0800724 return False
725
726 return True
Ying Wangbd93d422011-10-28 17:02:30 -0700727
728
729def ImagePropFromGlobalDict(glob_dict, mount_point):
730 """Build an image property dictionary from the global dictionary.
731
732 Args:
733 glob_dict: the global dictionary from the build system.
734 mount_point: such as "system", "data" etc.
735 """
Doug Zongker1ad7ade2013-12-06 11:53:27 -0800736 d = {}
Tao Bao052ae352015-09-28 13:44:13 -0700737
Tao Bao822f5842015-09-30 16:01:14 -0700738 if "build.prop" in glob_dict:
739 bp = glob_dict["build.prop"]
740 if "ro.build.date.utc" in bp:
741 d["timestamp"] = bp["ro.build.date.utc"]
Ying Wang9f8e8db2011-11-04 11:37:01 -0700742
743 def copy_prop(src_p, dest_p):
Patrick Tjin3f5f9932018-03-23 11:36:43 -0700744 """Copy a property from the global dictionary.
745
746 Args:
747 src_p: The source property in the global dictionary.
748 dest_p: The destination property.
749 Returns:
750 True if property was found and copied, False otherwise.
751 """
Ying Wang9f8e8db2011-11-04 11:37:01 -0700752 if src_p in glob_dict:
753 d[dest_p] = str(glob_dict[src_p])
Patrick Tjin3f5f9932018-03-23 11:36:43 -0700754 return True
755 return False
Ying Wang9f8e8db2011-11-04 11:37:01 -0700756
Ying Wangbd93d422011-10-28 17:02:30 -0700757 common_props = (
Ying Wangbd93d422011-10-28 17:02:30 -0700758 "extfs_sparse_flag",
Todd Poynorb2a555e2015-12-15 18:00:14 -0800759 "squashfs_sparse_flag",
Kenny Rootf32dc712012-04-08 10:42:34 -0700760 "selinux_fc",
Ying Wang6a42a252013-02-27 13:54:02 -0800761 "skip_fsck",
Adrien Schildknecht9a072cc2016-11-18 17:06:29 -0800762 "ext_mkuserimg",
Geremy Condrafd6f7512013-06-16 17:26:08 -0700763 "verity",
Geremy Condrafd6f7512013-06-16 17:26:08 -0700764 "verity_key",
Sami Tolvanenf99b5312015-05-20 07:30:57 +0100765 "verity_signer_cmd",
David Zeuthen4014a9d2016-09-30 17:29:22 -0400766 "verity_fec",
Bowgo Tsai6ceeb1a2017-10-11 16:21:48 +0800767 "verity_disable",
Bowgo Tsai3e599ea2017-05-26 18:30:04 +0800768 "avb_enable",
Tao Bao2b6dfd62017-09-27 17:17:43 -0700769 "avb_avbtool",
770 "avb_salt",
Yifan Hongbbcba1e2018-06-18 16:32:35 -0700771 "use_logical_partitions",
Tao Bao2b6dfd62017-09-27 17:17:43 -0700772 )
Ying Wangbd93d422011-10-28 17:02:30 -0700773 for p in common_props:
Ying Wang9f8e8db2011-11-04 11:37:01 -0700774 copy_prop(p, p)
Ying Wangbd93d422011-10-28 17:02:30 -0700775
776 d["mount_point"] = mount_point
777 if mount_point == "system":
Bowgo Tsai3e599ea2017-05-26 18:30:04 +0800778 copy_prop("avb_system_hashtree_enable", "avb_hashtree_enable")
779 copy_prop("avb_system_add_hashtree_footer_args",
780 "avb_add_hashtree_footer_args")
781 copy_prop("avb_system_key_path", "avb_key_path")
782 copy_prop("avb_system_algorithm", "avb_algorithm")
Ying Wang9f8e8db2011-11-04 11:37:01 -0700783 copy_prop("fs_type", "fs_type")
Julius D'souza001c6762017-05-03 13:43:27 -0700784 # Copy the generic system fs type first, override with specific one if
Dan Albert8b72aef2015-03-23 19:13:21 -0700785 # available.
Mohamad Ayyashb97746e2015-03-03 12:30:37 -0800786 copy_prop("system_fs_type", "fs_type")
Julius D'souza001c6762017-05-03 13:43:27 -0700787 copy_prop("system_headroom", "partition_headroom")
Ying Wang9f8e8db2011-11-04 11:37:01 -0700788 copy_prop("system_size", "partition_size")
Tao Bao332a96b2018-03-31 10:27:35 -0700789 if not copy_prop("system_journal_size", "journal_size"):
790 d["journal_size"] = "0"
Daniel Rosenbergf4eabc32014-07-10 15:42:38 -0700791 copy_prop("system_verity_block_device", "verity_block_device")
Tao Baof3282b42015-04-01 11:21:55 -0700792 copy_prop("system_root_image", "system_root_image")
793 copy_prop("ramdisk_dir", "ramdisk_dir")
Tao Bao84e75682015-07-19 02:38:53 -0700794 copy_prop("ramdisk_fs_config", "ramdisk_fs_config")
Jin Qianfde9f792018-01-22 13:15:46 -0800795 copy_prop("ext4_share_dup_blocks", "ext4_share_dup_blocks")
Simon Wilsonf86e7ee2015-06-17 12:35:15 -0700796 copy_prop("system_squashfs_compressor", "squashfs_compressor")
797 copy_prop("system_squashfs_compressor_opt", "squashfs_compressor_opt")
Mohamad Ayyashdfec8152016-05-24 12:59:30 -0700798 copy_prop("system_squashfs_block_size", "squashfs_block_size")
Mohamad Ayyash1b6d3482016-06-15 15:53:07 -0700799 copy_prop("system_squashfs_disable_4k_align", "squashfs_disable_4k_align")
Mohamad Ayyashf8765552016-03-02 21:07:23 -0800800 copy_prop("system_base_fs_file", "base_fs_file")
Patrick Tjina1900842016-10-20 10:58:12 -0700801 copy_prop("system_extfs_inode_count", "extfs_inode_count")
Patrick Tjin3f5f9932018-03-23 11:36:43 -0700802 if not copy_prop("system_extfs_rsv_pct", "extfs_rsv_pct"):
803 d["extfs_rsv_pct"] = "0"
Yifan Hongbbcba1e2018-06-18 16:32:35 -0700804 copy_prop("system_reserved_size", "partition_reserved_size")
Alex Light4e358ab2016-06-16 14:47:10 -0700805 elif mount_point == "system_other":
Tao Baoc72727a2017-12-07 10:33:00 -0800806 # We inherit the selinux policies of /system since we contain some of its
807 # files.
Alex Light4e358ab2016-06-16 14:47:10 -0700808 d["mount_point"] = "system"
Bowgo Tsai3e599ea2017-05-26 18:30:04 +0800809 copy_prop("avb_system_hashtree_enable", "avb_hashtree_enable")
810 copy_prop("avb_system_add_hashtree_footer_args",
811 "avb_add_hashtree_footer_args")
812 copy_prop("avb_system_key_path", "avb_key_path")
813 copy_prop("avb_system_algorithm", "avb_algorithm")
Alex Light4e358ab2016-06-16 14:47:10 -0700814 copy_prop("fs_type", "fs_type")
815 copy_prop("system_fs_type", "fs_type")
816 copy_prop("system_size", "partition_size")
Tao Bao332a96b2018-03-31 10:27:35 -0700817 if not copy_prop("system_journal_size", "journal_size"):
818 d["journal_size"] = "0"
Alex Light4e358ab2016-06-16 14:47:10 -0700819 copy_prop("system_verity_block_device", "verity_block_device")
Alex Light4e358ab2016-06-16 14:47:10 -0700820 copy_prop("system_squashfs_compressor", "squashfs_compressor")
821 copy_prop("system_squashfs_compressor_opt", "squashfs_compressor_opt")
822 copy_prop("system_squashfs_block_size", "squashfs_block_size")
823 copy_prop("system_base_fs_file", "base_fs_file")
Patrick Tjina1900842016-10-20 10:58:12 -0700824 copy_prop("system_extfs_inode_count", "extfs_inode_count")
Patrick Tjin3f5f9932018-03-23 11:36:43 -0700825 if not copy_prop("system_extfs_rsv_pct", "extfs_rsv_pct"):
826 d["extfs_rsv_pct"] = "0"
Yifan Hongbbcba1e2018-06-18 16:32:35 -0700827 copy_prop("system_reserved_size", "partition_reserved_size")
Ying Wangbd93d422011-10-28 17:02:30 -0700828 elif mount_point == "data":
JP Abgrall5bfed5a2014-06-16 14:17:40 -0700829 # Copy the generic fs type first, override with specific one if available.
Ying Wang9f8e8db2011-11-04 11:37:01 -0700830 copy_prop("fs_type", "fs_type")
JP Abgrall5bfed5a2014-06-16 14:17:40 -0700831 copy_prop("userdata_fs_type", "fs_type")
Ying Wang9f8e8db2011-11-04 11:37:01 -0700832 copy_prop("userdata_size", "partition_size")
Tao Baoc72727a2017-12-07 10:33:00 -0800833 copy_prop("flash_logical_block_size", "flash_logical_block_size")
Connor O'Brien20f08c32017-01-05 16:48:14 -0800834 copy_prop("flash_erase_block_size", "flash_erase_block_size")
Ying Wang9f8e8db2011-11-04 11:37:01 -0700835 elif mount_point == "cache":
836 copy_prop("cache_fs_type", "fs_type")
837 copy_prop("cache_size", "partition_size")
Ying Wanga0febe52013-03-20 11:02:05 -0700838 elif mount_point == "vendor":
Bowgo Tsai3e599ea2017-05-26 18:30:04 +0800839 copy_prop("avb_vendor_hashtree_enable", "avb_hashtree_enable")
840 copy_prop("avb_vendor_add_hashtree_footer_args",
841 "avb_add_hashtree_footer_args")
842 copy_prop("avb_vendor_key_path", "avb_key_path")
843 copy_prop("avb_vendor_algorithm", "avb_algorithm")
Ying Wanga0febe52013-03-20 11:02:05 -0700844 copy_prop("vendor_fs_type", "fs_type")
845 copy_prop("vendor_size", "partition_size")
Tao Bao332a96b2018-03-31 10:27:35 -0700846 if not copy_prop("vendor_journal_size", "journal_size"):
847 d["journal_size"] = "0"
Daniel Rosenbergf4eabc32014-07-10 15:42:38 -0700848 copy_prop("vendor_verity_block_device", "verity_block_device")
Jin Qianfde9f792018-01-22 13:15:46 -0800849 copy_prop("ext4_share_dup_blocks", "ext4_share_dup_blocks")
Patrick Tjine11aa502016-02-09 15:40:38 -0800850 copy_prop("vendor_squashfs_compressor", "squashfs_compressor")
851 copy_prop("vendor_squashfs_compressor_opt", "squashfs_compressor_opt")
Mohamad Ayyashdfec8152016-05-24 12:59:30 -0700852 copy_prop("vendor_squashfs_block_size", "squashfs_block_size")
Mohamad Ayyash1b6d3482016-06-15 15:53:07 -0700853 copy_prop("vendor_squashfs_disable_4k_align", "squashfs_disable_4k_align")
Mohamad Ayyashf8765552016-03-02 21:07:23 -0800854 copy_prop("vendor_base_fs_file", "base_fs_file")
Patrick Tjina1900842016-10-20 10:58:12 -0700855 copy_prop("vendor_extfs_inode_count", "extfs_inode_count")
Patrick Tjin3f5f9932018-03-23 11:36:43 -0700856 if not copy_prop("vendor_extfs_rsv_pct", "extfs_rsv_pct"):
857 d["extfs_rsv_pct"] = "0"
Jaekyun Seokb7735d82017-11-27 17:04:47 +0900858 elif mount_point == "product":
859 copy_prop("avb_product_hashtree_enable", "avb_hashtree_enable")
860 copy_prop("avb_product_add_hashtree_footer_args",
861 "avb_add_hashtree_footer_args")
862 copy_prop("avb_product_key_path", "avb_key_path")
863 copy_prop("avb_product_algorithm", "avb_algorithm")
864 copy_prop("product_fs_type", "fs_type")
865 copy_prop("product_size", "partition_size")
Tao Bao332a96b2018-03-31 10:27:35 -0700866 if not copy_prop("product_journal_size", "journal_size"):
867 d["journal_size"] = "0"
Jaekyun Seokb7735d82017-11-27 17:04:47 +0900868 copy_prop("product_verity_block_device", "verity_block_device")
869 copy_prop("product_squashfs_compressor", "squashfs_compressor")
870 copy_prop("product_squashfs_compressor_opt", "squashfs_compressor_opt")
871 copy_prop("product_squashfs_block_size", "squashfs_block_size")
872 copy_prop("product_squashfs_disable_4k_align", "squashfs_disable_4k_align")
873 copy_prop("product_base_fs_file", "base_fs_file")
874 copy_prop("product_extfs_inode_count", "extfs_inode_count")
Patrick Tjin3f5f9932018-03-23 11:36:43 -0700875 if not copy_prop("product_extfs_rsv_pct", "extfs_rsv_pct"):
876 d["extfs_rsv_pct"] = "0"
Ying Wangb8888432014-03-11 17:13:27 -0700877 elif mount_point == "oem":
878 copy_prop("fs_type", "fs_type")
879 copy_prop("oem_size", "partition_size")
Tao Bao332a96b2018-03-31 10:27:35 -0700880 if not copy_prop("oem_journal_size", "journal_size"):
881 d["journal_size"] = "0"
Patrick Tjina1900842016-10-20 10:58:12 -0700882 copy_prop("oem_extfs_inode_count", "extfs_inode_count")
Patrick Tjin3f5f9932018-03-23 11:36:43 -0700883 if not copy_prop("oem_extfs_rsv_pct", "extfs_rsv_pct"):
884 d["extfs_rsv_pct"] = "0"
David Zeuthen4014a9d2016-09-30 17:29:22 -0400885 d["partition_name"] = mount_point
Ying Wangbd93d422011-10-28 17:02:30 -0700886 return d
887
888
889def LoadGlobalDict(filename):
890 """Load "name=value" pairs from filename"""
891 d = {}
892 f = open(filename)
893 for line in f:
894 line = line.strip()
895 if not line or line.startswith("#"):
896 continue
897 k, v = line.split("=", 1)
898 d[k] = v
899 f.close()
900 return d
901
902
Yifan Hongbbcba1e2018-06-18 16:32:35 -0700903def GlobalDictFromImageProp(image_prop, mount_point):
904 d = {}
905 def copy_prop(src_p, dest_p):
906 if src_p in image_prop:
907 d[dest_p] = image_prop[src_p]
908 return True
909 return False
910 if mount_point == "system":
911 copy_prop("partition_size", "system_size")
912 elif mount_point == "system_other":
913 copy_prop("partition_size", "system_size")
914 return d
915
916
917def SaveGlobalDict(filename, glob_dict):
918 with open(filename, "w") as f:
919 f.writelines(["%s=%s" % (key, value) for (key, value) in glob_dict.items()])
920
921
Ying Wangbd93d422011-10-28 17:02:30 -0700922def main(argv):
Yifan Hongbbcba1e2018-06-18 16:32:35 -0700923 if len(argv) < 4 or len(argv) > 5:
Tao Baoc72727a2017-12-07 10:33:00 -0800924 print(__doc__)
Ying Wangbd93d422011-10-28 17:02:30 -0700925 sys.exit(1)
926
927 in_dir = argv[0]
928 glob_dict_file = argv[1]
929 out_file = argv[2]
Thierry Strudel74a81e62015-07-09 09:54:55 -0700930 target_out = argv[3]
Yifan Hongbbcba1e2018-06-18 16:32:35 -0700931 prop_file_out = argv[4] if len(argv) >= 5 else None
Ying Wangbd93d422011-10-28 17:02:30 -0700932
933 glob_dict = LoadGlobalDict(glob_dict_file)
Ying Wangae61f502015-03-12 18:30:39 -0700934 if "mount_point" in glob_dict:
Tao Baoc7a6f1e2015-06-23 11:16:05 -0700935 # The caller knows the mount point and provides a dictionay needed by
936 # BuildImage().
Ying Wangae61f502015-03-12 18:30:39 -0700937 image_properties = glob_dict
Ying Wang9f8e8db2011-11-04 11:37:01 -0700938 else:
Ying Wangae61f502015-03-12 18:30:39 -0700939 image_filename = os.path.basename(out_file)
940 mount_point = ""
941 if image_filename == "system.img":
942 mount_point = "system"
Alex Light4e358ab2016-06-16 14:47:10 -0700943 elif image_filename == "system_other.img":
944 mount_point = "system_other"
Ying Wangae61f502015-03-12 18:30:39 -0700945 elif image_filename == "userdata.img":
946 mount_point = "data"
947 elif image_filename == "cache.img":
948 mount_point = "cache"
949 elif image_filename == "vendor.img":
950 mount_point = "vendor"
951 elif image_filename == "oem.img":
952 mount_point = "oem"
Jaekyun Seokb7735d82017-11-27 17:04:47 +0900953 elif image_filename == "product.img":
954 mount_point = "product"
Ying Wangae61f502015-03-12 18:30:39 -0700955 else:
Tao Baoc72727a2017-12-07 10:33:00 -0800956 print("error: unknown image file name ", image_filename, file=sys.stderr)
Tao Bao1c830bf2017-12-25 10:43:47 -0800957 sys.exit(1)
Ying Wangbd93d422011-10-28 17:02:30 -0700958
Ying Wangae61f502015-03-12 18:30:39 -0700959 image_properties = ImagePropFromGlobalDict(glob_dict, mount_point)
960
Thierry Strudel74a81e62015-07-09 09:54:55 -0700961 if not BuildImage(in_dir, image_properties, out_file, target_out):
Tao Baoc72727a2017-12-07 10:33:00 -0800962 print("error: failed to build %s from %s" % (out_file, in_dir),
963 file=sys.stderr)
Tao Bao1c830bf2017-12-25 10:43:47 -0800964 sys.exit(1)
Ying Wangbd93d422011-10-28 17:02:30 -0700965
Yifan Hongbbcba1e2018-06-18 16:32:35 -0700966 if prop_file_out:
967 glob_dict_out = GlobalDictFromImageProp(image_properties, mount_point)
968 SaveGlobalDict(prop_file_out, glob_dict_out)
Ying Wangbd93d422011-10-28 17:02:30 -0700969
970if __name__ == '__main__':
Tao Bao1c830bf2017-12-25 10:43:47 -0800971 try:
972 main(sys.argv[1:])
973 finally:
974 common.Cleanup()