blob: ed601883bc2d6f728d55c2f74a2535b8470d8be0 [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 Baoc7a6f1e2015-06-23 11:16:05 -0700328 (_, exit_code) = RunCommand(inflate_command)
Geremy Condrafd6f7512013-06-16 17:26:08 -0700329 if exit_code != 0:
330 os.remove(unsparse_image_path)
331 return False, None
332 return True, unsparse_image_path
333
Tao Baoc72727a2017-12-07 10:33:00 -0800334
Sami Tolvanenf99b5312015-05-20 07:30:57 +0100335def MakeVerityEnabledImage(out_file, fec_supported, prop_dict):
Geremy Condrafd6f7512013-06-16 17:26:08 -0700336 """Creates an image that is verifiable using dm-verity.
337
338 Args:
339 out_file: the location to write the verifiable image at
Dan Albert8b72aef2015-03-23 19:13:21 -0700340 prop_dict: a dictionary of properties required for image creation and
341 verification
Geremy Condrafd6f7512013-06-16 17:26:08 -0700342 Returns:
343 True on success, False otherwise.
344 """
345 # get properties
Sami Tolvanen433905f2016-09-01 15:58:35 -0700346 image_size = int(prop_dict["partition_size"])
Geremy Condrafd6f7512013-06-16 17:26:08 -0700347 block_dev = prop_dict["verity_block_device"]
Paul Lawrencea37b2bb2014-11-13 17:54:30 -0800348 signer_key = prop_dict["verity_key"] + ".pk8"
Baligh Uddin601ddea2015-06-09 15:48:14 -0700349 if OPTIONS.verity_signer_path is not None:
Tao Bao45810422016-10-17 16:20:12 -0700350 signer_path = OPTIONS.verity_signer_path
Baligh Uddin601ddea2015-06-09 15:48:14 -0700351 else:
352 signer_path = prop_dict["verity_signer_cmd"]
Tao Bao45810422016-10-17 16:20:12 -0700353 signer_args = OPTIONS.verity_signer_args
Geremy Condrafd6f7512013-06-16 17:26:08 -0700354
355 # make a tempdir
Tao Bao1c830bf2017-12-25 10:43:47 -0800356 tempdir_name = common.MakeTempDir(suffix="_verity_images")
Geremy Condrafd6f7512013-06-16 17:26:08 -0700357
358 # get partial image paths
359 verity_image_path = os.path.join(tempdir_name, "verity.img")
360 verity_metadata_path = os.path.join(tempdir_name, "verity_metadata.img")
Sami Tolvanenf99b5312015-05-20 07:30:57 +0100361 verity_fec_path = os.path.join(tempdir_name, "verity_fec.img")
Geremy Condrafd6f7512013-06-16 17:26:08 -0700362
363 # build the verity tree and get the root hash and salt
Colin Cross477cf2b2014-04-16 18:49:56 -0700364 if not BuildVerityTree(out_file, verity_image_path, prop_dict):
Geremy Condrafd6f7512013-06-16 17:26:08 -0700365 return False
366
367 # build the metadata blocks
368 root_hash = prop_dict["verity_root_hash"]
369 salt = prop_dict["verity_salt"]
Bowgo Tsai6ceeb1a2017-10-11 16:21:48 +0800370 verity_disable = "verity_disable" in prop_dict
Dan Albert8b72aef2015-03-23 19:13:21 -0700371 if not BuildVerityMetadata(image_size, verity_metadata_path, root_hash, salt,
Bowgo Tsai6ceeb1a2017-10-11 16:21:48 +0800372 block_dev, signer_path, signer_key, signer_args,
373 verity_disable):
Geremy Condrafd6f7512013-06-16 17:26:08 -0700374 return False
375
376 # build the full verified image
Sami Tolvanen433905f2016-09-01 15:58:35 -0700377 target_size = int(prop_dict["original_partition_size"])
378 verity_size = int(prop_dict["verity_size"])
379
380 padding_size = target_size - image_size - verity_size
381 assert padding_size >= 0
382
Geremy Condrafd6f7512013-06-16 17:26:08 -0700383 if not BuildVerifiedImage(out_file,
384 verity_image_path,
Sami Tolvanen4a060042015-12-18 15:50:25 +0000385 verity_metadata_path,
386 verity_fec_path,
Sami Tolvanen433905f2016-09-01 15:58:35 -0700387 padding_size,
Sami Tolvanen4a060042015-12-18 15:50:25 +0000388 fec_supported):
Geremy Condrafd6f7512013-06-16 17:26:08 -0700389 return False
390
Geremy Condrafd6f7512013-06-16 17:26:08 -0700391 return True
392
Tao Baoc72727a2017-12-07 10:33:00 -0800393
Mohamad Ayyashf8765552016-03-02 21:07:23 -0800394def ConvertBlockMapToBaseFs(block_map_file):
Tao Bao1c830bf2017-12-25 10:43:47 -0800395 base_fs_file = common.MakeTempFile(prefix="script_gen_", suffix=".base_fs")
Mohamad Ayyashf8765552016-03-02 21:07:23 -0800396 convert_command = ["blk_alloc_to_base_fs", block_map_file, base_fs_file]
397 (_, exit_code) = RunCommand(convert_command)
Tao Baoc72727a2017-12-07 10:33:00 -0800398 return base_fs_file if exit_code == 0 else None
Mohamad Ayyashf8765552016-03-02 21:07:23 -0800399
Tao Baod4349f22017-12-07 23:01:25 -0800400
401def CheckHeadroom(ext4fs_output, prop_dict):
402 """Checks if there's enough headroom space available.
403
404 Headroom is the reserved space on system image (via PRODUCT_SYSTEM_HEADROOM),
405 which is useful for devices with low disk space that have system image
406 variation between builds. The 'partition_headroom' in prop_dict is the size
407 in bytes, while the numbers in 'ext4fs_output' are for 4K-blocks.
408
409 Args:
410 ext4fs_output: The output string from mke2fs command.
411 prop_dict: The property dict.
412
413 Returns:
414 The check result.
Tao Baod8a953d2018-01-02 21:19:27 -0800415
416 Raises:
417 AssertionError: On invalid input.
Tao Baod4349f22017-12-07 23:01:25 -0800418 """
Tao Baod8a953d2018-01-02 21:19:27 -0800419 assert ext4fs_output is not None
420 assert prop_dict.get('fs_type', '').startswith('ext4')
421 assert 'partition_headroom' in prop_dict
422 assert 'mount_point' in prop_dict
423
Tao Baod4349f22017-12-07 23:01:25 -0800424 ext4fs_stats = re.compile(
425 r'Created filesystem with .* (?P<used_blocks>[0-9]+)/'
426 r'(?P<total_blocks>[0-9]+) blocks')
Tao Baoc72727a2017-12-07 10:33:00 -0800427 last_line = ext4fs_output.strip().split('\n')[-1]
428 m = ext4fs_stats.match(last_line)
Tao Baod4349f22017-12-07 23:01:25 -0800429 used_blocks = int(m.groupdict().get('used_blocks'))
430 total_blocks = int(m.groupdict().get('total_blocks'))
Tao Baod8a953d2018-01-02 21:19:27 -0800431 headroom_blocks = int(prop_dict['partition_headroom']) / BLOCK_SIZE
Tao Baod4349f22017-12-07 23:01:25 -0800432 adjusted_blocks = total_blocks - headroom_blocks
433 if used_blocks > adjusted_blocks:
Tao Baod8a953d2018-01-02 21:19:27 -0800434 mount_point = prop_dict["mount_point"]
Tao Baod4349f22017-12-07 23:01:25 -0800435 print("Error: Not enough room on %s (total: %d blocks, used: %d blocks, "
436 "headroom: %d blocks, available: %d blocks)" % (
437 mount_point, total_blocks, used_blocks, headroom_blocks,
438 adjusted_blocks))
439 return False
440 return True
441
442
Thierry Strudel74a81e62015-07-09 09:54:55 -0700443def BuildImage(in_dir, prop_dict, out_file, target_out=None):
Ying Wangbd93d422011-10-28 17:02:30 -0700444 """Build an image to out_file from in_dir with property prop_dict.
445
446 Args:
447 in_dir: path of input directory.
448 prop_dict: property dictionary.
449 out_file: path of the output image file.
Tao Baoc72727a2017-12-07 10:33:00 -0800450 target_out: path of the product out directory to read device specific FS
451 config files.
Ying Wangbd93d422011-10-28 17:02:30 -0700452
453 Returns:
454 True iff the image is built successfully.
455 """
Tao Baof3282b42015-04-01 11:21:55 -0700456 # system_root_image=true: build a system.img that combines the contents of
457 # /system and the ramdisk, and can be mounted at the root of the file system.
Ying Wanga2292c92015-03-24 19:07:40 -0700458 origin_in = in_dir
459 fs_config = prop_dict.get("fs_config")
Tao Baoc72727a2017-12-07 10:33:00 -0800460 if (prop_dict.get("system_root_image") == "true" and
461 prop_dict["mount_point"] == "system"):
Tao Bao1c830bf2017-12-25 10:43:47 -0800462 in_dir = common.MakeTempDir()
Tao Baoc72727a2017-12-07 10:33:00 -0800463 # Change the mount point to "/".
Ying Wanga2292c92015-03-24 19:07:40 -0700464 prop_dict["mount_point"] = "/"
465 if fs_config:
466 # We need to merge the fs_config files of system and ramdisk.
Tao Bao1c830bf2017-12-25 10:43:47 -0800467 merged_fs_config = common.MakeTempFile(prefix="root_fs_config",
468 suffix=".txt")
Ying Wanga2292c92015-03-24 19:07:40 -0700469 with open(merged_fs_config, "w") as fw:
470 if "ramdisk_fs_config" in prop_dict:
471 with open(prop_dict["ramdisk_fs_config"]) as fr:
472 fw.writelines(fr.readlines())
473 with open(fs_config) as fr:
474 fw.writelines(fr.readlines())
475 fs_config = merged_fs_config
476
Ying Wangbd93d422011-10-28 17:02:30 -0700477 build_command = []
478 fs_type = prop_dict.get("fs_type", "")
Tao Baoc72727a2017-12-07 10:33:00 -0800479 run_e2fsck = False
Geremy Condrafd6f7512013-06-16 17:26:08 -0700480
Mohamad Ayyashdd063522015-03-24 12:42:03 -0700481 fs_spans_partition = True
482 if fs_type.startswith("squash"):
Tao Baoc7a6f1e2015-06-23 11:16:05 -0700483 fs_spans_partition = False
Mohamad Ayyashdd063522015-03-24 12:42:03 -0700484
Daniel Rosenbergf4eabc32014-07-10 15:42:38 -0700485 is_verity_partition = "verity_block_device" in prop_dict
Geremy Condra5b5f4952014-05-05 22:19:37 -0700486 verity_supported = prop_dict.get("verity") == "true"
Sami Tolvanenf99b5312015-05-20 07:30:57 +0100487 verity_fec_supported = prop_dict.get("verity_fec") == "true"
488
Tao Baoc7a6f1e2015-06-23 11:16:05 -0700489 # Adjust the partition size to make room for the hashes if this is to be
490 # verified.
Sami Tolvanen405e71d2016-02-09 12:28:58 -0800491 if verity_supported and is_verity_partition:
Geremy Condrafd6f7512013-06-16 17:26:08 -0700492 partition_size = int(prop_dict.get("partition_size"))
Tao Baoc72727a2017-12-07 10:33:00 -0800493 (adjusted_size, verity_size) = AdjustPartitionSizeForVerity(
494 partition_size, verity_fec_supported)
Geremy Condrafd6f7512013-06-16 17:26:08 -0700495 if not adjusted_size:
496 return False
497 prop_dict["partition_size"] = str(adjusted_size)
498 prop_dict["original_partition_size"] = str(partition_size)
Sami Tolvanen433905f2016-09-01 15:58:35 -0700499 prop_dict["verity_size"] = str(verity_size)
Geremy Condrafd6f7512013-06-16 17:26:08 -0700500
Bowgo Tsai7ea994b2017-05-19 23:44:26 +0800501 # Adjust partition size for AVB hash footer or AVB hashtree footer.
502 avb_footer_type = ''
503 if prop_dict.get("avb_hash_enable") == "true":
504 avb_footer_type = 'hash'
505 elif prop_dict.get("avb_hashtree_enable") == "true":
506 avb_footer_type = 'hashtree'
507
508 if avb_footer_type:
Bowgo Tsai3e599ea2017-05-26 18:30:04 +0800509 avbtool = prop_dict["avb_avbtool"]
510 partition_size = prop_dict["partition_size"]
Bowgo Tsai7ea994b2017-05-19 23:44:26 +0800511 # avb_add_hash_footer_args or avb_add_hashtree_footer_args.
512 additional_args = prop_dict["avb_add_" + avb_footer_type + "_footer_args"]
Tao Baoc72727a2017-12-07 10:33:00 -0800513 max_image_size = AVBCalcMaxImageSize(avbtool, avb_footer_type,
514 partition_size, additional_args)
David Zeuthen4014a9d2016-09-30 17:29:22 -0400515 if max_image_size == 0:
516 return False
517 prop_dict["partition_size"] = str(max_image_size)
Bowgo Tsai3e599ea2017-05-26 18:30:04 +0800518 prop_dict["original_partition_size"] = partition_size
David Zeuthen4014a9d2016-09-30 17:29:22 -0400519
Ying Wangbd93d422011-10-28 17:02:30 -0700520 if fs_type.startswith("ext"):
Adrien Schildknecht9a072cc2016-11-18 17:06:29 -0800521 build_command = [prop_dict["ext_mkuserimg"]]
Ying Wangbd93d422011-10-28 17:02:30 -0700522 if "extfs_sparse_flag" in prop_dict:
523 build_command.append(prop_dict["extfs_sparse_flag"])
Tao Baoc72727a2017-12-07 10:33:00 -0800524 run_e2fsck = True
Ying Wangbd93d422011-10-28 17:02:30 -0700525 build_command.extend([in_dir, out_file, fs_type,
526 prop_dict["mount_point"]])
Doug Zongker850b8072013-12-05 15:54:55 -0800527 build_command.append(prop_dict["partition_size"])
Ying Wangf3b86352014-11-18 18:03:13 -0800528 if "journal_size" in prop_dict:
529 build_command.extend(["-j", prop_dict["journal_size"]])
Doug Zongker850b8072013-12-05 15:54:55 -0800530 if "timestamp" in prop_dict:
531 build_command.extend(["-T", str(prop_dict["timestamp"])])
Ying Wanga2292c92015-03-24 19:07:40 -0700532 if fs_config:
Doug Zongker82822822014-06-16 09:10:55 -0700533 build_command.extend(["-C", fs_config])
Thierry Strudel74a81e62015-07-09 09:54:55 -0700534 if target_out:
535 build_command.extend(["-D", target_out])
Ying Wanga2292c92015-03-24 19:07:40 -0700536 if "block_list" in prop_dict:
537 build_command.extend(["-B", prop_dict["block_list"]])
Mohamad Ayyashf8765552016-03-02 21:07:23 -0800538 if "base_fs_file" in prop_dict:
539 base_fs_file = ConvertBlockMapToBaseFs(prop_dict["base_fs_file"])
540 if base_fs_file is None:
541 return False
542 build_command.extend(["-d", base_fs_file])
Christoffer Dall8ed01f32014-12-17 21:34:12 +0100543 build_command.extend(["-L", prop_dict["mount_point"]])
Patrick Tjina1900842016-10-20 10:58:12 -0700544 if "extfs_inode_count" in prop_dict:
545 build_command.extend(["-i", prop_dict["extfs_inode_count"]])
Connor O'Brien20f08c32017-01-05 16:48:14 -0800546 if "flash_erase_block_size" in prop_dict:
547 build_command.extend(["-e", prop_dict["flash_erase_block_size"]])
548 if "flash_logical_block_size" in prop_dict:
549 build_command.extend(["-o", prop_dict["flash_logical_block_size"]])
Tao Baod86e3112017-09-22 15:45:33 -0700550 # Specify UUID and hash_seed if using mke2fs.
551 if prop_dict["ext_mkuserimg"] == "mkuserimg_mke2fs.sh":
552 if "uuid" in prop_dict:
553 build_command.extend(["-U", prop_dict["uuid"]])
554 if "hash_seed" in prop_dict:
555 build_command.extend(["-S", prop_dict["hash_seed"]])
Ying Wanga2292c92015-03-24 19:07:40 -0700556 if "selinux_fc" in prop_dict:
Kenny Rootf32dc712012-04-08 10:42:34 -0700557 build_command.append(prop_dict["selinux_fc"])
Mohamad Ayyashb97746e2015-03-03 12:30:37 -0800558 elif fs_type.startswith("squash"):
559 build_command = ["mksquashfsimage.sh"]
560 build_command.extend([in_dir, out_file])
Todd Poynorb2a555e2015-12-15 18:00:14 -0800561 if "squashfs_sparse_flag" in prop_dict:
562 build_command.extend([prop_dict["squashfs_sparse_flag"]])
Mohamad Ayyashb97746e2015-03-03 12:30:37 -0800563 build_command.extend(["-m", prop_dict["mount_point"]])
Thierry Strudel74a81e62015-07-09 09:54:55 -0700564 if target_out:
565 build_command.extend(["-d", target_out])
Mohamad Ayyash88378822016-04-07 22:10:51 -0700566 if fs_config:
567 build_command.extend(["-C", fs_config])
Ying Wanga2292c92015-03-24 19:07:40 -0700568 if "selinux_fc" in prop_dict:
Mohamad Ayyashb97746e2015-03-03 12:30:37 -0800569 build_command.extend(["-c", prop_dict["selinux_fc"]])
Mohamad Ayyashc3484f72016-06-13 09:46:58 -0700570 if "block_list" in prop_dict:
571 build_command.extend(["-B", prop_dict["block_list"]])
Simon Wilsonf86e7ee2015-06-17 12:35:15 -0700572 if "squashfs_compressor" in prop_dict:
573 build_command.extend(["-z", prop_dict["squashfs_compressor"]])
574 if "squashfs_compressor_opt" in prop_dict:
575 build_command.extend(["-zo", prop_dict["squashfs_compressor_opt"]])
Mohamad Ayyashdfec8152016-05-24 12:59:30 -0700576 if "squashfs_block_size" in prop_dict:
577 build_command.extend(["-b", prop_dict["squashfs_block_size"]])
Tao Baoc72727a2017-12-07 10:33:00 -0800578 if prop_dict.get("squashfs_disable_4k_align") == "true":
Mohamad Ayyash1b6d3482016-06-15 15:53:07 -0700579 build_command.extend(["-a"])
JP Abgrall5bfed5a2014-06-16 14:17:40 -0700580 elif fs_type.startswith("f2fs"):
581 build_command = ["mkf2fsuserimg.sh"]
582 build_command.extend([out_file, prop_dict["partition_size"]])
Jaegeuk Kim2ea1eba2017-11-28 19:21:28 -0800583 if fs_config:
584 build_command.extend(["-C", fs_config])
585 build_command.extend(["-f", in_dir])
586 if target_out:
587 build_command.extend(["-D", target_out])
588 if "selinux_fc" in prop_dict:
589 build_command.extend(["-s", prop_dict["selinux_fc"]])
590 build_command.extend(["-t", prop_dict["mount_point"]])
591 if "timestamp" in prop_dict:
592 build_command.extend(["-T", str(prop_dict["timestamp"])])
593 build_command.extend(["-L", prop_dict["mount_point"]])
Ying Wangbd93d422011-10-28 17:02:30 -0700594 else:
Elliott Hughes305b0882016-06-15 17:04:54 -0700595 print("Error: unknown filesystem type '%s'" % (fs_type))
596 return False
Ying Wangbd93d422011-10-28 17:02:30 -0700597
Ying Wanga2292c92015-03-24 19:07:40 -0700598 if in_dir != origin_in:
599 # Construct a staging directory of the root file system.
600 ramdisk_dir = prop_dict.get("ramdisk_dir")
601 if ramdisk_dir:
602 shutil.rmtree(in_dir)
603 shutil.copytree(ramdisk_dir, in_dir, symlinks=True)
604 staging_system = os.path.join(in_dir, "system")
605 shutil.rmtree(staging_system, ignore_errors=True)
606 shutil.copytree(origin_in, staging_system, symlinks=True)
Tao Baoc7a6f1e2015-06-23 11:16:05 -0700607
Tao Baoc72727a2017-12-07 10:33:00 -0800608 (mkfs_output, exit_code) = RunCommand(build_command)
Ying Wang69e9b4d2012-11-26 18:10:23 -0800609 if exit_code != 0:
Elliott Hughes73ff57f2017-12-06 12:16:39 -0800610 print("Error: '%s' failed with exit code %d" % (build_command, exit_code))
Ying Wang69e9b4d2012-11-26 18:10:23 -0800611 return False
612
Tao Baod4349f22017-12-07 23:01:25 -0800613 # Check if there's enough headroom space available for ext4 image.
Tao Bao79d52f82017-12-07 14:07:44 -0800614 if "partition_headroom" in prop_dict and fs_type.startswith("ext4"):
Tao Baoc72727a2017-12-07 10:33:00 -0800615 if not CheckHeadroom(mkfs_output, prop_dict):
Tao Baoc7a6f1e2015-06-23 11:16:05 -0700616 return False
617
Mohamad Ayyashdd063522015-03-24 12:42:03 -0700618 if not fs_spans_partition:
619 mount_point = prop_dict.get("mount_point")
620 partition_size = int(prop_dict.get("partition_size"))
Sami Tolvanen405e71d2016-02-09 12:28:58 -0800621 image_size = GetSimgSize(out_file)
Mohamad Ayyashdd063522015-03-24 12:42:03 -0700622 if image_size > partition_size:
Tao Baoc7a6f1e2015-06-23 11:16:05 -0700623 print("Error: %s image size of %d is larger than partition size of "
624 "%d" % (mount_point, image_size, partition_size))
625 return False
Mohamad Ayyashdd063522015-03-24 12:42:03 -0700626 if verity_supported and is_verity_partition:
Sami Tolvanen405e71d2016-02-09 12:28:58 -0800627 ZeroPadSimg(out_file, partition_size - image_size)
Mohamad Ayyashdd063522015-03-24 12:42:03 -0700628
Tao Baoc72727a2017-12-07 10:33:00 -0800629 # Create the verified image if this is to be verified.
Geremy Condra5b5f4952014-05-05 22:19:37 -0700630 if verity_supported and is_verity_partition:
Sami Tolvanenf99b5312015-05-20 07:30:57 +0100631 if not MakeVerityEnabledImage(out_file, verity_fec_supported, prop_dict):
Geremy Condrafd6f7512013-06-16 17:26:08 -0700632 return False
633
Bowgo Tsai7ea994b2017-05-19 23:44:26 +0800634 # Add AVB HASH or HASHTREE footer (metadata).
635 if avb_footer_type:
Bowgo Tsai3e599ea2017-05-26 18:30:04 +0800636 avbtool = prop_dict["avb_avbtool"]
637 original_partition_size = prop_dict["original_partition_size"]
David Zeuthen4014a9d2016-09-30 17:29:22 -0400638 partition_name = prop_dict["partition_name"]
Bowgo Tsai3e599ea2017-05-26 18:30:04 +0800639 # key_path and algorithm are only available when chain partition is used.
640 key_path = prop_dict.get("avb_key_path")
641 algorithm = prop_dict.get("avb_algorithm")
Tao Bao2b6dfd62017-09-27 17:17:43 -0700642 salt = prop_dict.get("avb_salt")
Bowgo Tsai7ea994b2017-05-19 23:44:26 +0800643 # avb_add_hash_footer_args or avb_add_hashtree_footer_args
644 additional_args = prop_dict["avb_add_" + avb_footer_type + "_footer_args"]
Tao Baoc72727a2017-12-07 10:33:00 -0800645 if not AVBAddFooter(out_file, avbtool, avb_footer_type,
646 original_partition_size, partition_name, key_path,
647 algorithm, salt, additional_args):
David Zeuthen4014a9d2016-09-30 17:29:22 -0400648 return False
649
Tao Baoc72727a2017-12-07 10:33:00 -0800650 if run_e2fsck and prop_dict.get("skip_fsck") != "true":
Geremy Condra6e8f53c2013-12-05 17:09:18 -0800651 success, unsparse_image = UnsparseImage(out_file, replace=False)
Geremy Condrafd6f7512013-06-16 17:26:08 -0700652 if not success:
Ying Wang69e9b4d2012-11-26 18:10:23 -0800653 return False
654
655 # Run e2fsck on the inflated image file
656 e2fsck_command = ["e2fsck", "-f", "-n", unsparse_image]
Tao Baoc7a6f1e2015-06-23 11:16:05 -0700657 (_, exit_code) = RunCommand(e2fsck_command)
Ying Wang69e9b4d2012-11-26 18:10:23 -0800658
659 os.remove(unsparse_image)
660
Elliott Hughes73ff57f2017-12-06 12:16:39 -0800661 if exit_code != 0:
Tao Baoc72727a2017-12-07 10:33:00 -0800662 print("Error: '%s' failed with exit code %d" % (e2fsck_command,
663 exit_code))
Elliott Hughes73ff57f2017-12-06 12:16:39 -0800664 return False
665
666 return True
Ying Wangbd93d422011-10-28 17:02:30 -0700667
668
669def ImagePropFromGlobalDict(glob_dict, mount_point):
670 """Build an image property dictionary from the global dictionary.
671
672 Args:
673 glob_dict: the global dictionary from the build system.
674 mount_point: such as "system", "data" etc.
675 """
Doug Zongker1ad7ade2013-12-06 11:53:27 -0800676 d = {}
Tao Bao052ae352015-09-28 13:44:13 -0700677
Tao Bao822f5842015-09-30 16:01:14 -0700678 if "build.prop" in glob_dict:
679 bp = glob_dict["build.prop"]
680 if "ro.build.date.utc" in bp:
681 d["timestamp"] = bp["ro.build.date.utc"]
Ying Wang9f8e8db2011-11-04 11:37:01 -0700682
683 def copy_prop(src_p, dest_p):
684 if src_p in glob_dict:
685 d[dest_p] = str(glob_dict[src_p])
686
Ying Wangbd93d422011-10-28 17:02:30 -0700687 common_props = (
Ying Wangbd93d422011-10-28 17:02:30 -0700688 "extfs_sparse_flag",
Todd Poynorb2a555e2015-12-15 18:00:14 -0800689 "squashfs_sparse_flag",
Kenny Rootf32dc712012-04-08 10:42:34 -0700690 "selinux_fc",
Ying Wang6a42a252013-02-27 13:54:02 -0800691 "skip_fsck",
Adrien Schildknecht9a072cc2016-11-18 17:06:29 -0800692 "ext_mkuserimg",
Geremy Condrafd6f7512013-06-16 17:26:08 -0700693 "verity",
Geremy Condrafd6f7512013-06-16 17:26:08 -0700694 "verity_key",
Sami Tolvanenf99b5312015-05-20 07:30:57 +0100695 "verity_signer_cmd",
David Zeuthen4014a9d2016-09-30 17:29:22 -0400696 "verity_fec",
Bowgo Tsai6ceeb1a2017-10-11 16:21:48 +0800697 "verity_disable",
Bowgo Tsai3e599ea2017-05-26 18:30:04 +0800698 "avb_enable",
Tao Bao2b6dfd62017-09-27 17:17:43 -0700699 "avb_avbtool",
700 "avb_salt",
701 )
Ying Wangbd93d422011-10-28 17:02:30 -0700702 for p in common_props:
Ying Wang9f8e8db2011-11-04 11:37:01 -0700703 copy_prop(p, p)
Ying Wangbd93d422011-10-28 17:02:30 -0700704
705 d["mount_point"] = mount_point
706 if mount_point == "system":
Bowgo Tsai3e599ea2017-05-26 18:30:04 +0800707 copy_prop("avb_system_hashtree_enable", "avb_hashtree_enable")
708 copy_prop("avb_system_add_hashtree_footer_args",
709 "avb_add_hashtree_footer_args")
710 copy_prop("avb_system_key_path", "avb_key_path")
711 copy_prop("avb_system_algorithm", "avb_algorithm")
Ying Wang9f8e8db2011-11-04 11:37:01 -0700712 copy_prop("fs_type", "fs_type")
Julius D'souza001c6762017-05-03 13:43:27 -0700713 # Copy the generic system fs type first, override with specific one if
Dan Albert8b72aef2015-03-23 19:13:21 -0700714 # available.
Mohamad Ayyashb97746e2015-03-03 12:30:37 -0800715 copy_prop("system_fs_type", "fs_type")
Julius D'souza001c6762017-05-03 13:43:27 -0700716 copy_prop("system_headroom", "partition_headroom")
Ying Wang9f8e8db2011-11-04 11:37:01 -0700717 copy_prop("system_size", "partition_size")
Ying Wangf3b86352014-11-18 18:03:13 -0800718 copy_prop("system_journal_size", "journal_size")
Daniel Rosenbergf4eabc32014-07-10 15:42:38 -0700719 copy_prop("system_verity_block_device", "verity_block_device")
Tao Baof3282b42015-04-01 11:21:55 -0700720 copy_prop("system_root_image", "system_root_image")
721 copy_prop("ramdisk_dir", "ramdisk_dir")
Tao Bao84e75682015-07-19 02:38:53 -0700722 copy_prop("ramdisk_fs_config", "ramdisk_fs_config")
Simon Wilsonf86e7ee2015-06-17 12:35:15 -0700723 copy_prop("system_squashfs_compressor", "squashfs_compressor")
724 copy_prop("system_squashfs_compressor_opt", "squashfs_compressor_opt")
Mohamad Ayyashdfec8152016-05-24 12:59:30 -0700725 copy_prop("system_squashfs_block_size", "squashfs_block_size")
Mohamad Ayyash1b6d3482016-06-15 15:53:07 -0700726 copy_prop("system_squashfs_disable_4k_align", "squashfs_disable_4k_align")
Mohamad Ayyashf8765552016-03-02 21:07:23 -0800727 copy_prop("system_base_fs_file", "base_fs_file")
Patrick Tjina1900842016-10-20 10:58:12 -0700728 copy_prop("system_extfs_inode_count", "extfs_inode_count")
Alex Light4e358ab2016-06-16 14:47:10 -0700729 elif mount_point == "system_other":
Tao Baoc72727a2017-12-07 10:33:00 -0800730 # We inherit the selinux policies of /system since we contain some of its
731 # files.
Alex Light4e358ab2016-06-16 14:47:10 -0700732 d["mount_point"] = "system"
Bowgo Tsai3e599ea2017-05-26 18:30:04 +0800733 copy_prop("avb_system_hashtree_enable", "avb_hashtree_enable")
734 copy_prop("avb_system_add_hashtree_footer_args",
735 "avb_add_hashtree_footer_args")
736 copy_prop("avb_system_key_path", "avb_key_path")
737 copy_prop("avb_system_algorithm", "avb_algorithm")
Alex Light4e358ab2016-06-16 14:47:10 -0700738 copy_prop("fs_type", "fs_type")
739 copy_prop("system_fs_type", "fs_type")
740 copy_prop("system_size", "partition_size")
741 copy_prop("system_journal_size", "journal_size")
742 copy_prop("system_verity_block_device", "verity_block_device")
Alex Light4e358ab2016-06-16 14:47:10 -0700743 copy_prop("system_squashfs_compressor", "squashfs_compressor")
744 copy_prop("system_squashfs_compressor_opt", "squashfs_compressor_opt")
745 copy_prop("system_squashfs_block_size", "squashfs_block_size")
746 copy_prop("system_base_fs_file", "base_fs_file")
Patrick Tjina1900842016-10-20 10:58:12 -0700747 copy_prop("system_extfs_inode_count", "extfs_inode_count")
Ying Wangbd93d422011-10-28 17:02:30 -0700748 elif mount_point == "data":
JP Abgrall5bfed5a2014-06-16 14:17:40 -0700749 # Copy the generic fs type first, override with specific one if available.
Ying Wang9f8e8db2011-11-04 11:37:01 -0700750 copy_prop("fs_type", "fs_type")
JP Abgrall5bfed5a2014-06-16 14:17:40 -0700751 copy_prop("userdata_fs_type", "fs_type")
Ying Wang9f8e8db2011-11-04 11:37:01 -0700752 copy_prop("userdata_size", "partition_size")
Tao Baoc72727a2017-12-07 10:33:00 -0800753 copy_prop("flash_logical_block_size", "flash_logical_block_size")
Connor O'Brien20f08c32017-01-05 16:48:14 -0800754 copy_prop("flash_erase_block_size", "flash_erase_block_size")
Ying Wang9f8e8db2011-11-04 11:37:01 -0700755 elif mount_point == "cache":
756 copy_prop("cache_fs_type", "fs_type")
757 copy_prop("cache_size", "partition_size")
Ying Wanga0febe52013-03-20 11:02:05 -0700758 elif mount_point == "vendor":
Bowgo Tsai3e599ea2017-05-26 18:30:04 +0800759 copy_prop("avb_vendor_hashtree_enable", "avb_hashtree_enable")
760 copy_prop("avb_vendor_add_hashtree_footer_args",
761 "avb_add_hashtree_footer_args")
762 copy_prop("avb_vendor_key_path", "avb_key_path")
763 copy_prop("avb_vendor_algorithm", "avb_algorithm")
Ying Wanga0febe52013-03-20 11:02:05 -0700764 copy_prop("vendor_fs_type", "fs_type")
765 copy_prop("vendor_size", "partition_size")
Ying Wangf3b86352014-11-18 18:03:13 -0800766 copy_prop("vendor_journal_size", "journal_size")
Daniel Rosenbergf4eabc32014-07-10 15:42:38 -0700767 copy_prop("vendor_verity_block_device", "verity_block_device")
Patrick Tjine11aa502016-02-09 15:40:38 -0800768 copy_prop("vendor_squashfs_compressor", "squashfs_compressor")
769 copy_prop("vendor_squashfs_compressor_opt", "squashfs_compressor_opt")
Mohamad Ayyashdfec8152016-05-24 12:59:30 -0700770 copy_prop("vendor_squashfs_block_size", "squashfs_block_size")
Mohamad Ayyash1b6d3482016-06-15 15:53:07 -0700771 copy_prop("vendor_squashfs_disable_4k_align", "squashfs_disable_4k_align")
Mohamad Ayyashf8765552016-03-02 21:07:23 -0800772 copy_prop("vendor_base_fs_file", "base_fs_file")
Patrick Tjina1900842016-10-20 10:58:12 -0700773 copy_prop("vendor_extfs_inode_count", "extfs_inode_count")
Ying Wangb8888432014-03-11 17:13:27 -0700774 elif mount_point == "oem":
775 copy_prop("fs_type", "fs_type")
776 copy_prop("oem_size", "partition_size")
Ying Wangf3b86352014-11-18 18:03:13 -0800777 copy_prop("oem_journal_size", "journal_size")
Patrick Tjina1900842016-10-20 10:58:12 -0700778 copy_prop("oem_extfs_inode_count", "extfs_inode_count")
David Zeuthen4014a9d2016-09-30 17:29:22 -0400779 d["partition_name"] = mount_point
Ying Wangbd93d422011-10-28 17:02:30 -0700780 return d
781
782
783def LoadGlobalDict(filename):
784 """Load "name=value" pairs from filename"""
785 d = {}
786 f = open(filename)
787 for line in f:
788 line = line.strip()
789 if not line or line.startswith("#"):
790 continue
791 k, v = line.split("=", 1)
792 d[k] = v
793 f.close()
794 return d
795
796
797def main(argv):
Thierry Strudel74a81e62015-07-09 09:54:55 -0700798 if len(argv) != 4:
Tao Baoc72727a2017-12-07 10:33:00 -0800799 print(__doc__)
Ying Wangbd93d422011-10-28 17:02:30 -0700800 sys.exit(1)
801
802 in_dir = argv[0]
803 glob_dict_file = argv[1]
804 out_file = argv[2]
Thierry Strudel74a81e62015-07-09 09:54:55 -0700805 target_out = argv[3]
Ying Wangbd93d422011-10-28 17:02:30 -0700806
807 glob_dict = LoadGlobalDict(glob_dict_file)
Ying Wangae61f502015-03-12 18:30:39 -0700808 if "mount_point" in glob_dict:
Tao Baoc7a6f1e2015-06-23 11:16:05 -0700809 # The caller knows the mount point and provides a dictionay needed by
810 # BuildImage().
Ying Wangae61f502015-03-12 18:30:39 -0700811 image_properties = glob_dict
Ying Wang9f8e8db2011-11-04 11:37:01 -0700812 else:
Ying Wangae61f502015-03-12 18:30:39 -0700813 image_filename = os.path.basename(out_file)
814 mount_point = ""
815 if image_filename == "system.img":
816 mount_point = "system"
Alex Light4e358ab2016-06-16 14:47:10 -0700817 elif image_filename == "system_other.img":
818 mount_point = "system_other"
Ying Wangae61f502015-03-12 18:30:39 -0700819 elif image_filename == "userdata.img":
820 mount_point = "data"
821 elif image_filename == "cache.img":
822 mount_point = "cache"
823 elif image_filename == "vendor.img":
824 mount_point = "vendor"
825 elif image_filename == "oem.img":
826 mount_point = "oem"
827 else:
Tao Baoc72727a2017-12-07 10:33:00 -0800828 print("error: unknown image file name ", image_filename, file=sys.stderr)
Tao Bao1c830bf2017-12-25 10:43:47 -0800829 sys.exit(1)
Ying Wangbd93d422011-10-28 17:02:30 -0700830
Ying Wangae61f502015-03-12 18:30:39 -0700831 image_properties = ImagePropFromGlobalDict(glob_dict, mount_point)
832
Thierry Strudel74a81e62015-07-09 09:54:55 -0700833 if not BuildImage(in_dir, image_properties, out_file, target_out):
Tao Baoc72727a2017-12-07 10:33:00 -0800834 print("error: failed to build %s from %s" % (out_file, in_dir),
835 file=sys.stderr)
Tao Bao1c830bf2017-12-25 10:43:47 -0800836 sys.exit(1)
Ying Wangbd93d422011-10-28 17:02:30 -0700837
838
839if __name__ == '__main__':
Tao Bao1c830bf2017-12-25 10:43:47 -0800840 try:
841 main(sys.argv[1:])
842 finally:
843 common.Cleanup()