blob: b7e114d8f94d9f72982824f0788ca6e9fcb0b6f7 [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
Tao Baoc2606eb2018-07-20 14:44:46 -0700428def SetUpInDirAndFsConfig(origin_in, prop_dict):
429 """Returns the in_dir and fs_config that should be used for image building.
430
431 If the target uses system_root_image and it's building system.img, it creates
432 and returns a staged dir that combines the contents of /system (i.e. in the
433 given in_dir) and root.
434
435 Args:
436 origin_in: Path to the input directory.
437 prop_dict: A property dict that contains info like partition size. Values
438 may be updated.
439
440 Returns:
441 A tuple of in_dir and fs_config that should be used to build the image.
442 """
443 fs_config = prop_dict.get("fs_config")
444 if (prop_dict.get("system_root_image") != "true" or
445 prop_dict["mount_point"] != "system"):
446 return origin_in, fs_config
447
448 # Construct a staging directory of the root file system.
449 in_dir = common.MakeTempDir()
450 root_dir = prop_dict.get("root_dir")
451 if root_dir:
452 shutil.rmtree(in_dir)
453 shutil.copytree(root_dir, in_dir, symlinks=True)
454 in_dir_system = os.path.join(in_dir, "system")
455 shutil.rmtree(in_dir_system, ignore_errors=True)
456 shutil.copytree(origin_in, in_dir_system, symlinks=True)
457
458 # Change the mount point to "/".
459 prop_dict["mount_point"] = "/"
460 if fs_config:
461 # We need to merge the fs_config files of system and root.
462 merged_fs_config = common.MakeTempFile(
463 prefix="merged_fs_config", suffix=".txt")
464 with open(merged_fs_config, "w") as fw:
465 if "root_fs_config" in prop_dict:
466 with open(prop_dict["root_fs_config"]) as fr:
467 fw.writelines(fr.readlines())
468 with open(fs_config) as fr:
469 fw.writelines(fr.readlines())
470 fs_config = merged_fs_config
471 return in_dir, fs_config
472
473
Tao Baod4349f22017-12-07 23:01:25 -0800474def CheckHeadroom(ext4fs_output, prop_dict):
475 """Checks if there's enough headroom space available.
476
477 Headroom is the reserved space on system image (via PRODUCT_SYSTEM_HEADROOM),
478 which is useful for devices with low disk space that have system image
479 variation between builds. The 'partition_headroom' in prop_dict is the size
480 in bytes, while the numbers in 'ext4fs_output' are for 4K-blocks.
481
482 Args:
483 ext4fs_output: The output string from mke2fs command.
484 prop_dict: The property dict.
485
486 Returns:
487 The check result.
Tao Baod8a953d2018-01-02 21:19:27 -0800488
489 Raises:
490 AssertionError: On invalid input.
Tao Baod4349f22017-12-07 23:01:25 -0800491 """
Tao Baod8a953d2018-01-02 21:19:27 -0800492 assert ext4fs_output is not None
493 assert prop_dict.get('fs_type', '').startswith('ext4')
494 assert 'partition_headroom' in prop_dict
495 assert 'mount_point' in prop_dict
496
Tao Baod4349f22017-12-07 23:01:25 -0800497 ext4fs_stats = re.compile(
498 r'Created filesystem with .* (?P<used_blocks>[0-9]+)/'
499 r'(?P<total_blocks>[0-9]+) blocks')
Tao Baoc72727a2017-12-07 10:33:00 -0800500 last_line = ext4fs_output.strip().split('\n')[-1]
501 m = ext4fs_stats.match(last_line)
Tao Baod4349f22017-12-07 23:01:25 -0800502 used_blocks = int(m.groupdict().get('used_blocks'))
503 total_blocks = int(m.groupdict().get('total_blocks'))
Tao Baod8a953d2018-01-02 21:19:27 -0800504 headroom_blocks = int(prop_dict['partition_headroom']) / BLOCK_SIZE
Tao Baod4349f22017-12-07 23:01:25 -0800505 adjusted_blocks = total_blocks - headroom_blocks
506 if used_blocks > adjusted_blocks:
Tao Baod8a953d2018-01-02 21:19:27 -0800507 mount_point = prop_dict["mount_point"]
Tao Baod4349f22017-12-07 23:01:25 -0800508 print("Error: Not enough room on %s (total: %d blocks, used: %d blocks, "
509 "headroom: %d blocks, available: %d blocks)" % (
510 mount_point, total_blocks, used_blocks, headroom_blocks,
511 adjusted_blocks))
512 return False
513 return True
514
515
Thierry Strudel74a81e62015-07-09 09:54:55 -0700516def BuildImage(in_dir, prop_dict, out_file, target_out=None):
Tao Baoc2606eb2018-07-20 14:44:46 -0700517 """Builds an image for the files under in_dir and writes it to out_file.
518
519 When using system_root_image, it will additionally look for the files under
520 root (specified by 'root_dir') and builds an image that contains both sources.
Ying Wangbd93d422011-10-28 17:02:30 -0700521
522 Args:
Tao Baoc2606eb2018-07-20 14:44:46 -0700523 in_dir: Path to input directory.
524 prop_dict: A property dict that contains info like partition size. Values
525 will be updated with computed values.
526 out_file: The output image file.
527 target_out: Path to the TARGET_OUT directory as in Makefile. It actually
528 points to the /system directory under PRODUCT_OUT. fs_config (the one
529 under system/core/libcutils) reads device specific FS config files from
530 there.
Ying Wangbd93d422011-10-28 17:02:30 -0700531
532 Returns:
533 True iff the image is built successfully.
534 """
Tao Baoc2606eb2018-07-20 14:44:46 -0700535 in_dir, fs_config = SetUpInDirAndFsConfig(in_dir, prop_dict)
Ying Wanga2292c92015-03-24 19:07:40 -0700536
Ying Wangbd93d422011-10-28 17:02:30 -0700537 build_command = []
538 fs_type = prop_dict.get("fs_type", "")
Tao Baoc72727a2017-12-07 10:33:00 -0800539 run_e2fsck = False
Geremy Condrafd6f7512013-06-16 17:26:08 -0700540
Mohamad Ayyashdd063522015-03-24 12:42:03 -0700541 fs_spans_partition = True
542 if fs_type.startswith("squash"):
Tao Baoc7a6f1e2015-06-23 11:16:05 -0700543 fs_spans_partition = False
Mohamad Ayyashdd063522015-03-24 12:42:03 -0700544
Daniel Rosenbergf4eabc32014-07-10 15:42:38 -0700545 is_verity_partition = "verity_block_device" in prop_dict
Geremy Condra5b5f4952014-05-05 22:19:37 -0700546 verity_supported = prop_dict.get("verity") == "true"
Sami Tolvanenf99b5312015-05-20 07:30:57 +0100547 verity_fec_supported = prop_dict.get("verity_fec") == "true"
548
Yifan Hongbbcba1e2018-06-18 16:32:35 -0700549 if (prop_dict.get("use_logical_partitions") == "true" and
550 "partition_size" not in prop_dict):
551 # if partition_size is not defined, use output of `du' + reserved_size
Tao Baoc2606eb2018-07-20 14:44:46 -0700552 success, size = GetDiskUsage(in_dir)
Yifan Hongbbcba1e2018-06-18 16:32:35 -0700553 if not success:
554 return False
555 if OPTIONS.verbose:
Tao Baoc2606eb2018-07-20 14:44:46 -0700556 print("The tree size of %s is %d MB." % (in_dir, size // BYTES_IN_MB))
Yifan Hongbbcba1e2018-06-18 16:32:35 -0700557 size += int(prop_dict.get("partition_reserved_size", 0))
558 # Round this up to a multiple of 4K so that avbtool works
559 size = common.RoundUpTo4K(size)
560 prop_dict["partition_size"] = str(size)
561 if OPTIONS.verbose:
562 print("Allocating %d MB for %s." % (size // BYTES_IN_MB, out_file))
563
Tao Baoc7a6f1e2015-06-23 11:16:05 -0700564 # Adjust the partition size to make room for the hashes if this is to be
565 # verified.
Sami Tolvanen405e71d2016-02-09 12:28:58 -0800566 if verity_supported and is_verity_partition:
Geremy Condrafd6f7512013-06-16 17:26:08 -0700567 partition_size = int(prop_dict.get("partition_size"))
Tao Baoc72727a2017-12-07 10:33:00 -0800568 (adjusted_size, verity_size) = AdjustPartitionSizeForVerity(
569 partition_size, verity_fec_supported)
Geremy Condrafd6f7512013-06-16 17:26:08 -0700570 if not adjusted_size:
571 return False
572 prop_dict["partition_size"] = str(adjusted_size)
573 prop_dict["original_partition_size"] = str(partition_size)
Sami Tolvanen433905f2016-09-01 15:58:35 -0700574 prop_dict["verity_size"] = str(verity_size)
Geremy Condrafd6f7512013-06-16 17:26:08 -0700575
Bowgo Tsai7ea994b2017-05-19 23:44:26 +0800576 # Adjust partition size for AVB hash footer or AVB hashtree footer.
577 avb_footer_type = ''
578 if prop_dict.get("avb_hash_enable") == "true":
579 avb_footer_type = 'hash'
580 elif prop_dict.get("avb_hashtree_enable") == "true":
581 avb_footer_type = 'hashtree'
582
583 if avb_footer_type:
Bowgo Tsai3e599ea2017-05-26 18:30:04 +0800584 avbtool = prop_dict["avb_avbtool"]
585 partition_size = prop_dict["partition_size"]
Bowgo Tsai7ea994b2017-05-19 23:44:26 +0800586 # avb_add_hash_footer_args or avb_add_hashtree_footer_args.
587 additional_args = prop_dict["avb_add_" + avb_footer_type + "_footer_args"]
Tao Baoc72727a2017-12-07 10:33:00 -0800588 max_image_size = AVBCalcMaxImageSize(avbtool, avb_footer_type,
589 partition_size, additional_args)
David Zeuthen4014a9d2016-09-30 17:29:22 -0400590 if max_image_size == 0:
591 return False
592 prop_dict["partition_size"] = str(max_image_size)
Bowgo Tsai3e599ea2017-05-26 18:30:04 +0800593 prop_dict["original_partition_size"] = partition_size
David Zeuthen4014a9d2016-09-30 17:29:22 -0400594
Ying Wangbd93d422011-10-28 17:02:30 -0700595 if fs_type.startswith("ext"):
Adrien Schildknecht9a072cc2016-11-18 17:06:29 -0800596 build_command = [prop_dict["ext_mkuserimg"]]
Ying Wangbd93d422011-10-28 17:02:30 -0700597 if "extfs_sparse_flag" in prop_dict:
598 build_command.append(prop_dict["extfs_sparse_flag"])
Tao Baoc72727a2017-12-07 10:33:00 -0800599 run_e2fsck = True
Ying Wangbd93d422011-10-28 17:02:30 -0700600 build_command.extend([in_dir, out_file, fs_type,
601 prop_dict["mount_point"]])
Doug Zongker850b8072013-12-05 15:54:55 -0800602 build_command.append(prop_dict["partition_size"])
Ying Wangf3b86352014-11-18 18:03:13 -0800603 if "journal_size" in prop_dict:
604 build_command.extend(["-j", prop_dict["journal_size"]])
Doug Zongker850b8072013-12-05 15:54:55 -0800605 if "timestamp" in prop_dict:
606 build_command.extend(["-T", str(prop_dict["timestamp"])])
Ying Wanga2292c92015-03-24 19:07:40 -0700607 if fs_config:
Doug Zongker82822822014-06-16 09:10:55 -0700608 build_command.extend(["-C", fs_config])
Thierry Strudel74a81e62015-07-09 09:54:55 -0700609 if target_out:
610 build_command.extend(["-D", target_out])
Ying Wanga2292c92015-03-24 19:07:40 -0700611 if "block_list" in prop_dict:
612 build_command.extend(["-B", prop_dict["block_list"]])
Mohamad Ayyashf8765552016-03-02 21:07:23 -0800613 if "base_fs_file" in prop_dict:
614 base_fs_file = ConvertBlockMapToBaseFs(prop_dict["base_fs_file"])
615 if base_fs_file is None:
616 return False
617 build_command.extend(["-d", base_fs_file])
Christoffer Dall8ed01f32014-12-17 21:34:12 +0100618 build_command.extend(["-L", prop_dict["mount_point"]])
Patrick Tjina1900842016-10-20 10:58:12 -0700619 if "extfs_inode_count" in prop_dict:
620 build_command.extend(["-i", prop_dict["extfs_inode_count"]])
Patrick Tjin3f5f9932018-03-23 11:36:43 -0700621 if "extfs_rsv_pct" in prop_dict:
622 build_command.extend(["-M", prop_dict["extfs_rsv_pct"]])
Connor O'Brien20f08c32017-01-05 16:48:14 -0800623 if "flash_erase_block_size" in prop_dict:
624 build_command.extend(["-e", prop_dict["flash_erase_block_size"]])
625 if "flash_logical_block_size" in prop_dict:
626 build_command.extend(["-o", prop_dict["flash_logical_block_size"]])
Tao Baod86e3112017-09-22 15:45:33 -0700627 # Specify UUID and hash_seed if using mke2fs.
628 if prop_dict["ext_mkuserimg"] == "mkuserimg_mke2fs.sh":
629 if "uuid" in prop_dict:
630 build_command.extend(["-U", prop_dict["uuid"]])
631 if "hash_seed" in prop_dict:
632 build_command.extend(["-S", prop_dict["hash_seed"]])
Jin Qianfde9f792018-01-22 13:15:46 -0800633 if "ext4_share_dup_blocks" in prop_dict:
634 build_command.append("-c")
Ying Wanga2292c92015-03-24 19:07:40 -0700635 if "selinux_fc" in prop_dict:
Kenny Rootf32dc712012-04-08 10:42:34 -0700636 build_command.append(prop_dict["selinux_fc"])
Mohamad Ayyashb97746e2015-03-03 12:30:37 -0800637 elif fs_type.startswith("squash"):
638 build_command = ["mksquashfsimage.sh"]
639 build_command.extend([in_dir, out_file])
Todd Poynorb2a555e2015-12-15 18:00:14 -0800640 if "squashfs_sparse_flag" in prop_dict:
641 build_command.extend([prop_dict["squashfs_sparse_flag"]])
Mohamad Ayyashb97746e2015-03-03 12:30:37 -0800642 build_command.extend(["-m", prop_dict["mount_point"]])
Thierry Strudel74a81e62015-07-09 09:54:55 -0700643 if target_out:
644 build_command.extend(["-d", target_out])
Mohamad Ayyash88378822016-04-07 22:10:51 -0700645 if fs_config:
646 build_command.extend(["-C", fs_config])
Ying Wanga2292c92015-03-24 19:07:40 -0700647 if "selinux_fc" in prop_dict:
Mohamad Ayyashb97746e2015-03-03 12:30:37 -0800648 build_command.extend(["-c", prop_dict["selinux_fc"]])
Mohamad Ayyashc3484f72016-06-13 09:46:58 -0700649 if "block_list" in prop_dict:
650 build_command.extend(["-B", prop_dict["block_list"]])
Ng Zhi An9446c1d2018-01-19 15:51:46 -0800651 if "squashfs_block_size" in prop_dict:
652 build_command.extend(["-b", prop_dict["squashfs_block_size"]])
Simon Wilsonf86e7ee2015-06-17 12:35:15 -0700653 if "squashfs_compressor" in prop_dict:
654 build_command.extend(["-z", prop_dict["squashfs_compressor"]])
655 if "squashfs_compressor_opt" in prop_dict:
656 build_command.extend(["-zo", prop_dict["squashfs_compressor_opt"]])
Tao Baoc72727a2017-12-07 10:33:00 -0800657 if prop_dict.get("squashfs_disable_4k_align") == "true":
Mohamad Ayyash1b6d3482016-06-15 15:53:07 -0700658 build_command.extend(["-a"])
JP Abgrall5bfed5a2014-06-16 14:17:40 -0700659 elif fs_type.startswith("f2fs"):
660 build_command = ["mkf2fsuserimg.sh"]
661 build_command.extend([out_file, prop_dict["partition_size"]])
Jaegeuk Kim2ea1eba2017-11-28 19:21:28 -0800662 if fs_config:
663 build_command.extend(["-C", fs_config])
664 build_command.extend(["-f", in_dir])
665 if target_out:
666 build_command.extend(["-D", target_out])
667 if "selinux_fc" in prop_dict:
668 build_command.extend(["-s", prop_dict["selinux_fc"]])
669 build_command.extend(["-t", prop_dict["mount_point"]])
670 if "timestamp" in prop_dict:
671 build_command.extend(["-T", str(prop_dict["timestamp"])])
672 build_command.extend(["-L", prop_dict["mount_point"]])
Ying Wangbd93d422011-10-28 17:02:30 -0700673 else:
Elliott Hughes305b0882016-06-15 17:04:54 -0700674 print("Error: unknown filesystem type '%s'" % (fs_type))
675 return False
Ying Wangbd93d422011-10-28 17:02:30 -0700676
Tao Baoc72727a2017-12-07 10:33:00 -0800677 (mkfs_output, exit_code) = RunCommand(build_command)
Ying Wang69e9b4d2012-11-26 18:10:23 -0800678 if exit_code != 0:
Tao Baocd53a892018-01-19 10:29:52 -0800679 print("Error: '%s' failed with exit code %d:\n%s" % (
680 build_command, exit_code, mkfs_output))
Tao Baoc2606eb2018-07-20 14:44:46 -0700681 success, du = GetDiskUsage(in_dir)
Yifan Hongbbcba1e2018-06-18 16:32:35 -0700682 du_str = ("%d bytes (%d MB)" % (du, du // BYTES_IN_MB)
683 ) if success else "unknown"
Tao Bao4251fe92018-07-23 13:05:00 -0700684 print(
685 "Out of space? The tree size of {} is {}, with reserved space of {} "
686 "bytes ({} MB).".format(
Tao Baoc2606eb2018-07-20 14:44:46 -0700687 in_dir, du_str,
Tao Bao4251fe92018-07-23 13:05:00 -0700688 int(prop_dict.get("partition_reserved_size", 0)),
689 int(prop_dict.get("partition_reserved_size", 0)) // BYTES_IN_MB))
690 if "original_partition_size" in prop_dict:
691 print(
692 "The max size for filsystem files is {} bytes ({} MB), out of a "
693 "total image size of {} bytes ({} MB).".format(
694 int(prop_dict["partition_size"]),
695 int(prop_dict["partition_size"]) // BYTES_IN_MB,
696 int(prop_dict["original_partition_size"]),
697 int(prop_dict["original_partition_size"]) // BYTES_IN_MB))
698 else:
699 print("The max image size is {} bytes ({} MB).".format(
700 int(prop_dict["partition_size"]),
701 int(prop_dict["partition_size"]) // BYTES_IN_MB))
Ying Wang69e9b4d2012-11-26 18:10:23 -0800702 return False
703
Tao Baod4349f22017-12-07 23:01:25 -0800704 # Check if there's enough headroom space available for ext4 image.
Tao Bao79d52f82017-12-07 14:07:44 -0800705 if "partition_headroom" in prop_dict and fs_type.startswith("ext4"):
Tao Baoc72727a2017-12-07 10:33:00 -0800706 if not CheckHeadroom(mkfs_output, prop_dict):
Tao Baoc7a6f1e2015-06-23 11:16:05 -0700707 return False
708
Mohamad Ayyashdd063522015-03-24 12:42:03 -0700709 if not fs_spans_partition:
710 mount_point = prop_dict.get("mount_point")
711 partition_size = int(prop_dict.get("partition_size"))
Sami Tolvanen405e71d2016-02-09 12:28:58 -0800712 image_size = GetSimgSize(out_file)
Mohamad Ayyashdd063522015-03-24 12:42:03 -0700713 if image_size > partition_size:
Tao Baoc7a6f1e2015-06-23 11:16:05 -0700714 print("Error: %s image size of %d is larger than partition size of "
715 "%d" % (mount_point, image_size, partition_size))
716 return False
Mohamad Ayyashdd063522015-03-24 12:42:03 -0700717 if verity_supported and is_verity_partition:
Sami Tolvanen405e71d2016-02-09 12:28:58 -0800718 ZeroPadSimg(out_file, partition_size - image_size)
Mohamad Ayyashdd063522015-03-24 12:42:03 -0700719
Tao Baoc72727a2017-12-07 10:33:00 -0800720 # Create the verified image if this is to be verified.
Geremy Condra5b5f4952014-05-05 22:19:37 -0700721 if verity_supported and is_verity_partition:
Sami Tolvanenf99b5312015-05-20 07:30:57 +0100722 if not MakeVerityEnabledImage(out_file, verity_fec_supported, prop_dict):
Geremy Condrafd6f7512013-06-16 17:26:08 -0700723 return False
724
Bowgo Tsai7ea994b2017-05-19 23:44:26 +0800725 # Add AVB HASH or HASHTREE footer (metadata).
726 if avb_footer_type:
Bowgo Tsai3e599ea2017-05-26 18:30:04 +0800727 avbtool = prop_dict["avb_avbtool"]
728 original_partition_size = prop_dict["original_partition_size"]
David Zeuthen4014a9d2016-09-30 17:29:22 -0400729 partition_name = prop_dict["partition_name"]
Bowgo Tsai3e599ea2017-05-26 18:30:04 +0800730 # key_path and algorithm are only available when chain partition is used.
731 key_path = prop_dict.get("avb_key_path")
732 algorithm = prop_dict.get("avb_algorithm")
Tao Bao2b6dfd62017-09-27 17:17:43 -0700733 salt = prop_dict.get("avb_salt")
Bowgo Tsai7ea994b2017-05-19 23:44:26 +0800734 # avb_add_hash_footer_args or avb_add_hashtree_footer_args
735 additional_args = prop_dict["avb_add_" + avb_footer_type + "_footer_args"]
Tao Baoc72727a2017-12-07 10:33:00 -0800736 if not AVBAddFooter(out_file, avbtool, avb_footer_type,
737 original_partition_size, partition_name, key_path,
738 algorithm, salt, additional_args):
David Zeuthen4014a9d2016-09-30 17:29:22 -0400739 return False
740
Tao Baoc72727a2017-12-07 10:33:00 -0800741 if run_e2fsck and prop_dict.get("skip_fsck") != "true":
Geremy Condra6e8f53c2013-12-05 17:09:18 -0800742 success, unsparse_image = UnsparseImage(out_file, replace=False)
Geremy Condrafd6f7512013-06-16 17:26:08 -0700743 if not success:
Ying Wang69e9b4d2012-11-26 18:10:23 -0800744 return False
745
746 # Run e2fsck on the inflated image file
747 e2fsck_command = ["e2fsck", "-f", "-n", unsparse_image]
Tao Baocd53a892018-01-19 10:29:52 -0800748 (e2fsck_output, exit_code) = RunCommand(e2fsck_command)
Ying Wang69e9b4d2012-11-26 18:10:23 -0800749
750 os.remove(unsparse_image)
751
Elliott Hughes73ff57f2017-12-06 12:16:39 -0800752 if exit_code != 0:
Tao Baocd53a892018-01-19 10:29:52 -0800753 print("Error: '%s' failed with exit code %d:\n%s" % (
754 e2fsck_command, exit_code, e2fsck_output))
Elliott Hughes73ff57f2017-12-06 12:16:39 -0800755 return False
756
757 return True
Ying Wangbd93d422011-10-28 17:02:30 -0700758
759
760def ImagePropFromGlobalDict(glob_dict, mount_point):
761 """Build an image property dictionary from the global dictionary.
762
763 Args:
764 glob_dict: the global dictionary from the build system.
765 mount_point: such as "system", "data" etc.
766 """
Doug Zongker1ad7ade2013-12-06 11:53:27 -0800767 d = {}
Tao Bao052ae352015-09-28 13:44:13 -0700768
Tao Bao822f5842015-09-30 16:01:14 -0700769 if "build.prop" in glob_dict:
770 bp = glob_dict["build.prop"]
771 if "ro.build.date.utc" in bp:
772 d["timestamp"] = bp["ro.build.date.utc"]
Ying Wang9f8e8db2011-11-04 11:37:01 -0700773
774 def copy_prop(src_p, dest_p):
Patrick Tjin3f5f9932018-03-23 11:36:43 -0700775 """Copy a property from the global dictionary.
776
777 Args:
778 src_p: The source property in the global dictionary.
779 dest_p: The destination property.
780 Returns:
781 True if property was found and copied, False otherwise.
782 """
Ying Wang9f8e8db2011-11-04 11:37:01 -0700783 if src_p in glob_dict:
784 d[dest_p] = str(glob_dict[src_p])
Patrick Tjin3f5f9932018-03-23 11:36:43 -0700785 return True
786 return False
Ying Wang9f8e8db2011-11-04 11:37:01 -0700787
Ying Wangbd93d422011-10-28 17:02:30 -0700788 common_props = (
Ying Wangbd93d422011-10-28 17:02:30 -0700789 "extfs_sparse_flag",
Todd Poynorb2a555e2015-12-15 18:00:14 -0800790 "squashfs_sparse_flag",
Kenny Rootf32dc712012-04-08 10:42:34 -0700791 "selinux_fc",
Ying Wang6a42a252013-02-27 13:54:02 -0800792 "skip_fsck",
Adrien Schildknecht9a072cc2016-11-18 17:06:29 -0800793 "ext_mkuserimg",
Geremy Condrafd6f7512013-06-16 17:26:08 -0700794 "verity",
Geremy Condrafd6f7512013-06-16 17:26:08 -0700795 "verity_key",
Sami Tolvanenf99b5312015-05-20 07:30:57 +0100796 "verity_signer_cmd",
David Zeuthen4014a9d2016-09-30 17:29:22 -0400797 "verity_fec",
Bowgo Tsai6ceeb1a2017-10-11 16:21:48 +0800798 "verity_disable",
Bowgo Tsai3e599ea2017-05-26 18:30:04 +0800799 "avb_enable",
Tao Bao2b6dfd62017-09-27 17:17:43 -0700800 "avb_avbtool",
801 "avb_salt",
Yifan Hongbbcba1e2018-06-18 16:32:35 -0700802 "use_logical_partitions",
Tao Bao2b6dfd62017-09-27 17:17:43 -0700803 )
Ying Wangbd93d422011-10-28 17:02:30 -0700804 for p in common_props:
Ying Wang9f8e8db2011-11-04 11:37:01 -0700805 copy_prop(p, p)
Ying Wangbd93d422011-10-28 17:02:30 -0700806
807 d["mount_point"] = mount_point
808 if 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")
Ying Wang9f8e8db2011-11-04 11:37:01 -0700814 copy_prop("fs_type", "fs_type")
Julius D'souza001c6762017-05-03 13:43:27 -0700815 # Copy the generic system fs type first, override with specific one if
Dan Albert8b72aef2015-03-23 19:13:21 -0700816 # available.
Mohamad Ayyashb97746e2015-03-03 12:30:37 -0800817 copy_prop("system_fs_type", "fs_type")
Julius D'souza001c6762017-05-03 13:43:27 -0700818 copy_prop("system_headroom", "partition_headroom")
Ying Wang9f8e8db2011-11-04 11:37:01 -0700819 copy_prop("system_size", "partition_size")
Tao Bao332a96b2018-03-31 10:27:35 -0700820 if not copy_prop("system_journal_size", "journal_size"):
821 d["journal_size"] = "0"
Daniel Rosenbergf4eabc32014-07-10 15:42:38 -0700822 copy_prop("system_verity_block_device", "verity_block_device")
Tao Baof3282b42015-04-01 11:21:55 -0700823 copy_prop("system_root_image", "system_root_image")
Tao Bao8bfd3c72018-07-20 15:20:28 -0700824 copy_prop("root_dir", "root_dir")
825 copy_prop("root_fs_config", "root_fs_config")
Jin Qianfde9f792018-01-22 13:15:46 -0800826 copy_prop("ext4_share_dup_blocks", "ext4_share_dup_blocks")
Simon Wilsonf86e7ee2015-06-17 12:35:15 -0700827 copy_prop("system_squashfs_compressor", "squashfs_compressor")
828 copy_prop("system_squashfs_compressor_opt", "squashfs_compressor_opt")
Mohamad Ayyashdfec8152016-05-24 12:59:30 -0700829 copy_prop("system_squashfs_block_size", "squashfs_block_size")
Mohamad Ayyash1b6d3482016-06-15 15:53:07 -0700830 copy_prop("system_squashfs_disable_4k_align", "squashfs_disable_4k_align")
Mohamad Ayyashf8765552016-03-02 21:07:23 -0800831 copy_prop("system_base_fs_file", "base_fs_file")
Patrick Tjina1900842016-10-20 10:58:12 -0700832 copy_prop("system_extfs_inode_count", "extfs_inode_count")
Patrick Tjin3f5f9932018-03-23 11:36:43 -0700833 if not copy_prop("system_extfs_rsv_pct", "extfs_rsv_pct"):
834 d["extfs_rsv_pct"] = "0"
Yifan Hongbbcba1e2018-06-18 16:32:35 -0700835 copy_prop("system_reserved_size", "partition_reserved_size")
Alex Light4e358ab2016-06-16 14:47:10 -0700836 elif mount_point == "system_other":
Tao Baoc72727a2017-12-07 10:33:00 -0800837 # We inherit the selinux policies of /system since we contain some of its
838 # files.
Alex Light4e358ab2016-06-16 14:47:10 -0700839 d["mount_point"] = "system"
Bowgo Tsai3e599ea2017-05-26 18:30:04 +0800840 copy_prop("avb_system_hashtree_enable", "avb_hashtree_enable")
841 copy_prop("avb_system_add_hashtree_footer_args",
842 "avb_add_hashtree_footer_args")
843 copy_prop("avb_system_key_path", "avb_key_path")
844 copy_prop("avb_system_algorithm", "avb_algorithm")
Alex Light4e358ab2016-06-16 14:47:10 -0700845 copy_prop("fs_type", "fs_type")
846 copy_prop("system_fs_type", "fs_type")
847 copy_prop("system_size", "partition_size")
Tao Bao332a96b2018-03-31 10:27:35 -0700848 if not copy_prop("system_journal_size", "journal_size"):
849 d["journal_size"] = "0"
Alex Light4e358ab2016-06-16 14:47:10 -0700850 copy_prop("system_verity_block_device", "verity_block_device")
Alex Light4e358ab2016-06-16 14:47:10 -0700851 copy_prop("system_squashfs_compressor", "squashfs_compressor")
852 copy_prop("system_squashfs_compressor_opt", "squashfs_compressor_opt")
853 copy_prop("system_squashfs_block_size", "squashfs_block_size")
854 copy_prop("system_base_fs_file", "base_fs_file")
Patrick Tjina1900842016-10-20 10:58:12 -0700855 copy_prop("system_extfs_inode_count", "extfs_inode_count")
Patrick Tjin3f5f9932018-03-23 11:36:43 -0700856 if not copy_prop("system_extfs_rsv_pct", "extfs_rsv_pct"):
857 d["extfs_rsv_pct"] = "0"
Yifan Hongbbcba1e2018-06-18 16:32:35 -0700858 copy_prop("system_reserved_size", "partition_reserved_size")
Ying Wangbd93d422011-10-28 17:02:30 -0700859 elif mount_point == "data":
JP Abgrall5bfed5a2014-06-16 14:17:40 -0700860 # Copy the generic fs type first, override with specific one if available.
Ying Wang9f8e8db2011-11-04 11:37:01 -0700861 copy_prop("fs_type", "fs_type")
JP Abgrall5bfed5a2014-06-16 14:17:40 -0700862 copy_prop("userdata_fs_type", "fs_type")
Ying Wang9f8e8db2011-11-04 11:37:01 -0700863 copy_prop("userdata_size", "partition_size")
Tao Baoc72727a2017-12-07 10:33:00 -0800864 copy_prop("flash_logical_block_size", "flash_logical_block_size")
Connor O'Brien20f08c32017-01-05 16:48:14 -0800865 copy_prop("flash_erase_block_size", "flash_erase_block_size")
Ying Wang9f8e8db2011-11-04 11:37:01 -0700866 elif mount_point == "cache":
867 copy_prop("cache_fs_type", "fs_type")
868 copy_prop("cache_size", "partition_size")
Ying Wanga0febe52013-03-20 11:02:05 -0700869 elif mount_point == "vendor":
Bowgo Tsai3e599ea2017-05-26 18:30:04 +0800870 copy_prop("avb_vendor_hashtree_enable", "avb_hashtree_enable")
871 copy_prop("avb_vendor_add_hashtree_footer_args",
872 "avb_add_hashtree_footer_args")
873 copy_prop("avb_vendor_key_path", "avb_key_path")
874 copy_prop("avb_vendor_algorithm", "avb_algorithm")
Ying Wanga0febe52013-03-20 11:02:05 -0700875 copy_prop("vendor_fs_type", "fs_type")
876 copy_prop("vendor_size", "partition_size")
Tao Bao332a96b2018-03-31 10:27:35 -0700877 if not copy_prop("vendor_journal_size", "journal_size"):
878 d["journal_size"] = "0"
Daniel Rosenbergf4eabc32014-07-10 15:42:38 -0700879 copy_prop("vendor_verity_block_device", "verity_block_device")
Jin Qianfde9f792018-01-22 13:15:46 -0800880 copy_prop("ext4_share_dup_blocks", "ext4_share_dup_blocks")
Patrick Tjine11aa502016-02-09 15:40:38 -0800881 copy_prop("vendor_squashfs_compressor", "squashfs_compressor")
882 copy_prop("vendor_squashfs_compressor_opt", "squashfs_compressor_opt")
Mohamad Ayyashdfec8152016-05-24 12:59:30 -0700883 copy_prop("vendor_squashfs_block_size", "squashfs_block_size")
Mohamad Ayyash1b6d3482016-06-15 15:53:07 -0700884 copy_prop("vendor_squashfs_disable_4k_align", "squashfs_disable_4k_align")
Mohamad Ayyashf8765552016-03-02 21:07:23 -0800885 copy_prop("vendor_base_fs_file", "base_fs_file")
Patrick Tjina1900842016-10-20 10:58:12 -0700886 copy_prop("vendor_extfs_inode_count", "extfs_inode_count")
Patrick Tjin3f5f9932018-03-23 11:36:43 -0700887 if not copy_prop("vendor_extfs_rsv_pct", "extfs_rsv_pct"):
888 d["extfs_rsv_pct"] = "0"
Yifan Hong749062d2018-06-19 16:23:16 -0700889 copy_prop("vendor_reserved_size", "partition_reserved_size")
Jaekyun Seokb7735d82017-11-27 17:04:47 +0900890 elif mount_point == "product":
891 copy_prop("avb_product_hashtree_enable", "avb_hashtree_enable")
892 copy_prop("avb_product_add_hashtree_footer_args",
893 "avb_add_hashtree_footer_args")
894 copy_prop("avb_product_key_path", "avb_key_path")
895 copy_prop("avb_product_algorithm", "avb_algorithm")
896 copy_prop("product_fs_type", "fs_type")
897 copy_prop("product_size", "partition_size")
Tao Bao332a96b2018-03-31 10:27:35 -0700898 if not copy_prop("product_journal_size", "journal_size"):
899 d["journal_size"] = "0"
Jaekyun Seokb7735d82017-11-27 17:04:47 +0900900 copy_prop("product_verity_block_device", "verity_block_device")
901 copy_prop("product_squashfs_compressor", "squashfs_compressor")
902 copy_prop("product_squashfs_compressor_opt", "squashfs_compressor_opt")
903 copy_prop("product_squashfs_block_size", "squashfs_block_size")
904 copy_prop("product_squashfs_disable_4k_align", "squashfs_disable_4k_align")
905 copy_prop("product_base_fs_file", "base_fs_file")
906 copy_prop("product_extfs_inode_count", "extfs_inode_count")
Patrick Tjin3f5f9932018-03-23 11:36:43 -0700907 if not copy_prop("product_extfs_rsv_pct", "extfs_rsv_pct"):
908 d["extfs_rsv_pct"] = "0"
Yifan Hong56a6c3b2018-07-20 15:19:34 -0700909 copy_prop("product_reserved_size", "partition_reserved_size")
Dario Freni5f681e12018-05-29 13:09:01 +0100910 elif mount_point == "product-services":
911 copy_prop("avb_productservices_hashtree_enable", "avb_hashtree_enable")
912 copy_prop("avb_productservices_add_hashtree_footer_args",
913 "avb_add_hashtree_footer_args")
914 copy_prop("avb_productservices_key_path", "avb_key_path")
915 copy_prop("avb_productservices_algorithm", "avb_algorithm")
916 copy_prop("productservices_fs_type", "fs_type")
917 copy_prop("productservices_size", "partition_size")
918 if not copy_prop("productservices_journal_size", "journal_size"):
919 d["journal_size"] = "0"
920 copy_prop("productservices_verity_block_device", "verity_block_device")
921 copy_prop("productservices_squashfs_compressor", "squashfs_compressor")
922 copy_prop("productservices_squashfs_compressor_opt",
923 "squashfs_compressor_opt")
924 copy_prop("productservices_squashfs_block_size", "squashfs_block_size")
925 copy_prop("productservices_squashfs_disable_4k_align",
926 "squashfs_disable_4k_align")
927 copy_prop("productservices_base_fs_file", "base_fs_file")
928 copy_prop("productservices_extfs_inode_count", "extfs_inode_count")
929 if not copy_prop("productservices_extfs_rsv_pct", "extfs_rsv_pct"):
930 d["extfs_rsv_pct"] = "0"
Yifan Hong9c35a022018-07-20 15:33:47 -0700931 copy_prop("productservices_reserved_size", "partition_reserved_size")
Ying Wangb8888432014-03-11 17:13:27 -0700932 elif mount_point == "oem":
933 copy_prop("fs_type", "fs_type")
934 copy_prop("oem_size", "partition_size")
Tao Bao332a96b2018-03-31 10:27:35 -0700935 if not copy_prop("oem_journal_size", "journal_size"):
936 d["journal_size"] = "0"
Patrick Tjina1900842016-10-20 10:58:12 -0700937 copy_prop("oem_extfs_inode_count", "extfs_inode_count")
Patrick Tjin3f5f9932018-03-23 11:36:43 -0700938 if not copy_prop("oem_extfs_rsv_pct", "extfs_rsv_pct"):
939 d["extfs_rsv_pct"] = "0"
David Zeuthen4014a9d2016-09-30 17:29:22 -0400940 d["partition_name"] = mount_point
Ying Wangbd93d422011-10-28 17:02:30 -0700941 return d
942
943
944def LoadGlobalDict(filename):
945 """Load "name=value" pairs from filename"""
946 d = {}
947 f = open(filename)
948 for line in f:
949 line = line.strip()
950 if not line or line.startswith("#"):
951 continue
952 k, v = line.split("=", 1)
953 d[k] = v
954 f.close()
955 return d
956
957
Yifan Hongbbcba1e2018-06-18 16:32:35 -0700958def GlobalDictFromImageProp(image_prop, mount_point):
959 d = {}
960 def copy_prop(src_p, dest_p):
961 if src_p in image_prop:
962 d[dest_p] = image_prop[src_p]
963 return True
964 return False
Tao Bao4251fe92018-07-23 13:05:00 -0700965
966 if "original_partition_size" in image_prop:
967 size_property = "original_partition_size"
968 else:
969 size_property = "partition_size"
970
Yifan Hongbbcba1e2018-06-18 16:32:35 -0700971 if mount_point == "system":
Tao Bao4251fe92018-07-23 13:05:00 -0700972 copy_prop(size_property, "system_size")
Yifan Hongbbcba1e2018-06-18 16:32:35 -0700973 elif mount_point == "system_other":
Tao Bao4251fe92018-07-23 13:05:00 -0700974 copy_prop(size_property, "system_size")
Yifan Hong749062d2018-06-19 16:23:16 -0700975 elif mount_point == "vendor":
Tao Bao4251fe92018-07-23 13:05:00 -0700976 copy_prop(size_property, "vendor_size")
Yifan Hong56a6c3b2018-07-20 15:19:34 -0700977 elif mount_point == "product":
Tao Bao4251fe92018-07-23 13:05:00 -0700978 copy_prop(size_property, "product_size")
Yifan Hong9c35a022018-07-20 15:33:47 -0700979 elif mount_point == "product-services":
Tao Bao4251fe92018-07-23 13:05:00 -0700980 copy_prop(size_property, "productservices_size")
Yifan Hongbbcba1e2018-06-18 16:32:35 -0700981 return d
982
983
984def SaveGlobalDict(filename, glob_dict):
985 with open(filename, "w") as f:
986 f.writelines(["%s=%s" % (key, value) for (key, value) in glob_dict.items()])
987
988
Ying Wangbd93d422011-10-28 17:02:30 -0700989def main(argv):
Yifan Hongbbcba1e2018-06-18 16:32:35 -0700990 if len(argv) < 4 or len(argv) > 5:
Tao Baoc72727a2017-12-07 10:33:00 -0800991 print(__doc__)
Ying Wangbd93d422011-10-28 17:02:30 -0700992 sys.exit(1)
993
994 in_dir = argv[0]
995 glob_dict_file = argv[1]
996 out_file = argv[2]
Thierry Strudel74a81e62015-07-09 09:54:55 -0700997 target_out = argv[3]
Yifan Hongbbcba1e2018-06-18 16:32:35 -0700998 prop_file_out = argv[4] if len(argv) >= 5 else None
Ying Wangbd93d422011-10-28 17:02:30 -0700999
1000 glob_dict = LoadGlobalDict(glob_dict_file)
Ying Wangae61f502015-03-12 18:30:39 -07001001 if "mount_point" in glob_dict:
Tao Baoc7a6f1e2015-06-23 11:16:05 -07001002 # The caller knows the mount point and provides a dictionay needed by
1003 # BuildImage().
Ying Wangae61f502015-03-12 18:30:39 -07001004 image_properties = glob_dict
Ying Wang9f8e8db2011-11-04 11:37:01 -07001005 else:
Ying Wangae61f502015-03-12 18:30:39 -07001006 image_filename = os.path.basename(out_file)
1007 mount_point = ""
1008 if image_filename == "system.img":
1009 mount_point = "system"
Alex Light4e358ab2016-06-16 14:47:10 -07001010 elif image_filename == "system_other.img":
1011 mount_point = "system_other"
Ying Wangae61f502015-03-12 18:30:39 -07001012 elif image_filename == "userdata.img":
1013 mount_point = "data"
1014 elif image_filename == "cache.img":
1015 mount_point = "cache"
1016 elif image_filename == "vendor.img":
1017 mount_point = "vendor"
1018 elif image_filename == "oem.img":
1019 mount_point = "oem"
Jaekyun Seokb7735d82017-11-27 17:04:47 +09001020 elif image_filename == "product.img":
1021 mount_point = "product"
Dario Freni5f681e12018-05-29 13:09:01 +01001022 elif image_filename == "product-services.img":
1023 mount_point = "product-services"
Ying Wangae61f502015-03-12 18:30:39 -07001024 else:
Tao Baoc72727a2017-12-07 10:33:00 -08001025 print("error: unknown image file name ", image_filename, file=sys.stderr)
Tao Bao1c830bf2017-12-25 10:43:47 -08001026 sys.exit(1)
Ying Wangbd93d422011-10-28 17:02:30 -07001027
Ying Wangae61f502015-03-12 18:30:39 -07001028 image_properties = ImagePropFromGlobalDict(glob_dict, mount_point)
1029
Thierry Strudel74a81e62015-07-09 09:54:55 -07001030 if not BuildImage(in_dir, image_properties, out_file, target_out):
Tao Baoc72727a2017-12-07 10:33:00 -08001031 print("error: failed to build %s from %s" % (out_file, in_dir),
1032 file=sys.stderr)
Tao Bao1c830bf2017-12-25 10:43:47 -08001033 sys.exit(1)
Ying Wangbd93d422011-10-28 17:02:30 -07001034
Yifan Hongbbcba1e2018-06-18 16:32:35 -07001035 if prop_file_out:
1036 glob_dict_out = GlobalDictFromImageProp(image_properties, mount_point)
1037 SaveGlobalDict(prop_file_out, glob_dict_out)
Ying Wangbd93d422011-10-28 17:02:30 -07001038
1039if __name__ == '__main__':
Tao Bao1c830bf2017-12-25 10:43:47 -08001040 try:
1041 main(sys.argv[1:])
1042 finally:
1043 common.Cleanup()