blob: 1f5caf342034351947b4faf50d24da0c02dfa576 [file] [log] [blame]
Ying Wangbd93d422011-10-28 17:02:30 -07001#!/usr/bin/env python
2#
3# Copyright (C) 2011 The Android Open Source Project
4#
5# Licensed under the Apache License, Version 2.0 (the "License");
6# you may not use this file except in compliance with the License.
7# You may obtain a copy of the License at
8#
9# http://www.apache.org/licenses/LICENSE-2.0
10#
11# Unless required by applicable law or agreed to in writing, software
12# distributed under the License is distributed on an "AS IS" BASIS,
13# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14# See the License for the specific language governing permissions and
15# limitations under the License.
16
17"""
Tao Baoc72727a2017-12-07 10:33:00 -080018Builds output_image from the given input_directory, properties_file,
19and writes the image to target_output_directory.
Ying Wangbd93d422011-10-28 17:02:30 -070020
Tao Baoc72727a2017-12-07 10:33:00 -080021Usage: build_image.py input_directory properties_file output_image \\
22 target_output_directory
Ying Wangbd93d422011-10-28 17:02:30 -070023"""
Tao Baoc72727a2017-12-07 10:33:00 -080024
25from __future__ import print_function
26
Ying Wangbd93d422011-10-28 17:02:30 -070027import os
Ying Wang69e9b4d2012-11-26 18:10:23 -080028import os.path
Tao Baoc7a6f1e2015-06-23 11:16:05 -070029import re
David Zeuthen4014a9d2016-09-30 17:29:22 -040030import shlex
Geremy Condrafd6f7512013-06-16 17:26:08 -070031import shutil
Tao Baoc72727a2017-12-07 10:33:00 -080032import subprocess
33import sys
34
35import common
Sami Tolvanen405e71d2016-02-09 12:28:58 -080036import sparse_img
Tao Baoc72727a2017-12-07 10:33:00 -080037
Ying Wangbd93d422011-10-28 17:02:30 -070038
Baligh Uddin601ddea2015-06-09 15:48:14 -070039OPTIONS = common.OPTIONS
40
Geremy Condrae8e982a2014-05-16 19:14:30 -070041FIXED_SALT = "aee087a5be3b982978c923f566a94613496b417f2af592639bc80d141e34dfe7"
Sami Tolvanenf99b5312015-05-20 07:30:57 +010042BLOCK_SIZE = 4096
Geremy Condrae8e982a2014-05-16 19:14:30 -070043
Tao Baoc72727a2017-12-07 10:33:00 -080044
Tianjie Xu149b7fb2017-09-01 15:36:08 -070045def RunCommand(cmd, verbose=None):
Tao Baoc7a6f1e2015-06-23 11:16:05 -070046 """Echo and run the given command.
Ying Wang69e9b4d2012-11-26 18:10:23 -080047
48 Args:
49 cmd: the command represented as a list of strings.
Tianjie Xu149b7fb2017-09-01 15:36:08 -070050 verbose: show commands being executed.
Ying Wang69e9b4d2012-11-26 18:10:23 -080051 Returns:
Tao Baoc7a6f1e2015-06-23 11:16:05 -070052 A tuple of the output and the exit code.
Ying Wang69e9b4d2012-11-26 18:10:23 -080053 """
Tianjie Xu149b7fb2017-09-01 15:36:08 -070054 if verbose is None:
55 verbose = OPTIONS.verbose
56 if verbose:
57 print("Running: " + " ".join(cmd))
Tao Baoc7a6f1e2015-06-23 11:16:05 -070058 p = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
59 output, _ = p.communicate()
Tianjie Xu149b7fb2017-09-01 15:36:08 -070060
61 if verbose:
62 print(output.rstrip())
Tao Baoc7a6f1e2015-06-23 11:16:05 -070063 return (output, p.returncode)
Ying Wangbd93d422011-10-28 17:02:30 -070064
Tao Baoc72727a2017-12-07 10:33:00 -080065
Sami Tolvanenf99b5312015-05-20 07:30:57 +010066def GetVerityFECSize(partition_size):
Tianjie Xue3ad41b2017-03-08 11:05:56 -080067 cmd = ["fec", "-s", str(partition_size)]
Tianjie Xu149b7fb2017-09-01 15:36:08 -070068 output, exit_code = RunCommand(cmd, False)
Tianjie Xue3ad41b2017-03-08 11:05:56 -080069 if exit_code != 0:
Sami Tolvanenf99b5312015-05-20 07:30:57 +010070 return False, 0
71 return True, int(output)
72
Tao Baoc72727a2017-12-07 10:33:00 -080073
Geremy Condrafd6f7512013-06-16 17:26:08 -070074def GetVerityTreeSize(partition_size):
Tianjie Xue3ad41b2017-03-08 11:05:56 -080075 cmd = ["build_verity_tree", "-s", str(partition_size)]
Tianjie Xu149b7fb2017-09-01 15:36:08 -070076 output, exit_code = RunCommand(cmd, False)
Tianjie Xue3ad41b2017-03-08 11:05:56 -080077 if exit_code != 0:
Geremy Condrafd6f7512013-06-16 17:26:08 -070078 return False, 0
79 return True, int(output)
80
Tao Baoc72727a2017-12-07 10:33:00 -080081
Geremy Condrafd6f7512013-06-16 17:26:08 -070082def GetVerityMetadataSize(partition_size):
Tianjie Xue3ad41b2017-03-08 11:05:56 -080083 cmd = ["system/extras/verity/build_verity_metadata.py", "size",
84 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
Sami Tolvanenf99b5312015-05-20 07:30:57 +010091def GetVeritySize(partition_size, fec_supported):
92 success, verity_tree_size = GetVerityTreeSize(partition_size)
93 if not success:
94 return 0
95 success, verity_metadata_size = GetVerityMetadataSize(partition_size)
96 if not success:
97 return 0
98 verity_size = verity_tree_size + verity_metadata_size
99 if fec_supported:
100 success, fec_size = GetVerityFECSize(partition_size + verity_size)
101 if not success:
102 return 0
103 return verity_size + fec_size
104 return verity_size
105
Tao Baoc72727a2017-12-07 10:33:00 -0800106
Sami Tolvanen405e71d2016-02-09 12:28:58 -0800107def GetSimgSize(image_file):
108 simg = sparse_img.SparseImage(image_file, build_map=False)
109 return simg.blocksize * simg.total_blocks
110
Tao Baoc72727a2017-12-07 10:33:00 -0800111
Sami Tolvanen405e71d2016-02-09 12:28:58 -0800112def ZeroPadSimg(image_file, pad_size):
113 blocks = pad_size // BLOCK_SIZE
114 print("Padding %d blocks (%d bytes)" % (blocks, pad_size))
115 simg = sparse_img.SparseImage(image_file, mode="r+b", build_map=False)
116 simg.AppendFillChunk(0, blocks)
117
Tao Baoc72727a2017-12-07 10:33:00 -0800118
Bowgo Tsai7ea994b2017-05-19 23:44:26 +0800119def AVBCalcMaxImageSize(avbtool, footer_type, partition_size, additional_args):
David Zeuthen4014a9d2016-09-30 17:29:22 -0400120 """Calculates max image size for a given partition size.
121
122 Args:
123 avbtool: String with path to avbtool.
Bowgo Tsai7ea994b2017-05-19 23:44:26 +0800124 footer_type: 'hash' or 'hashtree' for generating footer.
David Zeuthen4014a9d2016-09-30 17:29:22 -0400125 partition_size: The size of the partition in question.
126 additional_args: Additional arguments to pass to 'avbtool
127 add_hashtree_image'.
128 Returns:
129 The maximum image size or 0 if an error occurred.
130 """
Tao Baoc72727a2017-12-07 10:33:00 -0800131 cmd = [avbtool, "add_%s_footer" % footer_type,
132 "--partition_size", partition_size, "--calc_max_image_size"]
Bowgo Tsai3e599ea2017-05-26 18:30:04 +0800133 cmd.extend(shlex.split(additional_args))
134
135 (output, exit_code) = RunCommand(cmd)
David Zeuthen4014a9d2016-09-30 17:29:22 -0400136 if exit_code != 0:
137 return 0
138 else:
139 return int(output)
140
Tao Baoc72727a2017-12-07 10:33:00 -0800141
Bowgo Tsai7ea994b2017-05-19 23:44:26 +0800142def AVBAddFooter(image_path, avbtool, footer_type, partition_size,
Tao Bao2b6dfd62017-09-27 17:17:43 -0700143 partition_name, key_path, algorithm, salt,
Bowgo Tsai3e599ea2017-05-26 18:30:04 +0800144 additional_args):
David Zeuthen4014a9d2016-09-30 17:29:22 -0400145 """Adds dm-verity hashtree and AVB metadata to an image.
146
147 Args:
148 image_path: Path to image to modify.
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 partition_name: The name of the partition - will be embedded in metadata.
Bowgo Tsai3e599ea2017-05-26 18:30:04 +0800153 key_path: Path to key to use or None.
154 algorithm: Name of algorithm to use or None.
Tao Bao2b6dfd62017-09-27 17:17:43 -0700155 salt: The salt to use (a hexadecimal string) or None.
David Zeuthen4014a9d2016-09-30 17:29:22 -0400156 additional_args: Additional arguments to pass to 'avbtool
Tao Baoc72727a2017-12-07 10:33:00 -0800157 add_hashtree_image'.
158
David Zeuthen4014a9d2016-09-30 17:29:22 -0400159 Returns:
160 True if the operation succeeded.
161 """
Tao Baoc72727a2017-12-07 10:33:00 -0800162 cmd = [avbtool, "add_%s_footer" % footer_type,
163 "--partition_size", partition_size,
164 "--partition_name", partition_name,
165 "--image", image_path]
Bowgo Tsai3e599ea2017-05-26 18:30:04 +0800166
167 if key_path and algorithm:
168 cmd.extend(["--key", key_path, "--algorithm", algorithm])
Tao Bao2b6dfd62017-09-27 17:17:43 -0700169 if salt:
170 cmd.extend(["--salt", salt])
Bowgo Tsai3e599ea2017-05-26 18:30:04 +0800171
172 cmd.extend(shlex.split(additional_args))
173
174 (_, exit_code) = RunCommand(cmd)
David Zeuthen4014a9d2016-09-30 17:29:22 -0400175 return exit_code == 0
176
Tao Baoc72727a2017-12-07 10:33:00 -0800177
Sami Tolvanenf99b5312015-05-20 07:30:57 +0100178def AdjustPartitionSizeForVerity(partition_size, fec_supported):
Geremy Condrafd6f7512013-06-16 17:26:08 -0700179 """Modifies the provided partition size to account for the verity metadata.
180
181 This information is used to size the created image appropriately.
Tao Baoc72727a2017-12-07 10:33:00 -0800182
Geremy Condrafd6f7512013-06-16 17:26:08 -0700183 Args:
184 partition_size: the size of the partition to be verified.
Tao Baoc72727a2017-12-07 10:33:00 -0800185
Geremy Condrafd6f7512013-06-16 17:26:08 -0700186 Returns:
Sami Tolvanen433905f2016-09-01 15:58:35 -0700187 A tuple of the size of the partition adjusted for verity metadata, and
188 the size of verity metadata.
Geremy Condrafd6f7512013-06-16 17:26:08 -0700189 """
Sami Tolvanenf99b5312015-05-20 07:30:57 +0100190 key = "%d %d" % (partition_size, fec_supported)
191 if key in AdjustPartitionSizeForVerity.results:
192 return AdjustPartitionSizeForVerity.results[key]
193
194 hi = partition_size
195 if hi % BLOCK_SIZE != 0:
196 hi = (hi // BLOCK_SIZE) * BLOCK_SIZE
197
198 # verity tree and fec sizes depend on the partition size, which
199 # means this estimate is always going to be unnecessarily small
Sami Tolvanen433905f2016-09-01 15:58:35 -0700200 verity_size = GetVeritySize(hi, fec_supported)
201 lo = partition_size - verity_size
Sami Tolvanenf99b5312015-05-20 07:30:57 +0100202 result = lo
203
204 # do a binary search for the optimal size
205 while lo < hi:
206 i = ((lo + hi) // (2 * BLOCK_SIZE)) * BLOCK_SIZE
Sami Tolvanen433905f2016-09-01 15:58:35 -0700207 v = GetVeritySize(i, fec_supported)
208 if i + v <= partition_size:
Sami Tolvanenf99b5312015-05-20 07:30:57 +0100209 if result < i:
210 result = i
Sami Tolvanen433905f2016-09-01 15:58:35 -0700211 verity_size = v
Sami Tolvanenf99b5312015-05-20 07:30:57 +0100212 lo = i + BLOCK_SIZE
213 else:
214 hi = i
215
Tomasz Wasilczyk29ec06b2017-11-15 10:34:01 -0800216 if OPTIONS.verbose:
217 print("Adjusted partition size for verity, partition_size: {},"
218 " verity_size: {}".format(result, verity_size))
Sami Tolvanen433905f2016-09-01 15:58:35 -0700219 AdjustPartitionSizeForVerity.results[key] = (result, verity_size)
220 return (result, verity_size)
Sami Tolvanenf99b5312015-05-20 07:30:57 +0100221
Tao Baoc72727a2017-12-07 10:33:00 -0800222
Sami Tolvanenf99b5312015-05-20 07:30:57 +0100223AdjustPartitionSizeForVerity.results = {}
224
Tao Baoc72727a2017-12-07 10:33:00 -0800225
Sami Tolvanen433905f2016-09-01 15:58:35 -0700226def BuildVerityFEC(sparse_image_path, verity_path, verity_fec_path,
227 padding_size):
Tianjie Xue3ad41b2017-03-08 11:05:56 -0800228 cmd = ["fec", "-e", "-p", str(padding_size), sparse_image_path,
229 verity_path, verity_fec_path]
230 output, exit_code = RunCommand(cmd)
231 if exit_code != 0:
Tao Baoc72727a2017-12-07 10:33:00 -0800232 print("Could not build FEC data! Error: %s" % output)
Sami Tolvanenf99b5312015-05-20 07:30:57 +0100233 return False
234 return True
Geremy Condrafd6f7512013-06-16 17:26:08 -0700235
Tao Baoc72727a2017-12-07 10:33:00 -0800236
Colin Cross477cf2b2014-04-16 18:49:56 -0700237def BuildVerityTree(sparse_image_path, verity_image_path, prop_dict):
Tianjie Xue3ad41b2017-03-08 11:05:56 -0800238 cmd = ["build_verity_tree", "-A", FIXED_SALT, sparse_image_path,
239 verity_image_path]
240 output, exit_code = RunCommand(cmd)
241 if exit_code != 0:
Tao Baoc72727a2017-12-07 10:33:00 -0800242 print("Could not build verity tree! Error: %s" % output)
Geremy Condrafd6f7512013-06-16 17:26:08 -0700243 return False
244 root, salt = output.split()
245 prop_dict["verity_root_hash"] = root
246 prop_dict["verity_salt"] = salt
247 return True
248
Tao Baoc72727a2017-12-07 10:33:00 -0800249
Geremy Condrafd6f7512013-06-16 17:26:08 -0700250def BuildVerityMetadata(image_size, verity_metadata_path, root_hash, salt,
Bowgo Tsai6ceeb1a2017-10-11 16:21:48 +0800251 block_device, signer_path, key, signer_args,
252 verity_disable):
Tianjie Xue3ad41b2017-03-08 11:05:56 -0800253 cmd = ["system/extras/verity/build_verity_metadata.py", "build",
254 str(image_size), verity_metadata_path, root_hash, salt, block_device,
255 signer_path, key]
Tao Bao45810422016-10-17 16:20:12 -0700256 if signer_args:
Tianjie Xue3ad41b2017-03-08 11:05:56 -0800257 cmd.append("--signer_args=\"%s\"" % (' '.join(signer_args),))
Bowgo Tsai6ceeb1a2017-10-11 16:21:48 +0800258 if verity_disable:
259 cmd.append("--verity_disable")
Tianjie Xue3ad41b2017-03-08 11:05:56 -0800260 output, exit_code = RunCommand(cmd)
261 if exit_code != 0:
Tao Baoc72727a2017-12-07 10:33:00 -0800262 print("Could not build verity metadata! Error: %s" % output)
Geremy Condrafd6f7512013-06-16 17:26:08 -0700263 return False
264 return True
265
Tao Baoc72727a2017-12-07 10:33:00 -0800266
Geremy Condrafd6f7512013-06-16 17:26:08 -0700267def Append2Simg(sparse_image_path, unsparse_image_path, error_message):
268 """Appends the unsparse image to the given sparse image.
269
270 Args:
271 sparse_image_path: the path to the (sparse) image
272 unsparse_image_path: the path to the (unsparse) image
273 Returns:
274 True on success, False on failure.
275 """
Tianjie Xue3ad41b2017-03-08 11:05:56 -0800276 cmd = ["append2simg", sparse_image_path, unsparse_image_path]
277 output, exit_code = RunCommand(cmd)
278 if exit_code != 0:
Tao Baoc72727a2017-12-07 10:33:00 -0800279 print("%s: %s" % (error_message, output))
Geremy Condrafd6f7512013-06-16 17:26:08 -0700280 return False
281 return True
282
Tao Baoc72727a2017-12-07 10:33:00 -0800283
Sami Tolvanenff914f52015-12-18 13:24:56 +0000284def Append(target, file_to_append, error_message):
Tao Baoc72727a2017-12-07 10:33:00 -0800285 """Appends file_to_append to target."""
286 try:
287 with open(target, "a") as out_file, open(file_to_append, "r") as input_file:
Tianjie Xue3ad41b2017-03-08 11:05:56 -0800288 for line in input_file:
289 out_file.write(line)
Tao Baoc72727a2017-12-07 10:33:00 -0800290 except IOError:
291 print(error_message)
292 return False
Sami Tolvanenff914f52015-12-18 13:24:56 +0000293 return True
294
Tao Baoc72727a2017-12-07 10:33:00 -0800295
Dan Albert8b72aef2015-03-23 19:13:21 -0700296def BuildVerifiedImage(data_image_path, verity_image_path,
Sami Tolvanen4a060042015-12-18 15:50:25 +0000297 verity_metadata_path, verity_fec_path,
Sami Tolvanen433905f2016-09-01 15:58:35 -0700298 padding_size, fec_supported):
Sami Tolvanenff914f52015-12-18 13:24:56 +0000299 if not Append(verity_image_path, verity_metadata_path,
300 "Could not append verity metadata!"):
Geremy Condrafd6f7512013-06-16 17:26:08 -0700301 return False
Sami Tolvanen4a060042015-12-18 15:50:25 +0000302
303 if fec_supported:
304 # build FEC for the entire partition, including metadata
305 if not BuildVerityFEC(data_image_path, verity_image_path,
Sami Tolvanen433905f2016-09-01 15:58:35 -0700306 verity_fec_path, padding_size):
Sami Tolvanen4a060042015-12-18 15:50:25 +0000307 return False
308
309 if not Append(verity_image_path, verity_fec_path, "Could not append FEC!"):
310 return False
311
Sami Tolvanenff914f52015-12-18 13:24:56 +0000312 if not Append2Simg(data_image_path, verity_image_path,
313 "Could not append verity data!"):
Sami Tolvanenf99b5312015-05-20 07:30:57 +0100314 return False
Geremy Condrafd6f7512013-06-16 17:26:08 -0700315 return True
316
Tao Baoc72727a2017-12-07 10:33:00 -0800317
Geremy Condra6e8f53c2013-12-05 17:09:18 -0800318def UnsparseImage(sparse_image_path, replace=True):
Geremy Condrafd6f7512013-06-16 17:26:08 -0700319 img_dir = os.path.dirname(sparse_image_path)
320 unsparse_image_path = "unsparse_" + os.path.basename(sparse_image_path)
321 unsparse_image_path = os.path.join(img_dir, unsparse_image_path)
322 if os.path.exists(unsparse_image_path):
Geremy Condra6e8f53c2013-12-05 17:09:18 -0800323 if replace:
324 os.unlink(unsparse_image_path)
325 else:
326 return True, unsparse_image_path
Geremy Condrafd6f7512013-06-16 17:26:08 -0700327 inflate_command = ["simg2img", sparse_image_path, unsparse_image_path]
Tao Baocd53a892018-01-19 10:29:52 -0800328 (inflate_output, exit_code) = RunCommand(inflate_command)
Geremy Condrafd6f7512013-06-16 17:26:08 -0700329 if exit_code != 0:
Tao Baocd53a892018-01-19 10:29:52 -0800330 print("Error: '%s' failed with exit code %d:\n%s" % (
331 inflate_command, exit_code, inflate_output))
Geremy Condrafd6f7512013-06-16 17:26:08 -0700332 os.remove(unsparse_image_path)
333 return False, None
334 return True, unsparse_image_path
335
Tao Baoc72727a2017-12-07 10:33:00 -0800336
Sami Tolvanenf99b5312015-05-20 07:30:57 +0100337def MakeVerityEnabledImage(out_file, fec_supported, prop_dict):
Geremy Condrafd6f7512013-06-16 17:26:08 -0700338 """Creates an image that is verifiable using dm-verity.
339
340 Args:
341 out_file: the location to write the verifiable image at
Dan Albert8b72aef2015-03-23 19:13:21 -0700342 prop_dict: a dictionary of properties required for image creation and
343 verification
Geremy Condrafd6f7512013-06-16 17:26:08 -0700344 Returns:
345 True on success, False otherwise.
346 """
347 # get properties
Sami Tolvanen433905f2016-09-01 15:58:35 -0700348 image_size = int(prop_dict["partition_size"])
Geremy Condrafd6f7512013-06-16 17:26:08 -0700349 block_dev = prop_dict["verity_block_device"]
Paul Lawrencea37b2bb2014-11-13 17:54:30 -0800350 signer_key = prop_dict["verity_key"] + ".pk8"
Baligh Uddin601ddea2015-06-09 15:48:14 -0700351 if OPTIONS.verity_signer_path is not None:
Tao Bao45810422016-10-17 16:20:12 -0700352 signer_path = OPTIONS.verity_signer_path
Baligh Uddin601ddea2015-06-09 15:48:14 -0700353 else:
354 signer_path = prop_dict["verity_signer_cmd"]
Tao Bao45810422016-10-17 16:20:12 -0700355 signer_args = OPTIONS.verity_signer_args
Geremy Condrafd6f7512013-06-16 17:26:08 -0700356
357 # make a tempdir
Tao Bao1c830bf2017-12-25 10:43:47 -0800358 tempdir_name = common.MakeTempDir(suffix="_verity_images")
Geremy Condrafd6f7512013-06-16 17:26:08 -0700359
360 # get partial image paths
361 verity_image_path = os.path.join(tempdir_name, "verity.img")
362 verity_metadata_path = os.path.join(tempdir_name, "verity_metadata.img")
Sami Tolvanenf99b5312015-05-20 07:30:57 +0100363 verity_fec_path = os.path.join(tempdir_name, "verity_fec.img")
Geremy Condrafd6f7512013-06-16 17:26:08 -0700364
365 # build the verity tree and get the root hash and salt
Colin Cross477cf2b2014-04-16 18:49:56 -0700366 if not BuildVerityTree(out_file, verity_image_path, prop_dict):
Geremy Condrafd6f7512013-06-16 17:26:08 -0700367 return False
368
369 # build the metadata blocks
370 root_hash = prop_dict["verity_root_hash"]
371 salt = prop_dict["verity_salt"]
Bowgo Tsai6ceeb1a2017-10-11 16:21:48 +0800372 verity_disable = "verity_disable" in prop_dict
Dan Albert8b72aef2015-03-23 19:13:21 -0700373 if not BuildVerityMetadata(image_size, verity_metadata_path, root_hash, salt,
Bowgo Tsai6ceeb1a2017-10-11 16:21:48 +0800374 block_dev, signer_path, signer_key, signer_args,
375 verity_disable):
Geremy Condrafd6f7512013-06-16 17:26:08 -0700376 return False
377
378 # build the full verified image
Sami Tolvanen433905f2016-09-01 15:58:35 -0700379 target_size = int(prop_dict["original_partition_size"])
380 verity_size = int(prop_dict["verity_size"])
381
382 padding_size = target_size - image_size - verity_size
383 assert padding_size >= 0
384
Geremy Condrafd6f7512013-06-16 17:26:08 -0700385 if not BuildVerifiedImage(out_file,
386 verity_image_path,
Sami Tolvanen4a060042015-12-18 15:50:25 +0000387 verity_metadata_path,
388 verity_fec_path,
Sami Tolvanen433905f2016-09-01 15:58:35 -0700389 padding_size,
Sami Tolvanen4a060042015-12-18 15:50:25 +0000390 fec_supported):
Geremy Condrafd6f7512013-06-16 17:26:08 -0700391 return False
392
Geremy Condrafd6f7512013-06-16 17:26:08 -0700393 return True
394
Tao Baoc72727a2017-12-07 10:33:00 -0800395
Mohamad Ayyashf8765552016-03-02 21:07:23 -0800396def ConvertBlockMapToBaseFs(block_map_file):
Tao Bao1c830bf2017-12-25 10:43:47 -0800397 base_fs_file = common.MakeTempFile(prefix="script_gen_", suffix=".base_fs")
Mohamad Ayyashf8765552016-03-02 21:07:23 -0800398 convert_command = ["blk_alloc_to_base_fs", block_map_file, base_fs_file]
399 (_, exit_code) = RunCommand(convert_command)
Tao Baoc72727a2017-12-07 10:33:00 -0800400 return base_fs_file if exit_code == 0 else None
Mohamad Ayyashf8765552016-03-02 21:07:23 -0800401
Tao Baod4349f22017-12-07 23:01:25 -0800402
403def CheckHeadroom(ext4fs_output, prop_dict):
404 """Checks if there's enough headroom space available.
405
406 Headroom is the reserved space on system image (via PRODUCT_SYSTEM_HEADROOM),
407 which is useful for devices with low disk space that have system image
408 variation between builds. The 'partition_headroom' in prop_dict is the size
409 in bytes, while the numbers in 'ext4fs_output' are for 4K-blocks.
410
411 Args:
412 ext4fs_output: The output string from mke2fs command.
413 prop_dict: The property dict.
414
415 Returns:
416 The check result.
Tao Baod8a953d2018-01-02 21:19:27 -0800417
418 Raises:
419 AssertionError: On invalid input.
Tao Baod4349f22017-12-07 23:01:25 -0800420 """
Tao Baod8a953d2018-01-02 21:19:27 -0800421 assert ext4fs_output is not None
422 assert prop_dict.get('fs_type', '').startswith('ext4')
423 assert 'partition_headroom' in prop_dict
424 assert 'mount_point' in prop_dict
425
Tao Baod4349f22017-12-07 23:01:25 -0800426 ext4fs_stats = re.compile(
427 r'Created filesystem with .* (?P<used_blocks>[0-9]+)/'
428 r'(?P<total_blocks>[0-9]+) blocks')
Tao Baoc72727a2017-12-07 10:33:00 -0800429 last_line = ext4fs_output.strip().split('\n')[-1]
430 m = ext4fs_stats.match(last_line)
Tao Baod4349f22017-12-07 23:01:25 -0800431 used_blocks = int(m.groupdict().get('used_blocks'))
432 total_blocks = int(m.groupdict().get('total_blocks'))
Tao Baod8a953d2018-01-02 21:19:27 -0800433 headroom_blocks = int(prop_dict['partition_headroom']) / BLOCK_SIZE
Tao Baod4349f22017-12-07 23:01:25 -0800434 adjusted_blocks = total_blocks - headroom_blocks
435 if used_blocks > adjusted_blocks:
Tao Baod8a953d2018-01-02 21:19:27 -0800436 mount_point = prop_dict["mount_point"]
Tao Baod4349f22017-12-07 23:01:25 -0800437 print("Error: Not enough room on %s (total: %d blocks, used: %d blocks, "
438 "headroom: %d blocks, available: %d blocks)" % (
439 mount_point, total_blocks, used_blocks, headroom_blocks,
440 adjusted_blocks))
441 return False
442 return True
443
444
Thierry Strudel74a81e62015-07-09 09:54:55 -0700445def BuildImage(in_dir, prop_dict, out_file, target_out=None):
Ying Wangbd93d422011-10-28 17:02:30 -0700446 """Build an image to out_file from in_dir with property prop_dict.
447
448 Args:
449 in_dir: path of input directory.
450 prop_dict: property dictionary.
451 out_file: path of the output image file.
Tao Baoc72727a2017-12-07 10:33:00 -0800452 target_out: path of the product out directory to read device specific FS
453 config files.
Ying Wangbd93d422011-10-28 17:02:30 -0700454
455 Returns:
456 True iff the image is built successfully.
457 """
Tao Baof3282b42015-04-01 11:21:55 -0700458 # system_root_image=true: build a system.img that combines the contents of
459 # /system and the ramdisk, and can be mounted at the root of the file system.
Ying Wanga2292c92015-03-24 19:07:40 -0700460 origin_in = in_dir
461 fs_config = prop_dict.get("fs_config")
Tao Baoc72727a2017-12-07 10:33:00 -0800462 if (prop_dict.get("system_root_image") == "true" and
463 prop_dict["mount_point"] == "system"):
Tao Bao1c830bf2017-12-25 10:43:47 -0800464 in_dir = common.MakeTempDir()
Tao Baoc72727a2017-12-07 10:33:00 -0800465 # Change the mount point to "/".
Ying Wanga2292c92015-03-24 19:07:40 -0700466 prop_dict["mount_point"] = "/"
467 if fs_config:
468 # We need to merge the fs_config files of system and ramdisk.
Tao Bao1c830bf2017-12-25 10:43:47 -0800469 merged_fs_config = common.MakeTempFile(prefix="root_fs_config",
470 suffix=".txt")
Ying Wanga2292c92015-03-24 19:07:40 -0700471 with open(merged_fs_config, "w") as fw:
472 if "ramdisk_fs_config" in prop_dict:
473 with open(prop_dict["ramdisk_fs_config"]) as fr:
474 fw.writelines(fr.readlines())
475 with open(fs_config) as fr:
476 fw.writelines(fr.readlines())
477 fs_config = merged_fs_config
478
Ying Wangbd93d422011-10-28 17:02:30 -0700479 build_command = []
480 fs_type = prop_dict.get("fs_type", "")
Tao Baoc72727a2017-12-07 10:33:00 -0800481 run_e2fsck = False
Geremy Condrafd6f7512013-06-16 17:26:08 -0700482
Mohamad Ayyashdd063522015-03-24 12:42:03 -0700483 fs_spans_partition = True
484 if fs_type.startswith("squash"):
Tao Baoc7a6f1e2015-06-23 11:16:05 -0700485 fs_spans_partition = False
Mohamad Ayyashdd063522015-03-24 12:42:03 -0700486
Daniel Rosenbergf4eabc32014-07-10 15:42:38 -0700487 is_verity_partition = "verity_block_device" in prop_dict
Geremy Condra5b5f4952014-05-05 22:19:37 -0700488 verity_supported = prop_dict.get("verity") == "true"
Sami Tolvanenf99b5312015-05-20 07:30:57 +0100489 verity_fec_supported = prop_dict.get("verity_fec") == "true"
490
Tao Baoc7a6f1e2015-06-23 11:16:05 -0700491 # Adjust the partition size to make room for the hashes if this is to be
492 # verified.
Sami Tolvanen405e71d2016-02-09 12:28:58 -0800493 if verity_supported and is_verity_partition:
Geremy Condrafd6f7512013-06-16 17:26:08 -0700494 partition_size = int(prop_dict.get("partition_size"))
Tao Baoc72727a2017-12-07 10:33:00 -0800495 (adjusted_size, verity_size) = AdjustPartitionSizeForVerity(
496 partition_size, verity_fec_supported)
Geremy Condrafd6f7512013-06-16 17:26:08 -0700497 if not adjusted_size:
498 return False
499 prop_dict["partition_size"] = str(adjusted_size)
500 prop_dict["original_partition_size"] = str(partition_size)
Sami Tolvanen433905f2016-09-01 15:58:35 -0700501 prop_dict["verity_size"] = str(verity_size)
Geremy Condrafd6f7512013-06-16 17:26:08 -0700502
Bowgo Tsai7ea994b2017-05-19 23:44:26 +0800503 # Adjust partition size for AVB hash footer or AVB hashtree footer.
504 avb_footer_type = ''
505 if prop_dict.get("avb_hash_enable") == "true":
506 avb_footer_type = 'hash'
507 elif prop_dict.get("avb_hashtree_enable") == "true":
508 avb_footer_type = 'hashtree'
509
510 if avb_footer_type:
Bowgo Tsai3e599ea2017-05-26 18:30:04 +0800511 avbtool = prop_dict["avb_avbtool"]
512 partition_size = prop_dict["partition_size"]
Bowgo Tsai7ea994b2017-05-19 23:44:26 +0800513 # avb_add_hash_footer_args or avb_add_hashtree_footer_args.
514 additional_args = prop_dict["avb_add_" + avb_footer_type + "_footer_args"]
Tao Baoc72727a2017-12-07 10:33:00 -0800515 max_image_size = AVBCalcMaxImageSize(avbtool, avb_footer_type,
516 partition_size, additional_args)
David Zeuthen4014a9d2016-09-30 17:29:22 -0400517 if max_image_size == 0:
518 return False
519 prop_dict["partition_size"] = str(max_image_size)
Bowgo Tsai3e599ea2017-05-26 18:30:04 +0800520 prop_dict["original_partition_size"] = partition_size
David Zeuthen4014a9d2016-09-30 17:29:22 -0400521
Ying Wangbd93d422011-10-28 17:02:30 -0700522 if fs_type.startswith("ext"):
Adrien Schildknecht9a072cc2016-11-18 17:06:29 -0800523 build_command = [prop_dict["ext_mkuserimg"]]
Ying Wangbd93d422011-10-28 17:02:30 -0700524 if "extfs_sparse_flag" in prop_dict:
525 build_command.append(prop_dict["extfs_sparse_flag"])
Tao Baoc72727a2017-12-07 10:33:00 -0800526 run_e2fsck = True
Ying Wangbd93d422011-10-28 17:02:30 -0700527 build_command.extend([in_dir, out_file, fs_type,
528 prop_dict["mount_point"]])
Doug Zongker850b8072013-12-05 15:54:55 -0800529 build_command.append(prop_dict["partition_size"])
Ying Wangf3b86352014-11-18 18:03:13 -0800530 if "journal_size" in prop_dict:
531 build_command.extend(["-j", prop_dict["journal_size"]])
Doug Zongker850b8072013-12-05 15:54:55 -0800532 if "timestamp" in prop_dict:
533 build_command.extend(["-T", str(prop_dict["timestamp"])])
Ying Wanga2292c92015-03-24 19:07:40 -0700534 if fs_config:
Doug Zongker82822822014-06-16 09:10:55 -0700535 build_command.extend(["-C", fs_config])
Thierry Strudel74a81e62015-07-09 09:54:55 -0700536 if target_out:
537 build_command.extend(["-D", target_out])
Ying Wanga2292c92015-03-24 19:07:40 -0700538 if "block_list" in prop_dict:
539 build_command.extend(["-B", prop_dict["block_list"]])
Mohamad Ayyashf8765552016-03-02 21:07:23 -0800540 if "base_fs_file" in prop_dict:
541 base_fs_file = ConvertBlockMapToBaseFs(prop_dict["base_fs_file"])
542 if base_fs_file is None:
543 return False
544 build_command.extend(["-d", base_fs_file])
Christoffer Dall8ed01f32014-12-17 21:34:12 +0100545 build_command.extend(["-L", prop_dict["mount_point"]])
Patrick Tjina1900842016-10-20 10:58:12 -0700546 if "extfs_inode_count" in prop_dict:
547 build_command.extend(["-i", prop_dict["extfs_inode_count"]])
Connor O'Brien20f08c32017-01-05 16:48:14 -0800548 if "flash_erase_block_size" in prop_dict:
549 build_command.extend(["-e", prop_dict["flash_erase_block_size"]])
550 if "flash_logical_block_size" in prop_dict:
551 build_command.extend(["-o", prop_dict["flash_logical_block_size"]])
Tao Baod86e3112017-09-22 15:45:33 -0700552 # Specify UUID and hash_seed if using mke2fs.
553 if prop_dict["ext_mkuserimg"] == "mkuserimg_mke2fs.sh":
554 if "uuid" in prop_dict:
555 build_command.extend(["-U", prop_dict["uuid"]])
556 if "hash_seed" in prop_dict:
557 build_command.extend(["-S", prop_dict["hash_seed"]])
Ying Wanga2292c92015-03-24 19:07:40 -0700558 if "selinux_fc" in prop_dict:
Kenny Rootf32dc712012-04-08 10:42:34 -0700559 build_command.append(prop_dict["selinux_fc"])
Mohamad Ayyashb97746e2015-03-03 12:30:37 -0800560 elif fs_type.startswith("squash"):
561 build_command = ["mksquashfsimage.sh"]
562 build_command.extend([in_dir, out_file])
Todd Poynorb2a555e2015-12-15 18:00:14 -0800563 if "squashfs_sparse_flag" in prop_dict:
564 build_command.extend([prop_dict["squashfs_sparse_flag"]])
Mohamad Ayyashb97746e2015-03-03 12:30:37 -0800565 build_command.extend(["-m", prop_dict["mount_point"]])
Thierry Strudel74a81e62015-07-09 09:54:55 -0700566 if target_out:
567 build_command.extend(["-d", target_out])
Mohamad Ayyash88378822016-04-07 22:10:51 -0700568 if fs_config:
569 build_command.extend(["-C", fs_config])
Ying Wanga2292c92015-03-24 19:07:40 -0700570 if "selinux_fc" in prop_dict:
Mohamad Ayyashb97746e2015-03-03 12:30:37 -0800571 build_command.extend(["-c", prop_dict["selinux_fc"]])
Mohamad Ayyashc3484f72016-06-13 09:46:58 -0700572 if "block_list" in prop_dict:
573 build_command.extend(["-B", prop_dict["block_list"]])
Ng Zhi An9446c1d2018-01-19 15:51:46 -0800574 if "squashfs_block_size" in prop_dict:
575 build_command.extend(["-b", prop_dict["squashfs_block_size"]])
Simon Wilsonf86e7ee2015-06-17 12:35:15 -0700576 if "squashfs_compressor" in prop_dict:
577 build_command.extend(["-z", prop_dict["squashfs_compressor"]])
578 if "squashfs_compressor_opt" in prop_dict:
579 build_command.extend(["-zo", prop_dict["squashfs_compressor_opt"]])
Tao Baoc72727a2017-12-07 10:33:00 -0800580 if prop_dict.get("squashfs_disable_4k_align") == "true":
Mohamad Ayyash1b6d3482016-06-15 15:53:07 -0700581 build_command.extend(["-a"])
JP Abgrall5bfed5a2014-06-16 14:17:40 -0700582 elif fs_type.startswith("f2fs"):
583 build_command = ["mkf2fsuserimg.sh"]
584 build_command.extend([out_file, prop_dict["partition_size"]])
Jaegeuk Kim2ea1eba2017-11-28 19:21:28 -0800585 if fs_config:
586 build_command.extend(["-C", fs_config])
587 build_command.extend(["-f", in_dir])
588 if target_out:
589 build_command.extend(["-D", target_out])
590 if "selinux_fc" in prop_dict:
591 build_command.extend(["-s", prop_dict["selinux_fc"]])
592 build_command.extend(["-t", prop_dict["mount_point"]])
593 if "timestamp" in prop_dict:
594 build_command.extend(["-T", str(prop_dict["timestamp"])])
595 build_command.extend(["-L", prop_dict["mount_point"]])
Ying Wangbd93d422011-10-28 17:02:30 -0700596 else:
Elliott Hughes305b0882016-06-15 17:04:54 -0700597 print("Error: unknown filesystem type '%s'" % (fs_type))
598 return False
Ying Wangbd93d422011-10-28 17:02:30 -0700599
Ying Wanga2292c92015-03-24 19:07:40 -0700600 if in_dir != origin_in:
601 # Construct a staging directory of the root file system.
602 ramdisk_dir = prop_dict.get("ramdisk_dir")
603 if ramdisk_dir:
604 shutil.rmtree(in_dir)
605 shutil.copytree(ramdisk_dir, in_dir, symlinks=True)
606 staging_system = os.path.join(in_dir, "system")
607 shutil.rmtree(staging_system, ignore_errors=True)
608 shutil.copytree(origin_in, staging_system, symlinks=True)
Tao Baoc7a6f1e2015-06-23 11:16:05 -0700609
Tao Baoc72727a2017-12-07 10:33:00 -0800610 (mkfs_output, exit_code) = RunCommand(build_command)
Ying Wang69e9b4d2012-11-26 18:10:23 -0800611 if exit_code != 0:
Tao Baocd53a892018-01-19 10:29:52 -0800612 print("Error: '%s' failed with exit code %d:\n%s" % (
613 build_command, exit_code, mkfs_output))
Ying Wang69e9b4d2012-11-26 18:10:23 -0800614 return False
615
Tao Baod4349f22017-12-07 23:01:25 -0800616 # Check if there's enough headroom space available for ext4 image.
Tao Bao79d52f82017-12-07 14:07:44 -0800617 if "partition_headroom" in prop_dict and fs_type.startswith("ext4"):
Tao Baoc72727a2017-12-07 10:33:00 -0800618 if not CheckHeadroom(mkfs_output, prop_dict):
Tao Baoc7a6f1e2015-06-23 11:16:05 -0700619 return False
620
Mohamad Ayyashdd063522015-03-24 12:42:03 -0700621 if not fs_spans_partition:
622 mount_point = prop_dict.get("mount_point")
623 partition_size = int(prop_dict.get("partition_size"))
Sami Tolvanen405e71d2016-02-09 12:28:58 -0800624 image_size = GetSimgSize(out_file)
Mohamad Ayyashdd063522015-03-24 12:42:03 -0700625 if image_size > partition_size:
Tao Baoc7a6f1e2015-06-23 11:16:05 -0700626 print("Error: %s image size of %d is larger than partition size of "
627 "%d" % (mount_point, image_size, partition_size))
628 return False
Mohamad Ayyashdd063522015-03-24 12:42:03 -0700629 if verity_supported and is_verity_partition:
Sami Tolvanen405e71d2016-02-09 12:28:58 -0800630 ZeroPadSimg(out_file, partition_size - image_size)
Mohamad Ayyashdd063522015-03-24 12:42:03 -0700631
Tao Baoc72727a2017-12-07 10:33:00 -0800632 # Create the verified image if this is to be verified.
Geremy Condra5b5f4952014-05-05 22:19:37 -0700633 if verity_supported and is_verity_partition:
Sami Tolvanenf99b5312015-05-20 07:30:57 +0100634 if not MakeVerityEnabledImage(out_file, verity_fec_supported, prop_dict):
Geremy Condrafd6f7512013-06-16 17:26:08 -0700635 return False
636
Bowgo Tsai7ea994b2017-05-19 23:44:26 +0800637 # Add AVB HASH or HASHTREE footer (metadata).
638 if avb_footer_type:
Bowgo Tsai3e599ea2017-05-26 18:30:04 +0800639 avbtool = prop_dict["avb_avbtool"]
640 original_partition_size = prop_dict["original_partition_size"]
David Zeuthen4014a9d2016-09-30 17:29:22 -0400641 partition_name = prop_dict["partition_name"]
Bowgo Tsai3e599ea2017-05-26 18:30:04 +0800642 # key_path and algorithm are only available when chain partition is used.
643 key_path = prop_dict.get("avb_key_path")
644 algorithm = prop_dict.get("avb_algorithm")
Tao Bao2b6dfd62017-09-27 17:17:43 -0700645 salt = prop_dict.get("avb_salt")
Bowgo Tsai7ea994b2017-05-19 23:44:26 +0800646 # avb_add_hash_footer_args or avb_add_hashtree_footer_args
647 additional_args = prop_dict["avb_add_" + avb_footer_type + "_footer_args"]
Tao Baoc72727a2017-12-07 10:33:00 -0800648 if not AVBAddFooter(out_file, avbtool, avb_footer_type,
649 original_partition_size, partition_name, key_path,
650 algorithm, salt, additional_args):
David Zeuthen4014a9d2016-09-30 17:29:22 -0400651 return False
652
Tao Baoc72727a2017-12-07 10:33:00 -0800653 if run_e2fsck and prop_dict.get("skip_fsck") != "true":
Geremy Condra6e8f53c2013-12-05 17:09:18 -0800654 success, unsparse_image = UnsparseImage(out_file, replace=False)
Geremy Condrafd6f7512013-06-16 17:26:08 -0700655 if not success:
Ying Wang69e9b4d2012-11-26 18:10:23 -0800656 return False
657
658 # Run e2fsck on the inflated image file
659 e2fsck_command = ["e2fsck", "-f", "-n", unsparse_image]
Tao Baocd53a892018-01-19 10:29:52 -0800660 (e2fsck_output, exit_code) = RunCommand(e2fsck_command)
Ying Wang69e9b4d2012-11-26 18:10:23 -0800661
662 os.remove(unsparse_image)
663
Elliott Hughes73ff57f2017-12-06 12:16:39 -0800664 if exit_code != 0:
Tao Baocd53a892018-01-19 10:29:52 -0800665 print("Error: '%s' failed with exit code %d:\n%s" % (
666 e2fsck_command, exit_code, e2fsck_output))
Elliott Hughes73ff57f2017-12-06 12:16:39 -0800667 return False
668
669 return True
Ying Wangbd93d422011-10-28 17:02:30 -0700670
671
672def ImagePropFromGlobalDict(glob_dict, mount_point):
673 """Build an image property dictionary from the global dictionary.
674
675 Args:
676 glob_dict: the global dictionary from the build system.
677 mount_point: such as "system", "data" etc.
678 """
Doug Zongker1ad7ade2013-12-06 11:53:27 -0800679 d = {}
Tao Bao052ae352015-09-28 13:44:13 -0700680
Tao Bao822f5842015-09-30 16:01:14 -0700681 if "build.prop" in glob_dict:
682 bp = glob_dict["build.prop"]
683 if "ro.build.date.utc" in bp:
684 d["timestamp"] = bp["ro.build.date.utc"]
Ying Wang9f8e8db2011-11-04 11:37:01 -0700685
686 def copy_prop(src_p, dest_p):
687 if src_p in glob_dict:
688 d[dest_p] = str(glob_dict[src_p])
689
Ying Wangbd93d422011-10-28 17:02:30 -0700690 common_props = (
Ying Wangbd93d422011-10-28 17:02:30 -0700691 "extfs_sparse_flag",
Todd Poynorb2a555e2015-12-15 18:00:14 -0800692 "squashfs_sparse_flag",
Kenny Rootf32dc712012-04-08 10:42:34 -0700693 "selinux_fc",
Ying Wang6a42a252013-02-27 13:54:02 -0800694 "skip_fsck",
Adrien Schildknecht9a072cc2016-11-18 17:06:29 -0800695 "ext_mkuserimg",
Geremy Condrafd6f7512013-06-16 17:26:08 -0700696 "verity",
Geremy Condrafd6f7512013-06-16 17:26:08 -0700697 "verity_key",
Sami Tolvanenf99b5312015-05-20 07:30:57 +0100698 "verity_signer_cmd",
David Zeuthen4014a9d2016-09-30 17:29:22 -0400699 "verity_fec",
Bowgo Tsai6ceeb1a2017-10-11 16:21:48 +0800700 "verity_disable",
Bowgo Tsai3e599ea2017-05-26 18:30:04 +0800701 "avb_enable",
Tao Bao2b6dfd62017-09-27 17:17:43 -0700702 "avb_avbtool",
703 "avb_salt",
704 )
Ying Wangbd93d422011-10-28 17:02:30 -0700705 for p in common_props:
Ying Wang9f8e8db2011-11-04 11:37:01 -0700706 copy_prop(p, p)
Ying Wangbd93d422011-10-28 17:02:30 -0700707
708 d["mount_point"] = mount_point
709 if mount_point == "system":
Bowgo Tsai3e599ea2017-05-26 18:30:04 +0800710 copy_prop("avb_system_hashtree_enable", "avb_hashtree_enable")
711 copy_prop("avb_system_add_hashtree_footer_args",
712 "avb_add_hashtree_footer_args")
713 copy_prop("avb_system_key_path", "avb_key_path")
714 copy_prop("avb_system_algorithm", "avb_algorithm")
Ying Wang9f8e8db2011-11-04 11:37:01 -0700715 copy_prop("fs_type", "fs_type")
Julius D'souza001c6762017-05-03 13:43:27 -0700716 # Copy the generic system fs type first, override with specific one if
Dan Albert8b72aef2015-03-23 19:13:21 -0700717 # available.
Mohamad Ayyashb97746e2015-03-03 12:30:37 -0800718 copy_prop("system_fs_type", "fs_type")
Julius D'souza001c6762017-05-03 13:43:27 -0700719 copy_prop("system_headroom", "partition_headroom")
Ying Wang9f8e8db2011-11-04 11:37:01 -0700720 copy_prop("system_size", "partition_size")
Ying Wangf3b86352014-11-18 18:03:13 -0800721 copy_prop("system_journal_size", "journal_size")
Daniel Rosenbergf4eabc32014-07-10 15:42:38 -0700722 copy_prop("system_verity_block_device", "verity_block_device")
Tao Baof3282b42015-04-01 11:21:55 -0700723 copy_prop("system_root_image", "system_root_image")
724 copy_prop("ramdisk_dir", "ramdisk_dir")
Tao Bao84e75682015-07-19 02:38:53 -0700725 copy_prop("ramdisk_fs_config", "ramdisk_fs_config")
Simon Wilsonf86e7ee2015-06-17 12:35:15 -0700726 copy_prop("system_squashfs_compressor", "squashfs_compressor")
727 copy_prop("system_squashfs_compressor_opt", "squashfs_compressor_opt")
Mohamad Ayyashdfec8152016-05-24 12:59:30 -0700728 copy_prop("system_squashfs_block_size", "squashfs_block_size")
Mohamad Ayyash1b6d3482016-06-15 15:53:07 -0700729 copy_prop("system_squashfs_disable_4k_align", "squashfs_disable_4k_align")
Mohamad Ayyashf8765552016-03-02 21:07:23 -0800730 copy_prop("system_base_fs_file", "base_fs_file")
Patrick Tjina1900842016-10-20 10:58:12 -0700731 copy_prop("system_extfs_inode_count", "extfs_inode_count")
Alex Light4e358ab2016-06-16 14:47:10 -0700732 elif mount_point == "system_other":
Tao Baoc72727a2017-12-07 10:33:00 -0800733 # We inherit the selinux policies of /system since we contain some of its
734 # files.
Alex Light4e358ab2016-06-16 14:47:10 -0700735 d["mount_point"] = "system"
Bowgo Tsai3e599ea2017-05-26 18:30:04 +0800736 copy_prop("avb_system_hashtree_enable", "avb_hashtree_enable")
737 copy_prop("avb_system_add_hashtree_footer_args",
738 "avb_add_hashtree_footer_args")
739 copy_prop("avb_system_key_path", "avb_key_path")
740 copy_prop("avb_system_algorithm", "avb_algorithm")
Alex Light4e358ab2016-06-16 14:47:10 -0700741 copy_prop("fs_type", "fs_type")
742 copy_prop("system_fs_type", "fs_type")
743 copy_prop("system_size", "partition_size")
744 copy_prop("system_journal_size", "journal_size")
745 copy_prop("system_verity_block_device", "verity_block_device")
Alex Light4e358ab2016-06-16 14:47:10 -0700746 copy_prop("system_squashfs_compressor", "squashfs_compressor")
747 copy_prop("system_squashfs_compressor_opt", "squashfs_compressor_opt")
748 copy_prop("system_squashfs_block_size", "squashfs_block_size")
749 copy_prop("system_base_fs_file", "base_fs_file")
Patrick Tjina1900842016-10-20 10:58:12 -0700750 copy_prop("system_extfs_inode_count", "extfs_inode_count")
Ying Wangbd93d422011-10-28 17:02:30 -0700751 elif mount_point == "data":
JP Abgrall5bfed5a2014-06-16 14:17:40 -0700752 # Copy the generic fs type first, override with specific one if available.
Ying Wang9f8e8db2011-11-04 11:37:01 -0700753 copy_prop("fs_type", "fs_type")
JP Abgrall5bfed5a2014-06-16 14:17:40 -0700754 copy_prop("userdata_fs_type", "fs_type")
Ying Wang9f8e8db2011-11-04 11:37:01 -0700755 copy_prop("userdata_size", "partition_size")
Tao Baoc72727a2017-12-07 10:33:00 -0800756 copy_prop("flash_logical_block_size", "flash_logical_block_size")
Connor O'Brien20f08c32017-01-05 16:48:14 -0800757 copy_prop("flash_erase_block_size", "flash_erase_block_size")
Ying Wang9f8e8db2011-11-04 11:37:01 -0700758 elif mount_point == "cache":
759 copy_prop("cache_fs_type", "fs_type")
760 copy_prop("cache_size", "partition_size")
Ying Wanga0febe52013-03-20 11:02:05 -0700761 elif mount_point == "vendor":
Bowgo Tsai3e599ea2017-05-26 18:30:04 +0800762 copy_prop("avb_vendor_hashtree_enable", "avb_hashtree_enable")
763 copy_prop("avb_vendor_add_hashtree_footer_args",
764 "avb_add_hashtree_footer_args")
765 copy_prop("avb_vendor_key_path", "avb_key_path")
766 copy_prop("avb_vendor_algorithm", "avb_algorithm")
Ying Wanga0febe52013-03-20 11:02:05 -0700767 copy_prop("vendor_fs_type", "fs_type")
768 copy_prop("vendor_size", "partition_size")
Ying Wangf3b86352014-11-18 18:03:13 -0800769 copy_prop("vendor_journal_size", "journal_size")
Daniel Rosenbergf4eabc32014-07-10 15:42:38 -0700770 copy_prop("vendor_verity_block_device", "verity_block_device")
Patrick Tjine11aa502016-02-09 15:40:38 -0800771 copy_prop("vendor_squashfs_compressor", "squashfs_compressor")
772 copy_prop("vendor_squashfs_compressor_opt", "squashfs_compressor_opt")
Mohamad Ayyashdfec8152016-05-24 12:59:30 -0700773 copy_prop("vendor_squashfs_block_size", "squashfs_block_size")
Mohamad Ayyash1b6d3482016-06-15 15:53:07 -0700774 copy_prop("vendor_squashfs_disable_4k_align", "squashfs_disable_4k_align")
Mohamad Ayyashf8765552016-03-02 21:07:23 -0800775 copy_prop("vendor_base_fs_file", "base_fs_file")
Patrick Tjina1900842016-10-20 10:58:12 -0700776 copy_prop("vendor_extfs_inode_count", "extfs_inode_count")
Ying Wangb8888432014-03-11 17:13:27 -0700777 elif mount_point == "oem":
778 copy_prop("fs_type", "fs_type")
779 copy_prop("oem_size", "partition_size")
Ying Wangf3b86352014-11-18 18:03:13 -0800780 copy_prop("oem_journal_size", "journal_size")
Patrick Tjina1900842016-10-20 10:58:12 -0700781 copy_prop("oem_extfs_inode_count", "extfs_inode_count")
David Zeuthen4014a9d2016-09-30 17:29:22 -0400782 d["partition_name"] = mount_point
Ying Wangbd93d422011-10-28 17:02:30 -0700783 return d
784
785
786def LoadGlobalDict(filename):
787 """Load "name=value" pairs from filename"""
788 d = {}
789 f = open(filename)
790 for line in f:
791 line = line.strip()
792 if not line or line.startswith("#"):
793 continue
794 k, v = line.split("=", 1)
795 d[k] = v
796 f.close()
797 return d
798
799
800def main(argv):
Thierry Strudel74a81e62015-07-09 09:54:55 -0700801 if len(argv) != 4:
Tao Baoc72727a2017-12-07 10:33:00 -0800802 print(__doc__)
Ying Wangbd93d422011-10-28 17:02:30 -0700803 sys.exit(1)
804
805 in_dir = argv[0]
806 glob_dict_file = argv[1]
807 out_file = argv[2]
Thierry Strudel74a81e62015-07-09 09:54:55 -0700808 target_out = argv[3]
Ying Wangbd93d422011-10-28 17:02:30 -0700809
810 glob_dict = LoadGlobalDict(glob_dict_file)
Ying Wangae61f502015-03-12 18:30:39 -0700811 if "mount_point" in glob_dict:
Tao Baoc7a6f1e2015-06-23 11:16:05 -0700812 # The caller knows the mount point and provides a dictionay needed by
813 # BuildImage().
Ying Wangae61f502015-03-12 18:30:39 -0700814 image_properties = glob_dict
Ying Wang9f8e8db2011-11-04 11:37:01 -0700815 else:
Ying Wangae61f502015-03-12 18:30:39 -0700816 image_filename = os.path.basename(out_file)
817 mount_point = ""
818 if image_filename == "system.img":
819 mount_point = "system"
Alex Light4e358ab2016-06-16 14:47:10 -0700820 elif image_filename == "system_other.img":
821 mount_point = "system_other"
Ying Wangae61f502015-03-12 18:30:39 -0700822 elif image_filename == "userdata.img":
823 mount_point = "data"
824 elif image_filename == "cache.img":
825 mount_point = "cache"
826 elif image_filename == "vendor.img":
827 mount_point = "vendor"
828 elif image_filename == "oem.img":
829 mount_point = "oem"
830 else:
Tao Baoc72727a2017-12-07 10:33:00 -0800831 print("error: unknown image file name ", image_filename, file=sys.stderr)
Tao Bao1c830bf2017-12-25 10:43:47 -0800832 sys.exit(1)
Ying Wangbd93d422011-10-28 17:02:30 -0700833
Ying Wangae61f502015-03-12 18:30:39 -0700834 image_properties = ImagePropFromGlobalDict(glob_dict, mount_point)
835
Thierry Strudel74a81e62015-07-09 09:54:55 -0700836 if not BuildImage(in_dir, image_properties, out_file, target_out):
Tao Baoc72727a2017-12-07 10:33:00 -0800837 print("error: failed to build %s from %s" % (out_file, in_dir),
838 file=sys.stderr)
Tao Bao1c830bf2017-12-25 10:43:47 -0800839 sys.exit(1)
Ying Wangbd93d422011-10-28 17:02:30 -0700840
841
842if __name__ == '__main__':
Tao Bao1c830bf2017-12-25 10:43:47 -0800843 try:
844 main(sys.argv[1:])
845 finally:
846 common.Cleanup()