blob: e198f404e4ba06971d88fb211fe23272c9fdb97a [file] [log] [blame]
Ying Wangbd93d422011-10-28 17:02:30 -07001#!/usr/bin/env python
2#
3# Copyright (C) 2011 The Android Open Source Project
4#
5# Licensed under the Apache License, Version 2.0 (the "License");
6# you may not use this file except in compliance with the License.
7# You may obtain a copy of the License at
8#
9# http://www.apache.org/licenses/LICENSE-2.0
10#
11# Unless required by applicable law or agreed to in writing, software
12# distributed under the License is distributed on an "AS IS" BASIS,
13# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14# See the License for the specific language governing permissions and
15# limitations under the License.
16
17"""
Tao Baoc72727a2017-12-07 10:33:00 -080018Builds output_image from the given input_directory, properties_file,
19and writes the image to target_output_directory.
Ying Wangbd93d422011-10-28 17:02:30 -070020
Yifan Hongbbcba1e2018-06-18 16:32:35 -070021If argument generated_prop_file exists, write additional properties to the file.
22
Tao Baoc72727a2017-12-07 10:33:00 -080023Usage: build_image.py input_directory properties_file output_image \\
Yifan Hongbbcba1e2018-06-18 16:32:35 -070024 target_output_directory [generated_prop_file]
Ying Wangbd93d422011-10-28 17:02:30 -070025"""
Tao Baoc72727a2017-12-07 10:33:00 -080026
27from __future__ import print_function
28
Ying Wangbd93d422011-10-28 17:02:30 -070029import os
Ying Wang69e9b4d2012-11-26 18:10:23 -080030import os.path
Tao Baoc7a6f1e2015-06-23 11:16:05 -070031import re
David Zeuthen4014a9d2016-09-30 17:29:22 -040032import shlex
Geremy Condrafd6f7512013-06-16 17:26:08 -070033import shutil
Tao Baoc72727a2017-12-07 10:33:00 -080034import subprocess
35import sys
36
37import common
Sami Tolvanen405e71d2016-02-09 12:28:58 -080038import sparse_img
Tao Baoc72727a2017-12-07 10:33:00 -080039
Ying Wangbd93d422011-10-28 17:02:30 -070040
Baligh Uddin601ddea2015-06-09 15:48:14 -070041OPTIONS = common.OPTIONS
42
Geremy Condrae8e982a2014-05-16 19:14:30 -070043FIXED_SALT = "aee087a5be3b982978c923f566a94613496b417f2af592639bc80d141e34dfe7"
Sami Tolvanenf99b5312015-05-20 07:30:57 +010044BLOCK_SIZE = 4096
Yifan Hongbbcba1e2018-06-18 16:32:35 -070045BYTES_IN_MB = 1024 * 1024
Geremy Condrae8e982a2014-05-16 19:14:30 -070046
Tao Baoc72727a2017-12-07 10:33:00 -080047
Yifan Hongbbcba1e2018-06-18 16:32:35 -070048def RunCommand(cmd, verbose=None, env=None):
Tao Baoc7a6f1e2015-06-23 11:16:05 -070049 """Echo and run the given command.
Ying Wang69e9b4d2012-11-26 18:10:23 -080050
51 Args:
52 cmd: the command represented as a list of strings.
Tianjie Xu149b7fb2017-09-01 15:36:08 -070053 verbose: show commands being executed.
Yifan Hongbbcba1e2018-06-18 16:32:35 -070054 env: a dictionary of additional environment variables.
Ying Wang69e9b4d2012-11-26 18:10:23 -080055 Returns:
Tao Baoc7a6f1e2015-06-23 11:16:05 -070056 A tuple of the output and the exit code.
Ying Wang69e9b4d2012-11-26 18:10:23 -080057 """
Yifan Hongbbcba1e2018-06-18 16:32:35 -070058 env_copy = None
59 if env is not None:
60 env_copy = os.environ.copy()
61 env_copy.update(env)
Tianjie Xu149b7fb2017-09-01 15:36:08 -070062 if verbose is None:
63 verbose = OPTIONS.verbose
64 if verbose:
65 print("Running: " + " ".join(cmd))
Yifan Hongbbcba1e2018-06-18 16:32:35 -070066 p = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.STDOUT,
67 env=env_copy)
Tao Baoc7a6f1e2015-06-23 11:16:05 -070068 output, _ = p.communicate()
Tianjie Xu149b7fb2017-09-01 15:36:08 -070069
70 if verbose:
71 print(output.rstrip())
Tao Baoc7a6f1e2015-06-23 11:16:05 -070072 return (output, p.returncode)
Ying Wangbd93d422011-10-28 17:02:30 -070073
Tao Baoc72727a2017-12-07 10:33:00 -080074
Sami Tolvanenf99b5312015-05-20 07:30:57 +010075def GetVerityFECSize(partition_size):
Tianjie Xue3ad41b2017-03-08 11:05:56 -080076 cmd = ["fec", "-s", str(partition_size)]
Tianjie Xu149b7fb2017-09-01 15:36:08 -070077 output, exit_code = RunCommand(cmd, False)
Tianjie Xue3ad41b2017-03-08 11:05:56 -080078 if exit_code != 0:
Sami Tolvanenf99b5312015-05-20 07:30:57 +010079 return False, 0
80 return True, int(output)
81
Tao Baoc72727a2017-12-07 10:33:00 -080082
Geremy Condrafd6f7512013-06-16 17:26:08 -070083def GetVerityTreeSize(partition_size):
Tianjie Xue3ad41b2017-03-08 11:05:56 -080084 cmd = ["build_verity_tree", "-s", str(partition_size)]
Tianjie Xu149b7fb2017-09-01 15:36:08 -070085 output, exit_code = RunCommand(cmd, False)
Tianjie Xue3ad41b2017-03-08 11:05:56 -080086 if exit_code != 0:
Geremy Condrafd6f7512013-06-16 17:26:08 -070087 return False, 0
88 return True, int(output)
89
Tao Baoc72727a2017-12-07 10:33:00 -080090
Geremy Condrafd6f7512013-06-16 17:26:08 -070091def GetVerityMetadataSize(partition_size):
Tao Baob4ec6d72018-03-15 23:21:28 -070092 cmd = ["build_verity_metadata.py", "size", str(partition_size)]
Tianjie Xu149b7fb2017-09-01 15:36:08 -070093 output, exit_code = RunCommand(cmd, False)
Tianjie Xue3ad41b2017-03-08 11:05:56 -080094 if exit_code != 0:
Geremy Condrafd6f7512013-06-16 17:26:08 -070095 return False, 0
96 return True, int(output)
97
Tao Baoc72727a2017-12-07 10:33:00 -080098
Sami Tolvanenf99b5312015-05-20 07:30:57 +010099def GetVeritySize(partition_size, fec_supported):
100 success, verity_tree_size = GetVerityTreeSize(partition_size)
101 if not success:
102 return 0
103 success, verity_metadata_size = GetVerityMetadataSize(partition_size)
104 if not success:
105 return 0
106 verity_size = verity_tree_size + verity_metadata_size
107 if fec_supported:
108 success, fec_size = GetVerityFECSize(partition_size + verity_size)
109 if not success:
110 return 0
111 return verity_size + fec_size
112 return verity_size
113
Tao Baoc72727a2017-12-07 10:33:00 -0800114
Yifan Hongbbcba1e2018-06-18 16:32:35 -0700115def GetDiskUsage(path):
116 """Return number of bytes that "path" occupies on host.
117
118 Args:
119 path: The directory or file to calculate size on
120 Returns:
121 True and the number of bytes if successful,
122 False and 0 otherwise.
123 """
124 env = {"POSIXLY_CORRECT": "1"}
125 cmd = ["du", "-s", path]
126 output, exit_code = RunCommand(cmd, verbose=False, env=env)
127 if exit_code != 0:
128 return False, 0
129 # POSIX du returns number of blocks with block size 512
130 return True, int(output.split()[0]) * 512
131
132
Sami Tolvanen405e71d2016-02-09 12:28:58 -0800133def GetSimgSize(image_file):
134 simg = sparse_img.SparseImage(image_file, build_map=False)
135 return simg.blocksize * simg.total_blocks
136
Tao Baoc72727a2017-12-07 10:33:00 -0800137
Sami Tolvanen405e71d2016-02-09 12:28:58 -0800138def ZeroPadSimg(image_file, pad_size):
139 blocks = pad_size // BLOCK_SIZE
140 print("Padding %d blocks (%d bytes)" % (blocks, pad_size))
141 simg = sparse_img.SparseImage(image_file, mode="r+b", build_map=False)
142 simg.AppendFillChunk(0, blocks)
143
Tao Baoc72727a2017-12-07 10:33:00 -0800144
Bowgo Tsai7ea994b2017-05-19 23:44:26 +0800145def AVBCalcMaxImageSize(avbtool, footer_type, partition_size, additional_args):
David Zeuthen4014a9d2016-09-30 17:29:22 -0400146 """Calculates max image size for a given partition size.
147
148 Args:
149 avbtool: String with path to avbtool.
Bowgo Tsai7ea994b2017-05-19 23:44:26 +0800150 footer_type: 'hash' or 'hashtree' for generating footer.
David Zeuthen4014a9d2016-09-30 17:29:22 -0400151 partition_size: The size of the partition in question.
Bowgo Tsai040410c2018-09-20 16:40:01 +0800152 additional_args: Additional arguments to pass to "avbtool add_hash_footer"
153 or "avbtool add_hashtree_footer".
154
David Zeuthen4014a9d2016-09-30 17:29:22 -0400155 Returns:
156 The maximum image size or 0 if an error occurred.
157 """
Tao Baoc72727a2017-12-07 10:33:00 -0800158 cmd = [avbtool, "add_%s_footer" % footer_type,
Bowgo Tsai040410c2018-09-20 16:40:01 +0800159 "--partition_size", str(partition_size), "--calc_max_image_size"]
Bowgo Tsai3e599ea2017-05-26 18:30:04 +0800160 cmd.extend(shlex.split(additional_args))
161
162 (output, exit_code) = RunCommand(cmd)
David Zeuthen4014a9d2016-09-30 17:29:22 -0400163 if exit_code != 0:
164 return 0
165 else:
166 return int(output)
167
Tao Baoc72727a2017-12-07 10:33:00 -0800168
Bowgo Tsai040410c2018-09-20 16:40:01 +0800169def AVBCalcMinPartitionSize(image_size, size_calculator):
170 """Calculates min partition size for a given image size.
171
172 Args:
173 image_size: The size of the image in question.
174 size_calculator: The function to calculate max image size
175 for a given partition size.
176
177 Returns:
178 The minimum partition size required to accommodate the image size.
179 """
180 # Use image size as partition size to approximate final partition size.
181 image_ratio = size_calculator(image_size) / float(image_size)
182
183 # Prepare a binary search for the optimal partition size.
184 lo = int(image_size / image_ratio) // BLOCK_SIZE * BLOCK_SIZE - BLOCK_SIZE
185
186 # Ensure lo is small enough: max_image_size should <= image_size.
187 delta = BLOCK_SIZE
188 max_image_size = size_calculator(lo)
189 while max_image_size > image_size:
190 image_ratio = max_image_size / float(lo)
191 lo = int(image_size / image_ratio) // BLOCK_SIZE * BLOCK_SIZE - delta
192 delta *= 2
193 max_image_size = size_calculator(lo)
194
195 hi = lo + BLOCK_SIZE
196
197 # Ensure hi is large enough: max_image_size should >= image_size.
198 delta = BLOCK_SIZE
199 max_image_size = size_calculator(hi)
200 while max_image_size < image_size:
201 image_ratio = max_image_size / float(hi)
202 hi = int(image_size / image_ratio) // BLOCK_SIZE * BLOCK_SIZE + delta
203 delta *= 2
204 max_image_size = size_calculator(hi)
205
206 partition_size = hi
207
208 # Start to binary search.
209 while lo < hi:
210 mid = ((lo + hi) // (2 * BLOCK_SIZE)) * BLOCK_SIZE
211 max_image_size = size_calculator(mid)
212 if max_image_size >= image_size: # if mid can accommodate image_size
213 if mid < partition_size: # if a smaller partition size is found
214 partition_size = mid
215 hi = mid
216 else:
217 lo = mid + BLOCK_SIZE
218
219 if OPTIONS.verbose:
220 print("AVBCalcMinPartitionSize({}): partition_size: {}.".format(
221 image_size, partition_size))
222
223 return partition_size
224
225
Bowgo Tsai7ea994b2017-05-19 23:44:26 +0800226def AVBAddFooter(image_path, avbtool, footer_type, partition_size,
Tao Bao2b6dfd62017-09-27 17:17:43 -0700227 partition_name, key_path, algorithm, salt,
Bowgo Tsai3e599ea2017-05-26 18:30:04 +0800228 additional_args):
David Zeuthen4014a9d2016-09-30 17:29:22 -0400229 """Adds dm-verity hashtree and AVB metadata to an image.
230
231 Args:
232 image_path: Path to image to modify.
233 avbtool: String with path to avbtool.
Bowgo Tsai7ea994b2017-05-19 23:44:26 +0800234 footer_type: 'hash' or 'hashtree' for generating footer.
David Zeuthen4014a9d2016-09-30 17:29:22 -0400235 partition_size: The size of the partition in question.
236 partition_name: The name of the partition - will be embedded in metadata.
Bowgo Tsai3e599ea2017-05-26 18:30:04 +0800237 key_path: Path to key to use or None.
238 algorithm: Name of algorithm to use or None.
Tao Bao2b6dfd62017-09-27 17:17:43 -0700239 salt: The salt to use (a hexadecimal string) or None.
Bowgo Tsai040410c2018-09-20 16:40:01 +0800240 additional_args: Additional arguments to pass to "avbtool add_hash_footer"
241 or "avbtool add_hashtree_footer".
Tao Baoc72727a2017-12-07 10:33:00 -0800242
David Zeuthen4014a9d2016-09-30 17:29:22 -0400243 Returns:
244 True if the operation succeeded.
245 """
Tao Baoc72727a2017-12-07 10:33:00 -0800246 cmd = [avbtool, "add_%s_footer" % footer_type,
247 "--partition_size", partition_size,
248 "--partition_name", partition_name,
249 "--image", image_path]
Bowgo Tsai3e599ea2017-05-26 18:30:04 +0800250
251 if key_path and algorithm:
252 cmd.extend(["--key", key_path, "--algorithm", algorithm])
Tao Bao2b6dfd62017-09-27 17:17:43 -0700253 if salt:
254 cmd.extend(["--salt", salt])
Bowgo Tsai3e599ea2017-05-26 18:30:04 +0800255
256 cmd.extend(shlex.split(additional_args))
257
Bowgo Tsai99ed1b42018-09-04 17:31:07 +0800258 output, exit_code = RunCommand(cmd)
259 if exit_code != 0:
260 print("Failed to add AVB footer! Error: %s" % output)
261 return False
262 return True
David Zeuthen4014a9d2016-09-30 17:29:22 -0400263
Tao Baoc72727a2017-12-07 10:33:00 -0800264
Sami Tolvanenf99b5312015-05-20 07:30:57 +0100265def AdjustPartitionSizeForVerity(partition_size, fec_supported):
Geremy Condrafd6f7512013-06-16 17:26:08 -0700266 """Modifies the provided partition size to account for the verity metadata.
267
268 This information is used to size the created image appropriately.
Tao Baoc72727a2017-12-07 10:33:00 -0800269
Geremy Condrafd6f7512013-06-16 17:26:08 -0700270 Args:
271 partition_size: the size of the partition to be verified.
Tao Baoc72727a2017-12-07 10:33:00 -0800272
Geremy Condrafd6f7512013-06-16 17:26:08 -0700273 Returns:
Sami Tolvanen433905f2016-09-01 15:58:35 -0700274 A tuple of the size of the partition adjusted for verity metadata, and
275 the size of verity metadata.
Geremy Condrafd6f7512013-06-16 17:26:08 -0700276 """
Sami Tolvanenf99b5312015-05-20 07:30:57 +0100277 key = "%d %d" % (partition_size, fec_supported)
278 if key in AdjustPartitionSizeForVerity.results:
279 return AdjustPartitionSizeForVerity.results[key]
280
281 hi = partition_size
282 if hi % BLOCK_SIZE != 0:
283 hi = (hi // BLOCK_SIZE) * BLOCK_SIZE
284
285 # verity tree and fec sizes depend on the partition size, which
286 # means this estimate is always going to be unnecessarily small
Sami Tolvanen433905f2016-09-01 15:58:35 -0700287 verity_size = GetVeritySize(hi, fec_supported)
288 lo = partition_size - verity_size
Sami Tolvanenf99b5312015-05-20 07:30:57 +0100289 result = lo
290
291 # do a binary search for the optimal size
292 while lo < hi:
293 i = ((lo + hi) // (2 * BLOCK_SIZE)) * BLOCK_SIZE
Sami Tolvanen433905f2016-09-01 15:58:35 -0700294 v = GetVeritySize(i, fec_supported)
295 if i + v <= partition_size:
Sami Tolvanenf99b5312015-05-20 07:30:57 +0100296 if result < i:
297 result = i
Sami Tolvanen433905f2016-09-01 15:58:35 -0700298 verity_size = v
Sami Tolvanenf99b5312015-05-20 07:30:57 +0100299 lo = i + BLOCK_SIZE
300 else:
301 hi = i
302
Tomasz Wasilczyk29ec06b2017-11-15 10:34:01 -0800303 if OPTIONS.verbose:
304 print("Adjusted partition size for verity, partition_size: {},"
305 " verity_size: {}".format(result, verity_size))
Sami Tolvanen433905f2016-09-01 15:58:35 -0700306 AdjustPartitionSizeForVerity.results[key] = (result, verity_size)
307 return (result, verity_size)
Sami Tolvanenf99b5312015-05-20 07:30:57 +0100308
Tao Baoc72727a2017-12-07 10:33:00 -0800309
Sami Tolvanenf99b5312015-05-20 07:30:57 +0100310AdjustPartitionSizeForVerity.results = {}
311
Tao Baoc72727a2017-12-07 10:33:00 -0800312
Sami Tolvanen433905f2016-09-01 15:58:35 -0700313def BuildVerityFEC(sparse_image_path, verity_path, verity_fec_path,
314 padding_size):
Tianjie Xue3ad41b2017-03-08 11:05:56 -0800315 cmd = ["fec", "-e", "-p", str(padding_size), sparse_image_path,
316 verity_path, verity_fec_path]
317 output, exit_code = RunCommand(cmd)
318 if exit_code != 0:
Tao Baoc72727a2017-12-07 10:33:00 -0800319 print("Could not build FEC data! Error: %s" % output)
Sami Tolvanenf99b5312015-05-20 07:30:57 +0100320 return False
321 return True
Geremy Condrafd6f7512013-06-16 17:26:08 -0700322
Tao Baoc72727a2017-12-07 10:33:00 -0800323
Colin Cross477cf2b2014-04-16 18:49:56 -0700324def BuildVerityTree(sparse_image_path, verity_image_path, prop_dict):
Tianjie Xue3ad41b2017-03-08 11:05:56 -0800325 cmd = ["build_verity_tree", "-A", FIXED_SALT, sparse_image_path,
326 verity_image_path]
327 output, exit_code = RunCommand(cmd)
328 if exit_code != 0:
Tao Baoc72727a2017-12-07 10:33:00 -0800329 print("Could not build verity tree! Error: %s" % output)
Geremy Condrafd6f7512013-06-16 17:26:08 -0700330 return False
331 root, salt = output.split()
332 prop_dict["verity_root_hash"] = root
333 prop_dict["verity_salt"] = salt
334 return True
335
Tao Baoc72727a2017-12-07 10:33:00 -0800336
Geremy Condrafd6f7512013-06-16 17:26:08 -0700337def BuildVerityMetadata(image_size, verity_metadata_path, root_hash, salt,
Bowgo Tsai6ceeb1a2017-10-11 16:21:48 +0800338 block_device, signer_path, key, signer_args,
339 verity_disable):
Tao Baob4ec6d72018-03-15 23:21:28 -0700340 cmd = ["build_verity_metadata.py", "build", str(image_size),
341 verity_metadata_path, root_hash, salt, block_device, signer_path, key]
Tao Bao45810422016-10-17 16:20:12 -0700342 if signer_args:
Tianjie Xue3ad41b2017-03-08 11:05:56 -0800343 cmd.append("--signer_args=\"%s\"" % (' '.join(signer_args),))
Bowgo Tsai6ceeb1a2017-10-11 16:21:48 +0800344 if verity_disable:
345 cmd.append("--verity_disable")
Tianjie Xue3ad41b2017-03-08 11:05:56 -0800346 output, exit_code = RunCommand(cmd)
347 if exit_code != 0:
Tao Baoc72727a2017-12-07 10:33:00 -0800348 print("Could not build verity metadata! Error: %s" % output)
Geremy Condrafd6f7512013-06-16 17:26:08 -0700349 return False
350 return True
351
Tao Baoc72727a2017-12-07 10:33:00 -0800352
Geremy Condrafd6f7512013-06-16 17:26:08 -0700353def Append2Simg(sparse_image_path, unsparse_image_path, error_message):
354 """Appends the unsparse image to the given sparse image.
355
356 Args:
357 sparse_image_path: the path to the (sparse) image
358 unsparse_image_path: the path to the (unsparse) image
359 Returns:
360 True on success, False on failure.
361 """
Tianjie Xue3ad41b2017-03-08 11:05:56 -0800362 cmd = ["append2simg", sparse_image_path, unsparse_image_path]
363 output, exit_code = RunCommand(cmd)
364 if exit_code != 0:
Tao Baoc72727a2017-12-07 10:33:00 -0800365 print("%s: %s" % (error_message, output))
Geremy Condrafd6f7512013-06-16 17:26:08 -0700366 return False
367 return True
368
Tao Baoc72727a2017-12-07 10:33:00 -0800369
Sami Tolvanenff914f52015-12-18 13:24:56 +0000370def Append(target, file_to_append, error_message):
Tao Baoc72727a2017-12-07 10:33:00 -0800371 """Appends file_to_append to target."""
372 try:
373 with open(target, "a") as out_file, open(file_to_append, "r") as input_file:
Tianjie Xue3ad41b2017-03-08 11:05:56 -0800374 for line in input_file:
375 out_file.write(line)
Tao Baoc72727a2017-12-07 10:33:00 -0800376 except IOError:
377 print(error_message)
378 return False
Sami Tolvanenff914f52015-12-18 13:24:56 +0000379 return True
380
Tao Baoc72727a2017-12-07 10:33:00 -0800381
Dan Albert8b72aef2015-03-23 19:13:21 -0700382def BuildVerifiedImage(data_image_path, verity_image_path,
Sami Tolvanen4a060042015-12-18 15:50:25 +0000383 verity_metadata_path, verity_fec_path,
Sami Tolvanen433905f2016-09-01 15:58:35 -0700384 padding_size, fec_supported):
Sami Tolvanenff914f52015-12-18 13:24:56 +0000385 if not Append(verity_image_path, verity_metadata_path,
386 "Could not append verity metadata!"):
Geremy Condrafd6f7512013-06-16 17:26:08 -0700387 return False
Sami Tolvanen4a060042015-12-18 15:50:25 +0000388
389 if fec_supported:
390 # build FEC for the entire partition, including metadata
391 if not BuildVerityFEC(data_image_path, verity_image_path,
Sami Tolvanen433905f2016-09-01 15:58:35 -0700392 verity_fec_path, padding_size):
Sami Tolvanen4a060042015-12-18 15:50:25 +0000393 return False
394
395 if not Append(verity_image_path, verity_fec_path, "Could not append FEC!"):
396 return False
397
Sami Tolvanenff914f52015-12-18 13:24:56 +0000398 if not Append2Simg(data_image_path, verity_image_path,
399 "Could not append verity data!"):
Sami Tolvanenf99b5312015-05-20 07:30:57 +0100400 return False
Geremy Condrafd6f7512013-06-16 17:26:08 -0700401 return True
402
Tao Baoc72727a2017-12-07 10:33:00 -0800403
Geremy Condra6e8f53c2013-12-05 17:09:18 -0800404def UnsparseImage(sparse_image_path, replace=True):
Geremy Condrafd6f7512013-06-16 17:26:08 -0700405 img_dir = os.path.dirname(sparse_image_path)
406 unsparse_image_path = "unsparse_" + os.path.basename(sparse_image_path)
407 unsparse_image_path = os.path.join(img_dir, unsparse_image_path)
408 if os.path.exists(unsparse_image_path):
Geremy Condra6e8f53c2013-12-05 17:09:18 -0800409 if replace:
410 os.unlink(unsparse_image_path)
411 else:
412 return True, unsparse_image_path
Geremy Condrafd6f7512013-06-16 17:26:08 -0700413 inflate_command = ["simg2img", sparse_image_path, unsparse_image_path]
Tao Baocd53a892018-01-19 10:29:52 -0800414 (inflate_output, exit_code) = RunCommand(inflate_command)
Geremy Condrafd6f7512013-06-16 17:26:08 -0700415 if exit_code != 0:
Tao Baocd53a892018-01-19 10:29:52 -0800416 print("Error: '%s' failed with exit code %d:\n%s" % (
417 inflate_command, exit_code, inflate_output))
Geremy Condrafd6f7512013-06-16 17:26:08 -0700418 os.remove(unsparse_image_path)
419 return False, None
420 return True, unsparse_image_path
421
Tao Baoc72727a2017-12-07 10:33:00 -0800422
Sami Tolvanenf99b5312015-05-20 07:30:57 +0100423def MakeVerityEnabledImage(out_file, fec_supported, prop_dict):
Geremy Condrafd6f7512013-06-16 17:26:08 -0700424 """Creates an image that is verifiable using dm-verity.
425
426 Args:
427 out_file: the location to write the verifiable image at
Dan Albert8b72aef2015-03-23 19:13:21 -0700428 prop_dict: a dictionary of properties required for image creation and
429 verification
Geremy Condrafd6f7512013-06-16 17:26:08 -0700430 Returns:
431 True on success, False otherwise.
432 """
433 # get properties
Tao Bao35f4ebc2018-09-27 15:31:11 -0700434 image_size = int(prop_dict["image_size"])
Geremy Condrafd6f7512013-06-16 17:26:08 -0700435 block_dev = prop_dict["verity_block_device"]
Paul Lawrencea37b2bb2014-11-13 17:54:30 -0800436 signer_key = prop_dict["verity_key"] + ".pk8"
Baligh Uddin601ddea2015-06-09 15:48:14 -0700437 if OPTIONS.verity_signer_path is not None:
Tao Bao45810422016-10-17 16:20:12 -0700438 signer_path = OPTIONS.verity_signer_path
Baligh Uddin601ddea2015-06-09 15:48:14 -0700439 else:
440 signer_path = prop_dict["verity_signer_cmd"]
Tao Bao45810422016-10-17 16:20:12 -0700441 signer_args = OPTIONS.verity_signer_args
Geremy Condrafd6f7512013-06-16 17:26:08 -0700442
443 # make a tempdir
Tao Bao1c830bf2017-12-25 10:43:47 -0800444 tempdir_name = common.MakeTempDir(suffix="_verity_images")
Geremy Condrafd6f7512013-06-16 17:26:08 -0700445
446 # get partial image paths
447 verity_image_path = os.path.join(tempdir_name, "verity.img")
448 verity_metadata_path = os.path.join(tempdir_name, "verity_metadata.img")
Sami Tolvanenf99b5312015-05-20 07:30:57 +0100449 verity_fec_path = os.path.join(tempdir_name, "verity_fec.img")
Geremy Condrafd6f7512013-06-16 17:26:08 -0700450
451 # build the verity tree and get the root hash and salt
Colin Cross477cf2b2014-04-16 18:49:56 -0700452 if not BuildVerityTree(out_file, verity_image_path, prop_dict):
Geremy Condrafd6f7512013-06-16 17:26:08 -0700453 return False
454
455 # build the metadata blocks
456 root_hash = prop_dict["verity_root_hash"]
457 salt = prop_dict["verity_salt"]
Bowgo Tsai6ceeb1a2017-10-11 16:21:48 +0800458 verity_disable = "verity_disable" in prop_dict
Dan Albert8b72aef2015-03-23 19:13:21 -0700459 if not BuildVerityMetadata(image_size, verity_metadata_path, root_hash, salt,
Bowgo Tsai6ceeb1a2017-10-11 16:21:48 +0800460 block_dev, signer_path, signer_key, signer_args,
461 verity_disable):
Geremy Condrafd6f7512013-06-16 17:26:08 -0700462 return False
463
464 # build the full verified image
Tao Bao35f4ebc2018-09-27 15:31:11 -0700465 partition_size = int(prop_dict["partition_size"])
Sami Tolvanen433905f2016-09-01 15:58:35 -0700466 verity_size = int(prop_dict["verity_size"])
467
Tao Bao35f4ebc2018-09-27 15:31:11 -0700468 padding_size = partition_size - image_size - verity_size
Sami Tolvanen433905f2016-09-01 15:58:35 -0700469 assert padding_size >= 0
470
Geremy Condrafd6f7512013-06-16 17:26:08 -0700471 if not BuildVerifiedImage(out_file,
472 verity_image_path,
Sami Tolvanen4a060042015-12-18 15:50:25 +0000473 verity_metadata_path,
474 verity_fec_path,
Sami Tolvanen433905f2016-09-01 15:58:35 -0700475 padding_size,
Sami Tolvanen4a060042015-12-18 15:50:25 +0000476 fec_supported):
Geremy Condrafd6f7512013-06-16 17:26:08 -0700477 return False
478
Geremy Condrafd6f7512013-06-16 17:26:08 -0700479 return True
480
Tao Baoc72727a2017-12-07 10:33:00 -0800481
Mohamad Ayyashf8765552016-03-02 21:07:23 -0800482def ConvertBlockMapToBaseFs(block_map_file):
Tao Bao1c830bf2017-12-25 10:43:47 -0800483 base_fs_file = common.MakeTempFile(prefix="script_gen_", suffix=".base_fs")
Mohamad Ayyashf8765552016-03-02 21:07:23 -0800484 convert_command = ["blk_alloc_to_base_fs", block_map_file, base_fs_file]
485 (_, exit_code) = RunCommand(convert_command)
Tao Baoc72727a2017-12-07 10:33:00 -0800486 return base_fs_file if exit_code == 0 else None
Mohamad Ayyashf8765552016-03-02 21:07:23 -0800487
Tao Baod4349f22017-12-07 23:01:25 -0800488
Tao Baoc2606eb2018-07-20 14:44:46 -0700489def SetUpInDirAndFsConfig(origin_in, prop_dict):
490 """Returns the in_dir and fs_config that should be used for image building.
491
Tom Cherryd14b8952018-08-09 14:26:00 -0700492 When building system.img for all targets, it creates and returns a staged dir
493 that combines the contents of /system (i.e. in the given in_dir) and root.
Tao Baoc2606eb2018-07-20 14:44:46 -0700494
495 Args:
496 origin_in: Path to the input directory.
497 prop_dict: A property dict that contains info like partition size. Values
498 may be updated.
499
500 Returns:
501 A tuple of in_dir and fs_config that should be used to build the image.
502 """
503 fs_config = prop_dict.get("fs_config")
Tom Cherryd14b8952018-08-09 14:26:00 -0700504
505 if prop_dict["mount_point"] == "system_other":
506 prop_dict["mount_point"] = "system"
507 return origin_in, fs_config
508
509 if prop_dict["mount_point"] != "system":
Tao Baoc2606eb2018-07-20 14:44:46 -0700510 return origin_in, fs_config
511
512 # Construct a staging directory of the root file system.
513 in_dir = common.MakeTempDir()
514 root_dir = prop_dict.get("root_dir")
515 if root_dir:
516 shutil.rmtree(in_dir)
517 shutil.copytree(root_dir, in_dir, symlinks=True)
518 in_dir_system = os.path.join(in_dir, "system")
519 shutil.rmtree(in_dir_system, ignore_errors=True)
520 shutil.copytree(origin_in, in_dir_system, symlinks=True)
521
522 # Change the mount point to "/".
523 prop_dict["mount_point"] = "/"
524 if fs_config:
525 # We need to merge the fs_config files of system and root.
526 merged_fs_config = common.MakeTempFile(
527 prefix="merged_fs_config", suffix=".txt")
528 with open(merged_fs_config, "w") as fw:
529 if "root_fs_config" in prop_dict:
530 with open(prop_dict["root_fs_config"]) as fr:
531 fw.writelines(fr.readlines())
532 with open(fs_config) as fr:
533 fw.writelines(fr.readlines())
534 fs_config = merged_fs_config
535 return in_dir, fs_config
536
537
Tao Baod4349f22017-12-07 23:01:25 -0800538def CheckHeadroom(ext4fs_output, prop_dict):
539 """Checks if there's enough headroom space available.
540
541 Headroom is the reserved space on system image (via PRODUCT_SYSTEM_HEADROOM),
542 which is useful for devices with low disk space that have system image
543 variation between builds. The 'partition_headroom' in prop_dict is the size
544 in bytes, while the numbers in 'ext4fs_output' are for 4K-blocks.
545
546 Args:
547 ext4fs_output: The output string from mke2fs command.
548 prop_dict: The property dict.
549
550 Returns:
551 The check result.
Tao Baod8a953d2018-01-02 21:19:27 -0800552
553 Raises:
554 AssertionError: On invalid input.
Tao Baod4349f22017-12-07 23:01:25 -0800555 """
Tao Baod8a953d2018-01-02 21:19:27 -0800556 assert ext4fs_output is not None
557 assert prop_dict.get('fs_type', '').startswith('ext4')
558 assert 'partition_headroom' in prop_dict
559 assert 'mount_point' in prop_dict
560
Tao Baod4349f22017-12-07 23:01:25 -0800561 ext4fs_stats = re.compile(
562 r'Created filesystem with .* (?P<used_blocks>[0-9]+)/'
563 r'(?P<total_blocks>[0-9]+) blocks')
Tao Baoc72727a2017-12-07 10:33:00 -0800564 last_line = ext4fs_output.strip().split('\n')[-1]
565 m = ext4fs_stats.match(last_line)
Tao Baod4349f22017-12-07 23:01:25 -0800566 used_blocks = int(m.groupdict().get('used_blocks'))
567 total_blocks = int(m.groupdict().get('total_blocks'))
Tao Baod8a953d2018-01-02 21:19:27 -0800568 headroom_blocks = int(prop_dict['partition_headroom']) / BLOCK_SIZE
Tao Baod4349f22017-12-07 23:01:25 -0800569 adjusted_blocks = total_blocks - headroom_blocks
570 if used_blocks > adjusted_blocks:
Tao Baod8a953d2018-01-02 21:19:27 -0800571 mount_point = prop_dict["mount_point"]
Tao Baod4349f22017-12-07 23:01:25 -0800572 print("Error: Not enough room on %s (total: %d blocks, used: %d blocks, "
573 "headroom: %d blocks, available: %d blocks)" % (
574 mount_point, total_blocks, used_blocks, headroom_blocks,
575 adjusted_blocks))
576 return False
577 return True
578
579
Thierry Strudel74a81e62015-07-09 09:54:55 -0700580def BuildImage(in_dir, prop_dict, out_file, target_out=None):
Tao Baoc2606eb2018-07-20 14:44:46 -0700581 """Builds an image for the files under in_dir and writes it to out_file.
582
Ying Wangbd93d422011-10-28 17:02:30 -0700583 Args:
Tao Baoc2606eb2018-07-20 14:44:46 -0700584 in_dir: Path to input directory.
585 prop_dict: A property dict that contains info like partition size. Values
586 will be updated with computed values.
587 out_file: The output image file.
588 target_out: Path to the TARGET_OUT directory as in Makefile. It actually
589 points to the /system directory under PRODUCT_OUT. fs_config (the one
590 under system/core/libcutils) reads device specific FS config files from
591 there.
Ying Wangbd93d422011-10-28 17:02:30 -0700592
593 Returns:
594 True iff the image is built successfully.
595 """
Tao Baoc2606eb2018-07-20 14:44:46 -0700596 in_dir, fs_config = SetUpInDirAndFsConfig(in_dir, prop_dict)
Ying Wanga2292c92015-03-24 19:07:40 -0700597
Ying Wangbd93d422011-10-28 17:02:30 -0700598 build_command = []
599 fs_type = prop_dict.get("fs_type", "")
Tao Baoc72727a2017-12-07 10:33:00 -0800600 run_e2fsck = False
Geremy Condrafd6f7512013-06-16 17:26:08 -0700601
Mohamad Ayyashdd063522015-03-24 12:42:03 -0700602 fs_spans_partition = True
603 if fs_type.startswith("squash"):
Tao Baoc7a6f1e2015-06-23 11:16:05 -0700604 fs_spans_partition = False
Mohamad Ayyashdd063522015-03-24 12:42:03 -0700605
Daniel Rosenbergf4eabc32014-07-10 15:42:38 -0700606 is_verity_partition = "verity_block_device" in prop_dict
Geremy Condra5b5f4952014-05-05 22:19:37 -0700607 verity_supported = prop_dict.get("verity") == "true"
Sami Tolvanenf99b5312015-05-20 07:30:57 +0100608 verity_fec_supported = prop_dict.get("verity_fec") == "true"
609
Bowgo Tsai040410c2018-09-20 16:40:01 +0800610 avb_footer_type = None
611 if prop_dict.get("avb_hash_enable") == "true":
612 avb_footer_type = "hash"
613 elif prop_dict.get("avb_hashtree_enable") == "true":
614 avb_footer_type = "hashtree"
615
616 if avb_footer_type:
617 avbtool = prop_dict.get("avb_avbtool")
618 avb_signing_args = prop_dict.get(
619 "avb_add_" + avb_footer_type + "_footer_args")
620
Yifan Hong2dae5722018-07-31 12:47:27 -0700621 if (prop_dict.get("use_dynamic_partition_size") == "true" and
Yifan Hongbbcba1e2018-06-18 16:32:35 -0700622 "partition_size" not in prop_dict):
623 # if partition_size is not defined, use output of `du' + reserved_size
Tao Baoc2606eb2018-07-20 14:44:46 -0700624 success, size = GetDiskUsage(in_dir)
Yifan Hongbbcba1e2018-06-18 16:32:35 -0700625 if not success:
626 return False
627 if OPTIONS.verbose:
Tao Baoc2606eb2018-07-20 14:44:46 -0700628 print("The tree size of %s is %d MB." % (in_dir, size // BYTES_IN_MB))
Yifan Hongbbcba1e2018-06-18 16:32:35 -0700629 size += int(prop_dict.get("partition_reserved_size", 0))
630 # Round this up to a multiple of 4K so that avbtool works
631 size = common.RoundUpTo4K(size)
Bowgo Tsai040410c2018-09-20 16:40:01 +0800632 # Adjust partition_size to add more space for AVB footer, to prevent
633 # it from consuming partition_reserved_size.
634 if avb_footer_type:
635 size = AVBCalcMinPartitionSize(
636 size,
637 lambda x: AVBCalcMaxImageSize(
638 avbtool, avb_footer_type, x, avb_signing_args))
Yifan Hongbbcba1e2018-06-18 16:32:35 -0700639 prop_dict["partition_size"] = str(size)
640 if OPTIONS.verbose:
641 print("Allocating %d MB for %s." % (size // BYTES_IN_MB, out_file))
642
Tao Bao35f4ebc2018-09-27 15:31:11 -0700643 prop_dict["image_size"] = prop_dict["partition_size"]
644
645 # Adjust the image size to make room for the hashes if this is to be verified.
Sami Tolvanen405e71d2016-02-09 12:28:58 -0800646 if verity_supported and is_verity_partition:
Geremy Condrafd6f7512013-06-16 17:26:08 -0700647 partition_size = int(prop_dict.get("partition_size"))
Tao Bao35f4ebc2018-09-27 15:31:11 -0700648 image_size, verity_size = AdjustPartitionSizeForVerity(
Tao Baoc72727a2017-12-07 10:33:00 -0800649 partition_size, verity_fec_supported)
Tao Bao35f4ebc2018-09-27 15:31:11 -0700650 if not image_size:
Geremy Condrafd6f7512013-06-16 17:26:08 -0700651 return False
Tao Bao35f4ebc2018-09-27 15:31:11 -0700652 prop_dict["image_size"] = str(image_size)
Sami Tolvanen433905f2016-09-01 15:58:35 -0700653 prop_dict["verity_size"] = str(verity_size)
Geremy Condrafd6f7512013-06-16 17:26:08 -0700654
Tao Bao35f4ebc2018-09-27 15:31:11 -0700655 # Adjust the image size for AVB hash footer or AVB hashtree footer.
Bowgo Tsai7ea994b2017-05-19 23:44:26 +0800656 if avb_footer_type:
Bowgo Tsai3e599ea2017-05-26 18:30:04 +0800657 partition_size = prop_dict["partition_size"]
Bowgo Tsai7ea994b2017-05-19 23:44:26 +0800658 # avb_add_hash_footer_args or avb_add_hashtree_footer_args.
Tao Baoc72727a2017-12-07 10:33:00 -0800659 max_image_size = AVBCalcMaxImageSize(avbtool, avb_footer_type,
Bowgo Tsai040410c2018-09-20 16:40:01 +0800660 partition_size, avb_signing_args)
Bowgo Tsai99ed1b42018-09-04 17:31:07 +0800661 if max_image_size <= 0:
662 print("AVBCalcMaxImageSize is <= 0: %d" % max_image_size)
David Zeuthen4014a9d2016-09-30 17:29:22 -0400663 return False
Tao Bao35f4ebc2018-09-27 15:31:11 -0700664 prop_dict["image_size"] = str(max_image_size)
David Zeuthen4014a9d2016-09-30 17:29:22 -0400665
Ying Wangbd93d422011-10-28 17:02:30 -0700666 if fs_type.startswith("ext"):
Adrien Schildknecht9a072cc2016-11-18 17:06:29 -0800667 build_command = [prop_dict["ext_mkuserimg"]]
Ying Wangbd93d422011-10-28 17:02:30 -0700668 if "extfs_sparse_flag" in prop_dict:
669 build_command.append(prop_dict["extfs_sparse_flag"])
Tao Baoc72727a2017-12-07 10:33:00 -0800670 run_e2fsck = True
Ying Wangbd93d422011-10-28 17:02:30 -0700671 build_command.extend([in_dir, out_file, fs_type,
672 prop_dict["mount_point"]])
Tao Bao35f4ebc2018-09-27 15:31:11 -0700673 build_command.append(prop_dict["image_size"])
Ying Wangf3b86352014-11-18 18:03:13 -0800674 if "journal_size" in prop_dict:
675 build_command.extend(["-j", prop_dict["journal_size"]])
Doug Zongker850b8072013-12-05 15:54:55 -0800676 if "timestamp" in prop_dict:
677 build_command.extend(["-T", str(prop_dict["timestamp"])])
Ying Wanga2292c92015-03-24 19:07:40 -0700678 if fs_config:
Doug Zongker82822822014-06-16 09:10:55 -0700679 build_command.extend(["-C", fs_config])
Thierry Strudel74a81e62015-07-09 09:54:55 -0700680 if target_out:
681 build_command.extend(["-D", target_out])
Ying Wanga2292c92015-03-24 19:07:40 -0700682 if "block_list" in prop_dict:
683 build_command.extend(["-B", prop_dict["block_list"]])
Mohamad Ayyashf8765552016-03-02 21:07:23 -0800684 if "base_fs_file" in prop_dict:
685 base_fs_file = ConvertBlockMapToBaseFs(prop_dict["base_fs_file"])
686 if base_fs_file is None:
687 return False
688 build_command.extend(["-d", base_fs_file])
Christoffer Dall8ed01f32014-12-17 21:34:12 +0100689 build_command.extend(["-L", prop_dict["mount_point"]])
Patrick Tjina1900842016-10-20 10:58:12 -0700690 if "extfs_inode_count" in prop_dict:
691 build_command.extend(["-i", prop_dict["extfs_inode_count"]])
Patrick Tjin3f5f9932018-03-23 11:36:43 -0700692 if "extfs_rsv_pct" in prop_dict:
693 build_command.extend(["-M", prop_dict["extfs_rsv_pct"]])
Connor O'Brien20f08c32017-01-05 16:48:14 -0800694 if "flash_erase_block_size" in prop_dict:
695 build_command.extend(["-e", prop_dict["flash_erase_block_size"]])
696 if "flash_logical_block_size" in prop_dict:
697 build_command.extend(["-o", prop_dict["flash_logical_block_size"]])
Tao Baod86e3112017-09-22 15:45:33 -0700698 # Specify UUID and hash_seed if using mke2fs.
Tianjie Xu57332222018-08-15 16:16:21 -0700699 if prop_dict["ext_mkuserimg"] == "mkuserimg_mke2fs":
Tao Baod86e3112017-09-22 15:45:33 -0700700 if "uuid" in prop_dict:
701 build_command.extend(["-U", prop_dict["uuid"]])
702 if "hash_seed" in prop_dict:
703 build_command.extend(["-S", prop_dict["hash_seed"]])
Jin Qianfde9f792018-01-22 13:15:46 -0800704 if "ext4_share_dup_blocks" in prop_dict:
705 build_command.append("-c")
Ying Wanga2292c92015-03-24 19:07:40 -0700706 if "selinux_fc" in prop_dict:
Kenny Rootf32dc712012-04-08 10:42:34 -0700707 build_command.append(prop_dict["selinux_fc"])
Mohamad Ayyashb97746e2015-03-03 12:30:37 -0800708 elif fs_type.startswith("squash"):
709 build_command = ["mksquashfsimage.sh"]
710 build_command.extend([in_dir, out_file])
Todd Poynorb2a555e2015-12-15 18:00:14 -0800711 if "squashfs_sparse_flag" in prop_dict:
712 build_command.extend([prop_dict["squashfs_sparse_flag"]])
Mohamad Ayyashb97746e2015-03-03 12:30:37 -0800713 build_command.extend(["-m", prop_dict["mount_point"]])
Thierry Strudel74a81e62015-07-09 09:54:55 -0700714 if target_out:
715 build_command.extend(["-d", target_out])
Mohamad Ayyash88378822016-04-07 22:10:51 -0700716 if fs_config:
717 build_command.extend(["-C", fs_config])
Ying Wanga2292c92015-03-24 19:07:40 -0700718 if "selinux_fc" in prop_dict:
Mohamad Ayyashb97746e2015-03-03 12:30:37 -0800719 build_command.extend(["-c", prop_dict["selinux_fc"]])
Mohamad Ayyashc3484f72016-06-13 09:46:58 -0700720 if "block_list" in prop_dict:
721 build_command.extend(["-B", prop_dict["block_list"]])
Ng Zhi An9446c1d2018-01-19 15:51:46 -0800722 if "squashfs_block_size" in prop_dict:
723 build_command.extend(["-b", prop_dict["squashfs_block_size"]])
Simon Wilsonf86e7ee2015-06-17 12:35:15 -0700724 if "squashfs_compressor" in prop_dict:
725 build_command.extend(["-z", prop_dict["squashfs_compressor"]])
726 if "squashfs_compressor_opt" in prop_dict:
727 build_command.extend(["-zo", prop_dict["squashfs_compressor_opt"]])
Tao Baoc72727a2017-12-07 10:33:00 -0800728 if prop_dict.get("squashfs_disable_4k_align") == "true":
Mohamad Ayyash1b6d3482016-06-15 15:53:07 -0700729 build_command.extend(["-a"])
JP Abgrall5bfed5a2014-06-16 14:17:40 -0700730 elif fs_type.startswith("f2fs"):
731 build_command = ["mkf2fsuserimg.sh"]
Tao Bao35f4ebc2018-09-27 15:31:11 -0700732 build_command.extend([out_file, prop_dict["image_size"]])
Jaegeuk Kim2ea1eba2017-11-28 19:21:28 -0800733 if fs_config:
734 build_command.extend(["-C", fs_config])
735 build_command.extend(["-f", in_dir])
736 if target_out:
737 build_command.extend(["-D", target_out])
738 if "selinux_fc" in prop_dict:
739 build_command.extend(["-s", prop_dict["selinux_fc"]])
740 build_command.extend(["-t", prop_dict["mount_point"]])
741 if "timestamp" in prop_dict:
742 build_command.extend(["-T", str(prop_dict["timestamp"])])
743 build_command.extend(["-L", prop_dict["mount_point"]])
Ying Wangbd93d422011-10-28 17:02:30 -0700744 else:
Elliott Hughes305b0882016-06-15 17:04:54 -0700745 print("Error: unknown filesystem type '%s'" % (fs_type))
746 return False
Ying Wangbd93d422011-10-28 17:02:30 -0700747
Tao Baoc72727a2017-12-07 10:33:00 -0800748 (mkfs_output, exit_code) = RunCommand(build_command)
Ying Wang69e9b4d2012-11-26 18:10:23 -0800749 if exit_code != 0:
Tao Baocd53a892018-01-19 10:29:52 -0800750 print("Error: '%s' failed with exit code %d:\n%s" % (
751 build_command, exit_code, mkfs_output))
Tao Baoc2606eb2018-07-20 14:44:46 -0700752 success, du = GetDiskUsage(in_dir)
Yifan Hongbbcba1e2018-06-18 16:32:35 -0700753 du_str = ("%d bytes (%d MB)" % (du, du // BYTES_IN_MB)
754 ) if success else "unknown"
Tao Bao4251fe92018-07-23 13:05:00 -0700755 print(
756 "Out of space? The tree size of {} is {}, with reserved space of {} "
757 "bytes ({} MB).".format(
Tao Baoc2606eb2018-07-20 14:44:46 -0700758 in_dir, du_str,
Tao Bao4251fe92018-07-23 13:05:00 -0700759 int(prop_dict.get("partition_reserved_size", 0)),
760 int(prop_dict.get("partition_reserved_size", 0)) // BYTES_IN_MB))
Tao Bao35f4ebc2018-09-27 15:31:11 -0700761 print(
762 "The max image size for filsystem files is {} bytes ({} MB), out of a "
763 "total partition size of {} bytes ({} MB).".format(
764 int(prop_dict["image_size"]),
765 int(prop_dict["image_size"]) // BYTES_IN_MB,
766 int(prop_dict["partition_size"]),
767 int(prop_dict["partition_size"]) // BYTES_IN_MB))
Ying Wang69e9b4d2012-11-26 18:10:23 -0800768 return False
769
Tao Baod4349f22017-12-07 23:01:25 -0800770 # Check if there's enough headroom space available for ext4 image.
Tao Bao79d52f82017-12-07 14:07:44 -0800771 if "partition_headroom" in prop_dict and fs_type.startswith("ext4"):
Tao Baoc72727a2017-12-07 10:33:00 -0800772 if not CheckHeadroom(mkfs_output, prop_dict):
Tao Baoc7a6f1e2015-06-23 11:16:05 -0700773 return False
774
Mohamad Ayyashdd063522015-03-24 12:42:03 -0700775 if not fs_spans_partition:
776 mount_point = prop_dict.get("mount_point")
Tao Bao35f4ebc2018-09-27 15:31:11 -0700777 image_size = int(prop_dict["image_size"])
778 sparse_image_size = GetSimgSize(out_file)
779 if sparse_image_size > image_size:
Tao Baoc7a6f1e2015-06-23 11:16:05 -0700780 print("Error: %s image size of %d is larger than partition size of "
Tao Bao35f4ebc2018-09-27 15:31:11 -0700781 "%d" % (mount_point, sparse_image_size, image_size))
Tao Baoc7a6f1e2015-06-23 11:16:05 -0700782 return False
Mohamad Ayyashdd063522015-03-24 12:42:03 -0700783 if verity_supported and is_verity_partition:
Tao Bao35f4ebc2018-09-27 15:31:11 -0700784 ZeroPadSimg(out_file, image_size - sparse_image_size)
Mohamad Ayyashdd063522015-03-24 12:42:03 -0700785
Tao Baoc72727a2017-12-07 10:33:00 -0800786 # Create the verified image if this is to be verified.
Geremy Condra5b5f4952014-05-05 22:19:37 -0700787 if verity_supported and is_verity_partition:
Sami Tolvanenf99b5312015-05-20 07:30:57 +0100788 if not MakeVerityEnabledImage(out_file, verity_fec_supported, prop_dict):
Geremy Condrafd6f7512013-06-16 17:26:08 -0700789 return False
790
Bowgo Tsai7ea994b2017-05-19 23:44:26 +0800791 # Add AVB HASH or HASHTREE footer (metadata).
792 if avb_footer_type:
Tao Bao35f4ebc2018-09-27 15:31:11 -0700793 partition_size = prop_dict["partition_size"]
David Zeuthen4014a9d2016-09-30 17:29:22 -0400794 partition_name = prop_dict["partition_name"]
Bowgo Tsai3e599ea2017-05-26 18:30:04 +0800795 # key_path and algorithm are only available when chain partition is used.
796 key_path = prop_dict.get("avb_key_path")
797 algorithm = prop_dict.get("avb_algorithm")
Tao Bao2b6dfd62017-09-27 17:17:43 -0700798 salt = prop_dict.get("avb_salt")
Tao Baoc72727a2017-12-07 10:33:00 -0800799 if not AVBAddFooter(out_file, avbtool, avb_footer_type,
Tao Bao35f4ebc2018-09-27 15:31:11 -0700800 partition_size, partition_name, key_path,
Bowgo Tsai040410c2018-09-20 16:40:01 +0800801 algorithm, salt, avb_signing_args):
David Zeuthen4014a9d2016-09-30 17:29:22 -0400802 return False
803
Tao Baoc72727a2017-12-07 10:33:00 -0800804 if run_e2fsck and prop_dict.get("skip_fsck") != "true":
Geremy Condra6e8f53c2013-12-05 17:09:18 -0800805 success, unsparse_image = UnsparseImage(out_file, replace=False)
Geremy Condrafd6f7512013-06-16 17:26:08 -0700806 if not success:
Ying Wang69e9b4d2012-11-26 18:10:23 -0800807 return False
808
809 # Run e2fsck on the inflated image file
810 e2fsck_command = ["e2fsck", "-f", "-n", unsparse_image]
Isaac Chenec7fa1c2018-08-02 14:02:56 +0800811 # TODO(b/112062612): work around e2fsck failure with SANITIZE_HOST=address
812 env4e2fsck = {"ASAN_OPTIONS": "detect_odr_violation=0"}
813 (e2fsck_output, exit_code) = RunCommand(e2fsck_command, env=env4e2fsck)
Ying Wang69e9b4d2012-11-26 18:10:23 -0800814
815 os.remove(unsparse_image)
816
Elliott Hughes73ff57f2017-12-06 12:16:39 -0800817 if exit_code != 0:
Tao Baocd53a892018-01-19 10:29:52 -0800818 print("Error: '%s' failed with exit code %d:\n%s" % (
819 e2fsck_command, exit_code, e2fsck_output))
Elliott Hughes73ff57f2017-12-06 12:16:39 -0800820 return False
821
822 return True
Ying Wangbd93d422011-10-28 17:02:30 -0700823
824
825def ImagePropFromGlobalDict(glob_dict, mount_point):
826 """Build an image property dictionary from the global dictionary.
827
828 Args:
829 glob_dict: the global dictionary from the build system.
830 mount_point: such as "system", "data" etc.
831 """
Doug Zongker1ad7ade2013-12-06 11:53:27 -0800832 d = {}
Tao Bao052ae352015-09-28 13:44:13 -0700833
Tao Bao822f5842015-09-30 16:01:14 -0700834 if "build.prop" in glob_dict:
835 bp = glob_dict["build.prop"]
836 if "ro.build.date.utc" in bp:
837 d["timestamp"] = bp["ro.build.date.utc"]
Ying Wang9f8e8db2011-11-04 11:37:01 -0700838
839 def copy_prop(src_p, dest_p):
Patrick Tjin3f5f9932018-03-23 11:36:43 -0700840 """Copy a property from the global dictionary.
841
842 Args:
843 src_p: The source property in the global dictionary.
844 dest_p: The destination property.
845 Returns:
846 True if property was found and copied, False otherwise.
847 """
Ying Wang9f8e8db2011-11-04 11:37:01 -0700848 if src_p in glob_dict:
849 d[dest_p] = str(glob_dict[src_p])
Patrick Tjin3f5f9932018-03-23 11:36:43 -0700850 return True
851 return False
Ying Wang9f8e8db2011-11-04 11:37:01 -0700852
Ying Wangbd93d422011-10-28 17:02:30 -0700853 common_props = (
Ying Wangbd93d422011-10-28 17:02:30 -0700854 "extfs_sparse_flag",
Todd Poynorb2a555e2015-12-15 18:00:14 -0800855 "squashfs_sparse_flag",
Kenny Rootf32dc712012-04-08 10:42:34 -0700856 "selinux_fc",
Ying Wang6a42a252013-02-27 13:54:02 -0800857 "skip_fsck",
Adrien Schildknecht9a072cc2016-11-18 17:06:29 -0800858 "ext_mkuserimg",
Geremy Condrafd6f7512013-06-16 17:26:08 -0700859 "verity",
Geremy Condrafd6f7512013-06-16 17:26:08 -0700860 "verity_key",
Sami Tolvanenf99b5312015-05-20 07:30:57 +0100861 "verity_signer_cmd",
David Zeuthen4014a9d2016-09-30 17:29:22 -0400862 "verity_fec",
Bowgo Tsai6ceeb1a2017-10-11 16:21:48 +0800863 "verity_disable",
Bowgo Tsai3e599ea2017-05-26 18:30:04 +0800864 "avb_enable",
Tao Bao2b6dfd62017-09-27 17:17:43 -0700865 "avb_avbtool",
866 "avb_salt",
Yifan Hong2dae5722018-07-31 12:47:27 -0700867 "use_dynamic_partition_size",
Tao Bao2b6dfd62017-09-27 17:17:43 -0700868 )
Ying Wangbd93d422011-10-28 17:02:30 -0700869 for p in common_props:
Ying Wang9f8e8db2011-11-04 11:37:01 -0700870 copy_prop(p, p)
Ying Wangbd93d422011-10-28 17:02:30 -0700871
872 d["mount_point"] = mount_point
873 if mount_point == "system":
Bowgo Tsai3e599ea2017-05-26 18:30:04 +0800874 copy_prop("avb_system_hashtree_enable", "avb_hashtree_enable")
875 copy_prop("avb_system_add_hashtree_footer_args",
876 "avb_add_hashtree_footer_args")
877 copy_prop("avb_system_key_path", "avb_key_path")
878 copy_prop("avb_system_algorithm", "avb_algorithm")
Ying Wang9f8e8db2011-11-04 11:37:01 -0700879 copy_prop("fs_type", "fs_type")
Julius D'souza001c6762017-05-03 13:43:27 -0700880 # Copy the generic system fs type first, override with specific one if
Dan Albert8b72aef2015-03-23 19:13:21 -0700881 # available.
Mohamad Ayyashb97746e2015-03-03 12:30:37 -0800882 copy_prop("system_fs_type", "fs_type")
Julius D'souza001c6762017-05-03 13:43:27 -0700883 copy_prop("system_headroom", "partition_headroom")
Ying Wang9f8e8db2011-11-04 11:37:01 -0700884 copy_prop("system_size", "partition_size")
Tao Bao332a96b2018-03-31 10:27:35 -0700885 if not copy_prop("system_journal_size", "journal_size"):
886 d["journal_size"] = "0"
Daniel Rosenbergf4eabc32014-07-10 15:42:38 -0700887 copy_prop("system_verity_block_device", "verity_block_device")
Tao Baof3282b42015-04-01 11:21:55 -0700888 copy_prop("system_root_image", "system_root_image")
Tao Bao8bfd3c72018-07-20 15:20:28 -0700889 copy_prop("root_dir", "root_dir")
890 copy_prop("root_fs_config", "root_fs_config")
Jin Qianfde9f792018-01-22 13:15:46 -0800891 copy_prop("ext4_share_dup_blocks", "ext4_share_dup_blocks")
Simon Wilsonf86e7ee2015-06-17 12:35:15 -0700892 copy_prop("system_squashfs_compressor", "squashfs_compressor")
893 copy_prop("system_squashfs_compressor_opt", "squashfs_compressor_opt")
Mohamad Ayyashdfec8152016-05-24 12:59:30 -0700894 copy_prop("system_squashfs_block_size", "squashfs_block_size")
Mohamad Ayyash1b6d3482016-06-15 15:53:07 -0700895 copy_prop("system_squashfs_disable_4k_align", "squashfs_disable_4k_align")
Mohamad Ayyashf8765552016-03-02 21:07:23 -0800896 copy_prop("system_base_fs_file", "base_fs_file")
Patrick Tjina1900842016-10-20 10:58:12 -0700897 copy_prop("system_extfs_inode_count", "extfs_inode_count")
Patrick Tjin3f5f9932018-03-23 11:36:43 -0700898 if not copy_prop("system_extfs_rsv_pct", "extfs_rsv_pct"):
899 d["extfs_rsv_pct"] = "0"
Yifan Hongbbcba1e2018-06-18 16:32:35 -0700900 copy_prop("system_reserved_size", "partition_reserved_size")
Alex Light4e358ab2016-06-16 14:47:10 -0700901 elif mount_point == "system_other":
Tao Baoc72727a2017-12-07 10:33:00 -0800902 # We inherit the selinux policies of /system since we contain some of its
903 # files.
Bowgo Tsai3e599ea2017-05-26 18:30:04 +0800904 copy_prop("avb_system_hashtree_enable", "avb_hashtree_enable")
905 copy_prop("avb_system_add_hashtree_footer_args",
906 "avb_add_hashtree_footer_args")
907 copy_prop("avb_system_key_path", "avb_key_path")
908 copy_prop("avb_system_algorithm", "avb_algorithm")
Alex Light4e358ab2016-06-16 14:47:10 -0700909 copy_prop("fs_type", "fs_type")
910 copy_prop("system_fs_type", "fs_type")
911 copy_prop("system_size", "partition_size")
Tao Bao332a96b2018-03-31 10:27:35 -0700912 if not copy_prop("system_journal_size", "journal_size"):
913 d["journal_size"] = "0"
Alex Light4e358ab2016-06-16 14:47:10 -0700914 copy_prop("system_verity_block_device", "verity_block_device")
Alex Light4e358ab2016-06-16 14:47:10 -0700915 copy_prop("system_squashfs_compressor", "squashfs_compressor")
916 copy_prop("system_squashfs_compressor_opt", "squashfs_compressor_opt")
917 copy_prop("system_squashfs_block_size", "squashfs_block_size")
918 copy_prop("system_base_fs_file", "base_fs_file")
Patrick Tjina1900842016-10-20 10:58:12 -0700919 copy_prop("system_extfs_inode_count", "extfs_inode_count")
Patrick Tjin3f5f9932018-03-23 11:36:43 -0700920 if not copy_prop("system_extfs_rsv_pct", "extfs_rsv_pct"):
921 d["extfs_rsv_pct"] = "0"
Yifan Hongbbcba1e2018-06-18 16:32:35 -0700922 copy_prop("system_reserved_size", "partition_reserved_size")
Ying Wangbd93d422011-10-28 17:02:30 -0700923 elif mount_point == "data":
JP Abgrall5bfed5a2014-06-16 14:17:40 -0700924 # Copy the generic fs type first, override with specific one if available.
Ying Wang9f8e8db2011-11-04 11:37:01 -0700925 copy_prop("fs_type", "fs_type")
JP Abgrall5bfed5a2014-06-16 14:17:40 -0700926 copy_prop("userdata_fs_type", "fs_type")
Ying Wang9f8e8db2011-11-04 11:37:01 -0700927 copy_prop("userdata_size", "partition_size")
Tao Baoc72727a2017-12-07 10:33:00 -0800928 copy_prop("flash_logical_block_size", "flash_logical_block_size")
Connor O'Brien20f08c32017-01-05 16:48:14 -0800929 copy_prop("flash_erase_block_size", "flash_erase_block_size")
Ying Wang9f8e8db2011-11-04 11:37:01 -0700930 elif mount_point == "cache":
931 copy_prop("cache_fs_type", "fs_type")
932 copy_prop("cache_size", "partition_size")
Ying Wanga0febe52013-03-20 11:02:05 -0700933 elif mount_point == "vendor":
Bowgo Tsai3e599ea2017-05-26 18:30:04 +0800934 copy_prop("avb_vendor_hashtree_enable", "avb_hashtree_enable")
935 copy_prop("avb_vendor_add_hashtree_footer_args",
936 "avb_add_hashtree_footer_args")
937 copy_prop("avb_vendor_key_path", "avb_key_path")
938 copy_prop("avb_vendor_algorithm", "avb_algorithm")
Ying Wanga0febe52013-03-20 11:02:05 -0700939 copy_prop("vendor_fs_type", "fs_type")
940 copy_prop("vendor_size", "partition_size")
Tao Bao332a96b2018-03-31 10:27:35 -0700941 if not copy_prop("vendor_journal_size", "journal_size"):
942 d["journal_size"] = "0"
Daniel Rosenbergf4eabc32014-07-10 15:42:38 -0700943 copy_prop("vendor_verity_block_device", "verity_block_device")
Jin Qianfde9f792018-01-22 13:15:46 -0800944 copy_prop("ext4_share_dup_blocks", "ext4_share_dup_blocks")
Patrick Tjine11aa502016-02-09 15:40:38 -0800945 copy_prop("vendor_squashfs_compressor", "squashfs_compressor")
946 copy_prop("vendor_squashfs_compressor_opt", "squashfs_compressor_opt")
Mohamad Ayyashdfec8152016-05-24 12:59:30 -0700947 copy_prop("vendor_squashfs_block_size", "squashfs_block_size")
Mohamad Ayyash1b6d3482016-06-15 15:53:07 -0700948 copy_prop("vendor_squashfs_disable_4k_align", "squashfs_disable_4k_align")
Mohamad Ayyashf8765552016-03-02 21:07:23 -0800949 copy_prop("vendor_base_fs_file", "base_fs_file")
Patrick Tjina1900842016-10-20 10:58:12 -0700950 copy_prop("vendor_extfs_inode_count", "extfs_inode_count")
Patrick Tjin3f5f9932018-03-23 11:36:43 -0700951 if not copy_prop("vendor_extfs_rsv_pct", "extfs_rsv_pct"):
952 d["extfs_rsv_pct"] = "0"
Yifan Hong749062d2018-06-19 16:23:16 -0700953 copy_prop("vendor_reserved_size", "partition_reserved_size")
Jaekyun Seokb7735d82017-11-27 17:04:47 +0900954 elif mount_point == "product":
955 copy_prop("avb_product_hashtree_enable", "avb_hashtree_enable")
956 copy_prop("avb_product_add_hashtree_footer_args",
957 "avb_add_hashtree_footer_args")
958 copy_prop("avb_product_key_path", "avb_key_path")
959 copy_prop("avb_product_algorithm", "avb_algorithm")
960 copy_prop("product_fs_type", "fs_type")
961 copy_prop("product_size", "partition_size")
Tao Bao332a96b2018-03-31 10:27:35 -0700962 if not copy_prop("product_journal_size", "journal_size"):
963 d["journal_size"] = "0"
Jaekyun Seokb7735d82017-11-27 17:04:47 +0900964 copy_prop("product_verity_block_device", "verity_block_device")
965 copy_prop("product_squashfs_compressor", "squashfs_compressor")
966 copy_prop("product_squashfs_compressor_opt", "squashfs_compressor_opt")
967 copy_prop("product_squashfs_block_size", "squashfs_block_size")
968 copy_prop("product_squashfs_disable_4k_align", "squashfs_disable_4k_align")
969 copy_prop("product_base_fs_file", "base_fs_file")
970 copy_prop("product_extfs_inode_count", "extfs_inode_count")
Patrick Tjin3f5f9932018-03-23 11:36:43 -0700971 if not copy_prop("product_extfs_rsv_pct", "extfs_rsv_pct"):
972 d["extfs_rsv_pct"] = "0"
Yifan Hong56a6c3b2018-07-20 15:19:34 -0700973 copy_prop("product_reserved_size", "partition_reserved_size")
Dario Freni924af7d2018-08-17 00:56:14 +0100974 elif mount_point == "product_services":
Yifan Hongebc041a2018-07-26 16:02:52 -0700975 copy_prop("avb_product_services_hashtree_enable", "avb_hashtree_enable")
976 copy_prop("avb_product_services_add_hashtree_footer_args",
Dario Freni5f681e12018-05-29 13:09:01 +0100977 "avb_add_hashtree_footer_args")
Yifan Hongebc041a2018-07-26 16:02:52 -0700978 copy_prop("avb_product_services_key_path", "avb_key_path")
979 copy_prop("avb_product_services_algorithm", "avb_algorithm")
980 copy_prop("product_services_fs_type", "fs_type")
981 copy_prop("product_services_size", "partition_size")
982 if not copy_prop("product_services_journal_size", "journal_size"):
Dario Freni5f681e12018-05-29 13:09:01 +0100983 d["journal_size"] = "0"
Yifan Hongebc041a2018-07-26 16:02:52 -0700984 copy_prop("product_services_verity_block_device", "verity_block_device")
985 copy_prop("product_services_squashfs_compressor", "squashfs_compressor")
986 copy_prop("product_services_squashfs_compressor_opt",
Dario Freni5f681e12018-05-29 13:09:01 +0100987 "squashfs_compressor_opt")
Yifan Hongebc041a2018-07-26 16:02:52 -0700988 copy_prop("product_services_squashfs_block_size", "squashfs_block_size")
989 copy_prop("product_services_squashfs_disable_4k_align",
Dario Freni5f681e12018-05-29 13:09:01 +0100990 "squashfs_disable_4k_align")
Yifan Hongebc041a2018-07-26 16:02:52 -0700991 copy_prop("product_services_base_fs_file", "base_fs_file")
992 copy_prop("product_services_extfs_inode_count", "extfs_inode_count")
993 if not copy_prop("product_services_extfs_rsv_pct", "extfs_rsv_pct"):
Dario Freni5f681e12018-05-29 13:09:01 +0100994 d["extfs_rsv_pct"] = "0"
Yifan Hongebc041a2018-07-26 16:02:52 -0700995 copy_prop("product_services_reserved_size", "partition_reserved_size")
Bowgo Tsaid624fa62017-11-14 23:42:30 +0800996 elif mount_point == "odm":
997 copy_prop("avb_odm_hashtree_enable", "avb_hashtree_enable")
998 copy_prop("avb_odm_add_hashtree_footer_args",
999 "avb_add_hashtree_footer_args")
1000 copy_prop("avb_odm_key_path", "avb_key_path")
1001 copy_prop("avb_odm_algorithm", "avb_algorithm")
1002 copy_prop("odm_fs_type", "fs_type")
1003 copy_prop("odm_size", "partition_size")
1004 if not copy_prop("odm_journal_size", "journal_size"):
1005 d["journal_size"] = "0"
1006 copy_prop("odm_verity_block_device", "verity_block_device")
1007 copy_prop("odm_squashfs_compressor", "squashfs_compressor")
1008 copy_prop("odm_squashfs_compressor_opt", "squashfs_compressor_opt")
1009 copy_prop("odm_squashfs_block_size", "squashfs_block_size")
1010 copy_prop("odm_squashfs_disable_4k_align", "squashfs_disable_4k_align")
1011 copy_prop("odm_base_fs_file", "base_fs_file")
1012 copy_prop("odm_extfs_inode_count", "extfs_inode_count")
1013 if not copy_prop("odm_extfs_rsv_pct", "extfs_rsv_pct"):
1014 d["extfs_rsv_pct"] = "0"
1015 copy_prop("odm_reserved_size", "partition_reserved_size")
Ying Wangb8888432014-03-11 17:13:27 -07001016 elif mount_point == "oem":
1017 copy_prop("fs_type", "fs_type")
1018 copy_prop("oem_size", "partition_size")
Tao Bao332a96b2018-03-31 10:27:35 -07001019 if not copy_prop("oem_journal_size", "journal_size"):
1020 d["journal_size"] = "0"
Patrick Tjina1900842016-10-20 10:58:12 -07001021 copy_prop("oem_extfs_inode_count", "extfs_inode_count")
Patrick Tjin3f5f9932018-03-23 11:36:43 -07001022 if not copy_prop("oem_extfs_rsv_pct", "extfs_rsv_pct"):
1023 d["extfs_rsv_pct"] = "0"
David Zeuthen4014a9d2016-09-30 17:29:22 -04001024 d["partition_name"] = mount_point
Ying Wangbd93d422011-10-28 17:02:30 -07001025 return d
1026
1027
1028def LoadGlobalDict(filename):
1029 """Load "name=value" pairs from filename"""
1030 d = {}
1031 f = open(filename)
1032 for line in f:
1033 line = line.strip()
1034 if not line or line.startswith("#"):
1035 continue
1036 k, v = line.split("=", 1)
1037 d[k] = v
1038 f.close()
1039 return d
1040
1041
Yifan Hongbbcba1e2018-06-18 16:32:35 -07001042def GlobalDictFromImageProp(image_prop, mount_point):
1043 d = {}
1044 def copy_prop(src_p, dest_p):
1045 if src_p in image_prop:
1046 d[dest_p] = image_prop[src_p]
1047 return True
1048 return False
Tao Bao4251fe92018-07-23 13:05:00 -07001049
Yifan Hongbbcba1e2018-06-18 16:32:35 -07001050 if mount_point == "system":
Tao Bao35f4ebc2018-09-27 15:31:11 -07001051 copy_prop("partition_size", "system_size")
Yifan Hongbbcba1e2018-06-18 16:32:35 -07001052 elif mount_point == "system_other":
Tao Bao35f4ebc2018-09-27 15:31:11 -07001053 copy_prop("partition_size", "system_size")
Yifan Hong749062d2018-06-19 16:23:16 -07001054 elif mount_point == "vendor":
Tao Bao35f4ebc2018-09-27 15:31:11 -07001055 copy_prop("partition_size", "vendor_size")
Bowgo Tsaid624fa62017-11-14 23:42:30 +08001056 elif mount_point == "odm":
Tao Bao35f4ebc2018-09-27 15:31:11 -07001057 copy_prop("partition_size", "odm_size")
Yifan Hong56a6c3b2018-07-20 15:19:34 -07001058 elif mount_point == "product":
Tao Bao35f4ebc2018-09-27 15:31:11 -07001059 copy_prop("partition_size", "product_size")
Dario Freni924af7d2018-08-17 00:56:14 +01001060 elif mount_point == "product_services":
Tao Bao35f4ebc2018-09-27 15:31:11 -07001061 copy_prop("partition_size", "product_services_size")
Yifan Hongbbcba1e2018-06-18 16:32:35 -07001062 return d
1063
1064
1065def SaveGlobalDict(filename, glob_dict):
1066 with open(filename, "w") as f:
1067 f.writelines(["%s=%s" % (key, value) for (key, value) in glob_dict.items()])
1068
1069
Ying Wangbd93d422011-10-28 17:02:30 -07001070def main(argv):
Yifan Hongbbcba1e2018-06-18 16:32:35 -07001071 if len(argv) < 4 or len(argv) > 5:
Tao Baoc72727a2017-12-07 10:33:00 -08001072 print(__doc__)
Ying Wangbd93d422011-10-28 17:02:30 -07001073 sys.exit(1)
1074
1075 in_dir = argv[0]
1076 glob_dict_file = argv[1]
1077 out_file = argv[2]
Thierry Strudel74a81e62015-07-09 09:54:55 -07001078 target_out = argv[3]
Yifan Hongbbcba1e2018-06-18 16:32:35 -07001079 prop_file_out = argv[4] if len(argv) >= 5 else None
Ying Wangbd93d422011-10-28 17:02:30 -07001080
1081 glob_dict = LoadGlobalDict(glob_dict_file)
Ying Wangae61f502015-03-12 18:30:39 -07001082 if "mount_point" in glob_dict:
Tao Baoc7a6f1e2015-06-23 11:16:05 -07001083 # The caller knows the mount point and provides a dictionay needed by
1084 # BuildImage().
Ying Wangae61f502015-03-12 18:30:39 -07001085 image_properties = glob_dict
Ying Wang9f8e8db2011-11-04 11:37:01 -07001086 else:
Ying Wangae61f502015-03-12 18:30:39 -07001087 image_filename = os.path.basename(out_file)
1088 mount_point = ""
1089 if image_filename == "system.img":
1090 mount_point = "system"
Alex Light4e358ab2016-06-16 14:47:10 -07001091 elif image_filename == "system_other.img":
1092 mount_point = "system_other"
Ying Wangae61f502015-03-12 18:30:39 -07001093 elif image_filename == "userdata.img":
1094 mount_point = "data"
1095 elif image_filename == "cache.img":
1096 mount_point = "cache"
1097 elif image_filename == "vendor.img":
1098 mount_point = "vendor"
Bowgo Tsaid624fa62017-11-14 23:42:30 +08001099 elif image_filename == "odm.img":
1100 mount_point = "odm"
Ying Wangae61f502015-03-12 18:30:39 -07001101 elif image_filename == "oem.img":
1102 mount_point = "oem"
Jaekyun Seokb7735d82017-11-27 17:04:47 +09001103 elif image_filename == "product.img":
1104 mount_point = "product"
Dario Freni924af7d2018-08-17 00:56:14 +01001105 elif image_filename == "product_services.img":
1106 mount_point = "product_services"
Ying Wangae61f502015-03-12 18:30:39 -07001107 else:
Tao Baoc72727a2017-12-07 10:33:00 -08001108 print("error: unknown image file name ", image_filename, file=sys.stderr)
Tao Bao1c830bf2017-12-25 10:43:47 -08001109 sys.exit(1)
Ying Wangbd93d422011-10-28 17:02:30 -07001110
Ying Wangae61f502015-03-12 18:30:39 -07001111 image_properties = ImagePropFromGlobalDict(glob_dict, mount_point)
1112
Thierry Strudel74a81e62015-07-09 09:54:55 -07001113 if not BuildImage(in_dir, image_properties, out_file, target_out):
Tao Baoc72727a2017-12-07 10:33:00 -08001114 print("error: failed to build %s from %s" % (out_file, in_dir),
1115 file=sys.stderr)
Tao Bao1c830bf2017-12-25 10:43:47 -08001116 sys.exit(1)
Ying Wangbd93d422011-10-28 17:02:30 -07001117
Yifan Hongbbcba1e2018-06-18 16:32:35 -07001118 if prop_file_out:
1119 glob_dict_out = GlobalDictFromImageProp(image_properties, mount_point)
1120 SaveGlobalDict(prop_file_out, glob_dict_out)
Ying Wangbd93d422011-10-28 17:02:30 -07001121
1122if __name__ == '__main__':
Tao Bao1c830bf2017-12-25 10:43:47 -08001123 try:
1124 main(sys.argv[1:])
1125 finally:
1126 common.Cleanup()