blob: 28d70d33db74a57b237de513c25e28fe05ee3b7d [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"""
Maria Bornski885dbb52015-09-04 11:13:16 -070018Build image output_image_file from input_directory, properties_file, and target_out_dir
Ying Wangbd93d422011-10-28 17:02:30 -070019
Maria Bornski885dbb52015-09-04 11:13:16 -070020Usage: build_image input_directory properties_file output_image_file target_out_dir
Ying Wangbd93d422011-10-28 17:02:30 -070021
22"""
23import os
Ying Wang69e9b4d2012-11-26 18:10:23 -080024import os.path
Tao Baoc7a6f1e2015-06-23 11:16:05 -070025import re
Ying Wangbd93d422011-10-28 17:02:30 -070026import subprocess
27import sys
Geremy Condrafd6f7512013-06-16 17:26:08 -070028import commands
Baligh Uddin601ddea2015-06-09 15:48:14 -070029import common
David Zeuthen4014a9d2016-09-30 17:29:22 -040030import shlex
Geremy Condrafd6f7512013-06-16 17:26:08 -070031import shutil
Sami Tolvanen405e71d2016-02-09 12:28:58 -080032import sparse_img
Geremy Condra5b5f4952014-05-05 22:19:37 -070033import tempfile
Ying Wangbd93d422011-10-28 17:02:30 -070034
Baligh Uddin601ddea2015-06-09 15:48:14 -070035OPTIONS = common.OPTIONS
36
Geremy Condrae8e982a2014-05-16 19:14:30 -070037FIXED_SALT = "aee087a5be3b982978c923f566a94613496b417f2af592639bc80d141e34dfe7"
Sami Tolvanenf99b5312015-05-20 07:30:57 +010038BLOCK_SIZE = 4096
Geremy Condrae8e982a2014-05-16 19:14:30 -070039
Ying Wang69e9b4d2012-11-26 18:10:23 -080040def RunCommand(cmd):
Tao Baoc7a6f1e2015-06-23 11:16:05 -070041 """Echo and run the given command.
Ying Wang69e9b4d2012-11-26 18:10:23 -080042
43 Args:
44 cmd: the command represented as a list of strings.
45 Returns:
Tao Baoc7a6f1e2015-06-23 11:16:05 -070046 A tuple of the output and the exit code.
Ying Wang69e9b4d2012-11-26 18:10:23 -080047 """
48 print "Running: ", " ".join(cmd)
Tao Baoc7a6f1e2015-06-23 11:16:05 -070049 p = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
50 output, _ = p.communicate()
51 print "%s" % (output.rstrip(),)
52 return (output, p.returncode)
Ying Wangbd93d422011-10-28 17:02:30 -070053
Sami Tolvanenf99b5312015-05-20 07:30:57 +010054def GetVerityFECSize(partition_size):
55 cmd = "fec -s %d" % partition_size
56 status, output = commands.getstatusoutput(cmd)
57 if status:
58 print output
59 return False, 0
60 return True, int(output)
61
Geremy Condrafd6f7512013-06-16 17:26:08 -070062def GetVerityTreeSize(partition_size):
Colin Cross477cf2b2014-04-16 18:49:56 -070063 cmd = "build_verity_tree -s %d"
Geremy Condrafd6f7512013-06-16 17:26:08 -070064 cmd %= partition_size
65 status, output = commands.getstatusoutput(cmd)
66 if status:
67 print output
68 return False, 0
69 return True, int(output)
70
71def GetVerityMetadataSize(partition_size):
72 cmd = "system/extras/verity/build_verity_metadata.py -s %d"
73 cmd %= partition_size
Baligh Uddin601ddea2015-06-09 15:48:14 -070074
Geremy Condrafd6f7512013-06-16 17:26:08 -070075 status, output = commands.getstatusoutput(cmd)
76 if status:
77 print output
78 return False, 0
79 return True, int(output)
80
Sami Tolvanenf99b5312015-05-20 07:30:57 +010081def GetVeritySize(partition_size, fec_supported):
82 success, verity_tree_size = GetVerityTreeSize(partition_size)
83 if not success:
84 return 0
85 success, verity_metadata_size = GetVerityMetadataSize(partition_size)
86 if not success:
87 return 0
88 verity_size = verity_tree_size + verity_metadata_size
89 if fec_supported:
90 success, fec_size = GetVerityFECSize(partition_size + verity_size)
91 if not success:
92 return 0
93 return verity_size + fec_size
94 return verity_size
95
Sami Tolvanen405e71d2016-02-09 12:28:58 -080096def GetSimgSize(image_file):
97 simg = sparse_img.SparseImage(image_file, build_map=False)
98 return simg.blocksize * simg.total_blocks
99
100def ZeroPadSimg(image_file, pad_size):
101 blocks = pad_size // BLOCK_SIZE
102 print("Padding %d blocks (%d bytes)" % (blocks, pad_size))
103 simg = sparse_img.SparseImage(image_file, mode="r+b", build_map=False)
104 simg.AppendFillChunk(0, blocks)
105
David Zeuthen4014a9d2016-09-30 17:29:22 -0400106def AVBCalcMaxImageSize(avbtool, partition_size, additional_args):
107 """Calculates max image size for a given partition size.
108
109 Args:
110 avbtool: String with path to avbtool.
111 partition_size: The size of the partition in question.
112 additional_args: Additional arguments to pass to 'avbtool
113 add_hashtree_image'.
114 Returns:
115 The maximum image size or 0 if an error occurred.
116 """
117 cmdline = "%s add_hashtree_footer " % avbtool
118 cmdline += "--partition_size %d " % partition_size
119 cmdline += "--calc_max_image_size "
120 cmdline += additional_args
121 (output, exit_code) = RunCommand(shlex.split(cmdline))
122 if exit_code != 0:
123 return 0
124 else:
125 return int(output)
126
127def AVBAddHashtree(image_path, avbtool, partition_size, partition_name,
128 signing_args, additional_args):
129 """Adds dm-verity hashtree and AVB metadata to an image.
130
131 Args:
132 image_path: Path to image to modify.
133 avbtool: String with path to avbtool.
134 partition_size: The size of the partition in question.
135 partition_name: The name of the partition - will be embedded in metadata.
136 signing_args: Arguments for signing the image.
137 additional_args: Additional arguments to pass to 'avbtool
138 add_hashtree_image'.
139 Returns:
140 True if the operation succeeded.
141 """
142 cmdline = "%s add_hashtree_footer " % avbtool
143 cmdline += "--partition_size %d " % partition_size
144 cmdline += "--partition_name %s " % partition_name
145 cmdline += "--image %s " % image_path
146 cmdline += signing_args + " "
147 cmdline += additional_args
148 (_, exit_code) = RunCommand(shlex.split(cmdline))
149 return exit_code == 0
150
Sami Tolvanenf99b5312015-05-20 07:30:57 +0100151def AdjustPartitionSizeForVerity(partition_size, fec_supported):
Geremy Condrafd6f7512013-06-16 17:26:08 -0700152 """Modifies the provided partition size to account for the verity metadata.
153
154 This information is used to size the created image appropriately.
155 Args:
156 partition_size: the size of the partition to be verified.
157 Returns:
Sami Tolvanen433905f2016-09-01 15:58:35 -0700158 A tuple of the size of the partition adjusted for verity metadata, and
159 the size of verity metadata.
Geremy Condrafd6f7512013-06-16 17:26:08 -0700160 """
Sami Tolvanenf99b5312015-05-20 07:30:57 +0100161 key = "%d %d" % (partition_size, fec_supported)
162 if key in AdjustPartitionSizeForVerity.results:
163 return AdjustPartitionSizeForVerity.results[key]
164
165 hi = partition_size
166 if hi % BLOCK_SIZE != 0:
167 hi = (hi // BLOCK_SIZE) * BLOCK_SIZE
168
169 # verity tree and fec sizes depend on the partition size, which
170 # means this estimate is always going to be unnecessarily small
Sami Tolvanen433905f2016-09-01 15:58:35 -0700171 verity_size = GetVeritySize(hi, fec_supported)
172 lo = partition_size - verity_size
Sami Tolvanenf99b5312015-05-20 07:30:57 +0100173 result = lo
174
175 # do a binary search for the optimal size
176 while lo < hi:
177 i = ((lo + hi) // (2 * BLOCK_SIZE)) * BLOCK_SIZE
Sami Tolvanen433905f2016-09-01 15:58:35 -0700178 v = GetVeritySize(i, fec_supported)
179 if i + v <= partition_size:
Sami Tolvanenf99b5312015-05-20 07:30:57 +0100180 if result < i:
181 result = i
Sami Tolvanen433905f2016-09-01 15:58:35 -0700182 verity_size = v
Sami Tolvanenf99b5312015-05-20 07:30:57 +0100183 lo = i + BLOCK_SIZE
184 else:
185 hi = i
186
Sami Tolvanen433905f2016-09-01 15:58:35 -0700187 AdjustPartitionSizeForVerity.results[key] = (result, verity_size)
188 return (result, verity_size)
Sami Tolvanenf99b5312015-05-20 07:30:57 +0100189
190AdjustPartitionSizeForVerity.results = {}
191
Sami Tolvanen433905f2016-09-01 15:58:35 -0700192def BuildVerityFEC(sparse_image_path, verity_path, verity_fec_path,
193 padding_size):
194 cmd = "fec -e -p %d %s %s %s" % (padding_size, sparse_image_path,
195 verity_path, verity_fec_path)
Sami Tolvanenf99b5312015-05-20 07:30:57 +0100196 print cmd
197 status, output = commands.getstatusoutput(cmd)
198 if status:
199 print "Could not build FEC data! Error: %s" % output
200 return False
201 return True
Geremy Condrafd6f7512013-06-16 17:26:08 -0700202
Colin Cross477cf2b2014-04-16 18:49:56 -0700203def BuildVerityTree(sparse_image_path, verity_image_path, prop_dict):
Dan Albert8b72aef2015-03-23 19:13:21 -0700204 cmd = "build_verity_tree -A %s %s %s" % (
205 FIXED_SALT, sparse_image_path, verity_image_path)
Geremy Condrafd6f7512013-06-16 17:26:08 -0700206 print cmd
207 status, output = commands.getstatusoutput(cmd)
208 if status:
209 print "Could not build verity tree! Error: %s" % output
210 return False
211 root, salt = output.split()
212 prop_dict["verity_root_hash"] = root
213 prop_dict["verity_salt"] = salt
214 return True
215
216def BuildVerityMetadata(image_size, verity_metadata_path, root_hash, salt,
217 block_device, signer_path, key):
Dan Albert8b72aef2015-03-23 19:13:21 -0700218 cmd_template = (
219 "system/extras/verity/build_verity_metadata.py %s %s %s %s %s %s %s")
220 cmd = cmd_template % (image_size, verity_metadata_path, root_hash, salt,
221 block_device, signer_path, key)
Geremy Condrafd6f7512013-06-16 17:26:08 -0700222 print cmd
223 status, output = commands.getstatusoutput(cmd)
224 if status:
225 print "Could not build verity metadata! Error: %s" % output
226 return False
227 return True
228
229def Append2Simg(sparse_image_path, unsparse_image_path, error_message):
230 """Appends the unsparse image to the given sparse image.
231
232 Args:
233 sparse_image_path: the path to the (sparse) image
234 unsparse_image_path: the path to the (unsparse) image
235 Returns:
236 True on success, False on failure.
237 """
238 cmd = "append2simg %s %s"
239 cmd %= (sparse_image_path, unsparse_image_path)
240 print cmd
241 status, output = commands.getstatusoutput(cmd)
242 if status:
243 print "%s: %s" % (error_message, output)
244 return False
245 return True
246
Sami Tolvanenff914f52015-12-18 13:24:56 +0000247def Append(target, file_to_append, error_message):
248 cmd = 'cat %s >> %s' % (file_to_append, target)
249 print cmd
250 status, output = commands.getstatusoutput(cmd)
251 if status:
252 print "%s: %s" % (error_message, output)
253 return False
254 return True
255
Dan Albert8b72aef2015-03-23 19:13:21 -0700256def BuildVerifiedImage(data_image_path, verity_image_path,
Sami Tolvanen4a060042015-12-18 15:50:25 +0000257 verity_metadata_path, verity_fec_path,
Sami Tolvanen433905f2016-09-01 15:58:35 -0700258 padding_size, fec_supported):
Sami Tolvanenff914f52015-12-18 13:24:56 +0000259 if not Append(verity_image_path, verity_metadata_path,
260 "Could not append verity metadata!"):
Geremy Condrafd6f7512013-06-16 17:26:08 -0700261 return False
Sami Tolvanen4a060042015-12-18 15:50:25 +0000262
263 if fec_supported:
264 # build FEC for the entire partition, including metadata
265 if not BuildVerityFEC(data_image_path, verity_image_path,
Sami Tolvanen433905f2016-09-01 15:58:35 -0700266 verity_fec_path, padding_size):
Sami Tolvanen4a060042015-12-18 15:50:25 +0000267 return False
268
269 if not Append(verity_image_path, verity_fec_path, "Could not append FEC!"):
270 return False
271
Sami Tolvanenff914f52015-12-18 13:24:56 +0000272 if not Append2Simg(data_image_path, verity_image_path,
273 "Could not append verity data!"):
Sami Tolvanenf99b5312015-05-20 07:30:57 +0100274 return False
Geremy Condrafd6f7512013-06-16 17:26:08 -0700275 return True
276
Geremy Condra6e8f53c2013-12-05 17:09:18 -0800277def UnsparseImage(sparse_image_path, replace=True):
Geremy Condrafd6f7512013-06-16 17:26:08 -0700278 img_dir = os.path.dirname(sparse_image_path)
279 unsparse_image_path = "unsparse_" + os.path.basename(sparse_image_path)
280 unsparse_image_path = os.path.join(img_dir, unsparse_image_path)
281 if os.path.exists(unsparse_image_path):
Geremy Condra6e8f53c2013-12-05 17:09:18 -0800282 if replace:
283 os.unlink(unsparse_image_path)
284 else:
285 return True, unsparse_image_path
Geremy Condrafd6f7512013-06-16 17:26:08 -0700286 inflate_command = ["simg2img", sparse_image_path, unsparse_image_path]
Tao Baoc7a6f1e2015-06-23 11:16:05 -0700287 (_, exit_code) = RunCommand(inflate_command)
Geremy Condrafd6f7512013-06-16 17:26:08 -0700288 if exit_code != 0:
289 os.remove(unsparse_image_path)
290 return False, None
291 return True, unsparse_image_path
292
Sami Tolvanenf99b5312015-05-20 07:30:57 +0100293def MakeVerityEnabledImage(out_file, fec_supported, prop_dict):
Geremy Condrafd6f7512013-06-16 17:26:08 -0700294 """Creates an image that is verifiable using dm-verity.
295
296 Args:
297 out_file: the location to write the verifiable image at
Dan Albert8b72aef2015-03-23 19:13:21 -0700298 prop_dict: a dictionary of properties required for image creation and
299 verification
Geremy Condrafd6f7512013-06-16 17:26:08 -0700300 Returns:
301 True on success, False otherwise.
302 """
303 # get properties
Sami Tolvanen433905f2016-09-01 15:58:35 -0700304 image_size = int(prop_dict["partition_size"])
Geremy Condrafd6f7512013-06-16 17:26:08 -0700305 block_dev = prop_dict["verity_block_device"]
Paul Lawrencea37b2bb2014-11-13 17:54:30 -0800306 signer_key = prop_dict["verity_key"] + ".pk8"
Baligh Uddin601ddea2015-06-09 15:48:14 -0700307 if OPTIONS.verity_signer_path is not None:
308 signer_path = OPTIONS.verity_signer_path + ' '
309 signer_path += ' '.join(OPTIONS.verity_signer_args)
310 else:
311 signer_path = prop_dict["verity_signer_cmd"]
Geremy Condrafd6f7512013-06-16 17:26:08 -0700312
313 # make a tempdir
Geremy Condra5b5f4952014-05-05 22:19:37 -0700314 tempdir_name = tempfile.mkdtemp(suffix="_verity_images")
Geremy Condrafd6f7512013-06-16 17:26:08 -0700315
316 # get partial image paths
317 verity_image_path = os.path.join(tempdir_name, "verity.img")
318 verity_metadata_path = os.path.join(tempdir_name, "verity_metadata.img")
Sami Tolvanenf99b5312015-05-20 07:30:57 +0100319 verity_fec_path = os.path.join(tempdir_name, "verity_fec.img")
Geremy Condrafd6f7512013-06-16 17:26:08 -0700320
321 # build the verity tree and get the root hash and salt
Colin Cross477cf2b2014-04-16 18:49:56 -0700322 if not BuildVerityTree(out_file, verity_image_path, prop_dict):
Geremy Condra5b5f4952014-05-05 22:19:37 -0700323 shutil.rmtree(tempdir_name, ignore_errors=True)
Geremy Condrafd6f7512013-06-16 17:26:08 -0700324 return False
325
326 # build the metadata blocks
327 root_hash = prop_dict["verity_root_hash"]
328 salt = prop_dict["verity_salt"]
Dan Albert8b72aef2015-03-23 19:13:21 -0700329 if not BuildVerityMetadata(image_size, verity_metadata_path, root_hash, salt,
330 block_dev, signer_path, signer_key):
Geremy Condra5b5f4952014-05-05 22:19:37 -0700331 shutil.rmtree(tempdir_name, ignore_errors=True)
Geremy Condrafd6f7512013-06-16 17:26:08 -0700332 return False
333
334 # build the full verified image
Sami Tolvanen433905f2016-09-01 15:58:35 -0700335 target_size = int(prop_dict["original_partition_size"])
336 verity_size = int(prop_dict["verity_size"])
337
338 padding_size = target_size - image_size - verity_size
339 assert padding_size >= 0
340
Geremy Condrafd6f7512013-06-16 17:26:08 -0700341 if not BuildVerifiedImage(out_file,
342 verity_image_path,
Sami Tolvanen4a060042015-12-18 15:50:25 +0000343 verity_metadata_path,
344 verity_fec_path,
Sami Tolvanen433905f2016-09-01 15:58:35 -0700345 padding_size,
Sami Tolvanen4a060042015-12-18 15:50:25 +0000346 fec_supported):
Geremy Condra5b5f4952014-05-05 22:19:37 -0700347 shutil.rmtree(tempdir_name, ignore_errors=True)
Geremy Condrafd6f7512013-06-16 17:26:08 -0700348 return False
349
Geremy Condra5b5f4952014-05-05 22:19:37 -0700350 shutil.rmtree(tempdir_name, ignore_errors=True)
Geremy Condrafd6f7512013-06-16 17:26:08 -0700351 return True
352
Mohamad Ayyashf8765552016-03-02 21:07:23 -0800353def ConvertBlockMapToBaseFs(block_map_file):
354 fd, base_fs_file = tempfile.mkstemp(prefix="script_gen_",
355 suffix=".base_fs")
356 os.close(fd)
357
358 convert_command = ["blk_alloc_to_base_fs", block_map_file, base_fs_file]
359 (_, exit_code) = RunCommand(convert_command)
360 if exit_code != 0:
361 os.remove(base_fs_file)
362 return None
363 return base_fs_file
364
Thierry Strudel74a81e62015-07-09 09:54:55 -0700365def BuildImage(in_dir, prop_dict, out_file, target_out=None):
Ying Wangbd93d422011-10-28 17:02:30 -0700366 """Build an image to out_file from in_dir with property prop_dict.
367
368 Args:
369 in_dir: path of input directory.
370 prop_dict: property dictionary.
371 out_file: path of the output image file.
Thierry Strudel74a81e62015-07-09 09:54:55 -0700372 target_out: path of the product out directory to read device specific FS config files.
Ying Wangbd93d422011-10-28 17:02:30 -0700373
374 Returns:
375 True iff the image is built successfully.
376 """
Tao Baof3282b42015-04-01 11:21:55 -0700377 # system_root_image=true: build a system.img that combines the contents of
378 # /system and the ramdisk, and can be mounted at the root of the file system.
Ying Wanga2292c92015-03-24 19:07:40 -0700379 origin_in = in_dir
380 fs_config = prop_dict.get("fs_config")
Mohamad Ayyashf8765552016-03-02 21:07:23 -0800381 base_fs_file = None
Ying Wanga2292c92015-03-24 19:07:40 -0700382 if (prop_dict.get("system_root_image") == "true"
383 and prop_dict["mount_point"] == "system"):
384 in_dir = tempfile.mkdtemp()
385 # Change the mount point to "/"
386 prop_dict["mount_point"] = "/"
387 if fs_config:
388 # We need to merge the fs_config files of system and ramdisk.
389 fd, merged_fs_config = tempfile.mkstemp(prefix="root_fs_config",
390 suffix=".txt")
391 os.close(fd)
392 with open(merged_fs_config, "w") as fw:
393 if "ramdisk_fs_config" in prop_dict:
394 with open(prop_dict["ramdisk_fs_config"]) as fr:
395 fw.writelines(fr.readlines())
396 with open(fs_config) as fr:
397 fw.writelines(fr.readlines())
398 fs_config = merged_fs_config
399
Ying Wangbd93d422011-10-28 17:02:30 -0700400 build_command = []
401 fs_type = prop_dict.get("fs_type", "")
Ying Wang69e9b4d2012-11-26 18:10:23 -0800402 run_fsck = False
Geremy Condrafd6f7512013-06-16 17:26:08 -0700403
Mohamad Ayyashdd063522015-03-24 12:42:03 -0700404 fs_spans_partition = True
405 if fs_type.startswith("squash"):
Tao Baoc7a6f1e2015-06-23 11:16:05 -0700406 fs_spans_partition = False
Mohamad Ayyashdd063522015-03-24 12:42:03 -0700407
Daniel Rosenbergf4eabc32014-07-10 15:42:38 -0700408 is_verity_partition = "verity_block_device" in prop_dict
Geremy Condra5b5f4952014-05-05 22:19:37 -0700409 verity_supported = prop_dict.get("verity") == "true"
Sami Tolvanenf99b5312015-05-20 07:30:57 +0100410 verity_fec_supported = prop_dict.get("verity_fec") == "true"
411
Tao Baoc7a6f1e2015-06-23 11:16:05 -0700412 # Adjust the partition size to make room for the hashes if this is to be
413 # verified.
Sami Tolvanen405e71d2016-02-09 12:28:58 -0800414 if verity_supported and is_verity_partition:
Geremy Condrafd6f7512013-06-16 17:26:08 -0700415 partition_size = int(prop_dict.get("partition_size"))
Sami Tolvanen433905f2016-09-01 15:58:35 -0700416 (adjusted_size, verity_size) = AdjustPartitionSizeForVerity(partition_size,
417 verity_fec_supported)
Geremy Condrafd6f7512013-06-16 17:26:08 -0700418 if not adjusted_size:
419 return False
420 prop_dict["partition_size"] = str(adjusted_size)
421 prop_dict["original_partition_size"] = str(partition_size)
Sami Tolvanen433905f2016-09-01 15:58:35 -0700422 prop_dict["verity_size"] = str(verity_size)
Geremy Condrafd6f7512013-06-16 17:26:08 -0700423
David Zeuthen4014a9d2016-09-30 17:29:22 -0400424 # Adjust partition size for AVB.
425 if prop_dict.get("avb_enable") == "true":
426 avbtool = prop_dict.get("avb_avbtool")
427 partition_size = int(prop_dict.get("partition_size"))
428 additional_args = prop_dict["avb_add_hashtree_footer_args"]
429 max_image_size = AVBCalcMaxImageSize(avbtool, partition_size,
430 additional_args)
431 if max_image_size == 0:
432 return False
433 prop_dict["partition_size"] = str(max_image_size)
434 prop_dict["original_partition_size"] = str(partition_size)
435
Ying Wangbd93d422011-10-28 17:02:30 -0700436 if fs_type.startswith("ext"):
437 build_command = ["mkuserimg.sh"]
438 if "extfs_sparse_flag" in prop_dict:
439 build_command.append(prop_dict["extfs_sparse_flag"])
Ying Wang69e9b4d2012-11-26 18:10:23 -0800440 run_fsck = True
Ying Wangbd93d422011-10-28 17:02:30 -0700441 build_command.extend([in_dir, out_file, fs_type,
442 prop_dict["mount_point"]])
Doug Zongker850b8072013-12-05 15:54:55 -0800443 build_command.append(prop_dict["partition_size"])
Ying Wangf3b86352014-11-18 18:03:13 -0800444 if "journal_size" in prop_dict:
445 build_command.extend(["-j", prop_dict["journal_size"]])
Doug Zongker850b8072013-12-05 15:54:55 -0800446 if "timestamp" in prop_dict:
447 build_command.extend(["-T", str(prop_dict["timestamp"])])
Ying Wanga2292c92015-03-24 19:07:40 -0700448 if fs_config:
Doug Zongker82822822014-06-16 09:10:55 -0700449 build_command.extend(["-C", fs_config])
Thierry Strudel74a81e62015-07-09 09:54:55 -0700450 if target_out:
451 build_command.extend(["-D", target_out])
Ying Wanga2292c92015-03-24 19:07:40 -0700452 if "block_list" in prop_dict:
453 build_command.extend(["-B", prop_dict["block_list"]])
Mohamad Ayyashf8765552016-03-02 21:07:23 -0800454 if "base_fs_file" in prop_dict:
455 base_fs_file = ConvertBlockMapToBaseFs(prop_dict["base_fs_file"])
456 if base_fs_file is None:
457 return False
458 build_command.extend(["-d", base_fs_file])
Christoffer Dall8ed01f32014-12-17 21:34:12 +0100459 build_command.extend(["-L", prop_dict["mount_point"]])
Ying Wanga2292c92015-03-24 19:07:40 -0700460 if "selinux_fc" in prop_dict:
Kenny Rootf32dc712012-04-08 10:42:34 -0700461 build_command.append(prop_dict["selinux_fc"])
Mohamad Ayyashb97746e2015-03-03 12:30:37 -0800462 elif fs_type.startswith("squash"):
463 build_command = ["mksquashfsimage.sh"]
464 build_command.extend([in_dir, out_file])
Todd Poynorb2a555e2015-12-15 18:00:14 -0800465 if "squashfs_sparse_flag" in prop_dict:
466 build_command.extend([prop_dict["squashfs_sparse_flag"]])
Mohamad Ayyashb97746e2015-03-03 12:30:37 -0800467 build_command.extend(["-m", prop_dict["mount_point"]])
Thierry Strudel74a81e62015-07-09 09:54:55 -0700468 if target_out:
469 build_command.extend(["-d", target_out])
Mohamad Ayyash88378822016-04-07 22:10:51 -0700470 if fs_config:
471 build_command.extend(["-C", fs_config])
Ying Wanga2292c92015-03-24 19:07:40 -0700472 if "selinux_fc" in prop_dict:
Mohamad Ayyashb97746e2015-03-03 12:30:37 -0800473 build_command.extend(["-c", prop_dict["selinux_fc"]])
Mohamad Ayyashc3484f72016-06-13 09:46:58 -0700474 if "block_list" in prop_dict:
475 build_command.extend(["-B", prop_dict["block_list"]])
Simon Wilsonf86e7ee2015-06-17 12:35:15 -0700476 if "squashfs_compressor" in prop_dict:
477 build_command.extend(["-z", prop_dict["squashfs_compressor"]])
478 if "squashfs_compressor_opt" in prop_dict:
479 build_command.extend(["-zo", prop_dict["squashfs_compressor_opt"]])
Mohamad Ayyashdfec8152016-05-24 12:59:30 -0700480 if "squashfs_block_size" in prop_dict:
481 build_command.extend(["-b", prop_dict["squashfs_block_size"]])
Mohamad Ayyash1b6d3482016-06-15 15:53:07 -0700482 if "squashfs_disable_4k_align" in prop_dict and prop_dict.get("squashfs_disable_4k_align") == "true":
483 build_command.extend(["-a"])
JP Abgrall5bfed5a2014-06-16 14:17:40 -0700484 elif fs_type.startswith("f2fs"):
485 build_command = ["mkf2fsuserimg.sh"]
486 build_command.extend([out_file, prop_dict["partition_size"]])
Ying Wangbd93d422011-10-28 17:02:30 -0700487 else:
Elliott Hughes305b0882016-06-15 17:04:54 -0700488 print("Error: unknown filesystem type '%s'" % (fs_type))
489 return False
Ying Wangbd93d422011-10-28 17:02:30 -0700490
Ying Wanga2292c92015-03-24 19:07:40 -0700491 if in_dir != origin_in:
492 # Construct a staging directory of the root file system.
493 ramdisk_dir = prop_dict.get("ramdisk_dir")
494 if ramdisk_dir:
495 shutil.rmtree(in_dir)
496 shutil.copytree(ramdisk_dir, in_dir, symlinks=True)
497 staging_system = os.path.join(in_dir, "system")
498 shutil.rmtree(staging_system, ignore_errors=True)
499 shutil.copytree(origin_in, staging_system, symlinks=True)
Tao Baoc7a6f1e2015-06-23 11:16:05 -0700500
501 reserved_blocks = prop_dict.get("has_ext4_reserved_blocks") == "true"
502 ext4fs_output = None
503
Ying Wanga2292c92015-03-24 19:07:40 -0700504 try:
Tao Baoc7a6f1e2015-06-23 11:16:05 -0700505 if reserved_blocks and fs_type.startswith("ext4"):
506 (ext4fs_output, exit_code) = RunCommand(build_command)
507 else:
508 (_, exit_code) = RunCommand(build_command)
Ying Wanga2292c92015-03-24 19:07:40 -0700509 finally:
510 if in_dir != origin_in:
511 # Clean up temporary directories and files.
512 shutil.rmtree(in_dir, ignore_errors=True)
513 if fs_config:
514 os.remove(fs_config)
Mohamad Ayyashf8765552016-03-02 21:07:23 -0800515 if base_fs_file is not None:
516 os.remove(base_fs_file)
Ying Wang69e9b4d2012-11-26 18:10:23 -0800517 if exit_code != 0:
518 return False
519
Tao Baoc7a6f1e2015-06-23 11:16:05 -0700520 # Bug: 21522719, 22023465
521 # There are some reserved blocks on ext4 FS (lesser of 4096 blocks and 2%).
522 # We need to deduct those blocks from the available space, since they are
523 # not writable even with root privilege. It only affects devices using
524 # file-based OTA and a kernel version of 3.10 or greater (currently just
525 # sprout).
526 if reserved_blocks and fs_type.startswith("ext4"):
527 assert ext4fs_output is not None
528 ext4fs_stats = re.compile(
529 r'Created filesystem with .* (?P<used_blocks>[0-9]+)/'
530 r'(?P<total_blocks>[0-9]+) blocks')
531 m = ext4fs_stats.match(ext4fs_output.strip().split('\n')[-1])
532 used_blocks = int(m.groupdict().get('used_blocks'))
533 total_blocks = int(m.groupdict().get('total_blocks'))
534 reserved_blocks = min(4096, int(total_blocks * 0.02))
535 adjusted_blocks = total_blocks - reserved_blocks
536 if used_blocks > adjusted_blocks:
537 mount_point = prop_dict.get("mount_point")
538 print("Error: Not enough room on %s (total: %d blocks, used: %d blocks, "
539 "reserved: %d blocks, available: %d blocks)" % (
540 mount_point, total_blocks, used_blocks, reserved_blocks,
541 adjusted_blocks))
542 return False
543
Mohamad Ayyashdd063522015-03-24 12:42:03 -0700544 if not fs_spans_partition:
545 mount_point = prop_dict.get("mount_point")
546 partition_size = int(prop_dict.get("partition_size"))
Sami Tolvanen405e71d2016-02-09 12:28:58 -0800547 image_size = GetSimgSize(out_file)
Mohamad Ayyashdd063522015-03-24 12:42:03 -0700548 if image_size > partition_size:
Tao Baoc7a6f1e2015-06-23 11:16:05 -0700549 print("Error: %s image size of %d is larger than partition size of "
550 "%d" % (mount_point, image_size, partition_size))
551 return False
Mohamad Ayyashdd063522015-03-24 12:42:03 -0700552 if verity_supported and is_verity_partition:
Sami Tolvanen405e71d2016-02-09 12:28:58 -0800553 ZeroPadSimg(out_file, partition_size - image_size)
Mohamad Ayyashdd063522015-03-24 12:42:03 -0700554
Geremy Condrafd6f7512013-06-16 17:26:08 -0700555 # create the verified image if this is to be verified
Geremy Condra5b5f4952014-05-05 22:19:37 -0700556 if verity_supported and is_verity_partition:
Sami Tolvanenf99b5312015-05-20 07:30:57 +0100557 if not MakeVerityEnabledImage(out_file, verity_fec_supported, prop_dict):
Geremy Condrafd6f7512013-06-16 17:26:08 -0700558 return False
559
David Zeuthen4014a9d2016-09-30 17:29:22 -0400560 # Add AVB hashtree and metadata.
561 if "avb_enable" in prop_dict:
562 avbtool = prop_dict.get("avb_avbtool")
563 original_partition_size = int(prop_dict.get("original_partition_size"))
564 partition_name = prop_dict["partition_name"]
565 signing_args = prop_dict["avb_signing_args"]
566 additional_args = prop_dict["avb_add_hashtree_footer_args"]
567 if not AVBAddHashtree(out_file, avbtool, original_partition_size,
568 partition_name, signing_args, additional_args):
569 return False
570
Ying Wang6a42a252013-02-27 13:54:02 -0800571 if run_fsck and prop_dict.get("skip_fsck") != "true":
Geremy Condra6e8f53c2013-12-05 17:09:18 -0800572 success, unsparse_image = UnsparseImage(out_file, replace=False)
Geremy Condrafd6f7512013-06-16 17:26:08 -0700573 if not success:
Ying Wang69e9b4d2012-11-26 18:10:23 -0800574 return False
575
576 # Run e2fsck on the inflated image file
577 e2fsck_command = ["e2fsck", "-f", "-n", unsparse_image]
Tao Baoc7a6f1e2015-06-23 11:16:05 -0700578 (_, exit_code) = RunCommand(e2fsck_command)
Ying Wang69e9b4d2012-11-26 18:10:23 -0800579
580 os.remove(unsparse_image)
581
582 return exit_code == 0
Ying Wangbd93d422011-10-28 17:02:30 -0700583
584
585def ImagePropFromGlobalDict(glob_dict, mount_point):
586 """Build an image property dictionary from the global dictionary.
587
588 Args:
589 glob_dict: the global dictionary from the build system.
590 mount_point: such as "system", "data" etc.
591 """
Doug Zongker1ad7ade2013-12-06 11:53:27 -0800592 d = {}
Tao Bao052ae352015-09-28 13:44:13 -0700593
Tao Bao822f5842015-09-30 16:01:14 -0700594 if "build.prop" in glob_dict:
595 bp = glob_dict["build.prop"]
596 if "ro.build.date.utc" in bp:
597 d["timestamp"] = bp["ro.build.date.utc"]
Ying Wang9f8e8db2011-11-04 11:37:01 -0700598
599 def copy_prop(src_p, dest_p):
600 if src_p in glob_dict:
601 d[dest_p] = str(glob_dict[src_p])
602
Ying Wangbd93d422011-10-28 17:02:30 -0700603 common_props = (
Ying Wangbd93d422011-10-28 17:02:30 -0700604 "extfs_sparse_flag",
Todd Poynorb2a555e2015-12-15 18:00:14 -0800605 "squashfs_sparse_flag",
Kenny Rootf32dc712012-04-08 10:42:34 -0700606 "selinux_fc",
Ying Wang6a42a252013-02-27 13:54:02 -0800607 "skip_fsck",
Geremy Condrafd6f7512013-06-16 17:26:08 -0700608 "verity",
Geremy Condrafd6f7512013-06-16 17:26:08 -0700609 "verity_key",
Sami Tolvanenf99b5312015-05-20 07:30:57 +0100610 "verity_signer_cmd",
David Zeuthen4014a9d2016-09-30 17:29:22 -0400611 "verity_fec",
612 "avb_signing_args",
613 "avb_avbtool"
Ying Wangbd93d422011-10-28 17:02:30 -0700614 )
615 for p in common_props:
Ying Wang9f8e8db2011-11-04 11:37:01 -0700616 copy_prop(p, p)
Ying Wangbd93d422011-10-28 17:02:30 -0700617
618 d["mount_point"] = mount_point
619 if mount_point == "system":
Ying Wang9f8e8db2011-11-04 11:37:01 -0700620 copy_prop("fs_type", "fs_type")
Dan Albert8b72aef2015-03-23 19:13:21 -0700621 # Copy the generic sysetem fs type first, override with specific one if
622 # available.
Mohamad Ayyashb97746e2015-03-03 12:30:37 -0800623 copy_prop("system_fs_type", "fs_type")
Ying Wang9f8e8db2011-11-04 11:37:01 -0700624 copy_prop("system_size", "partition_size")
Ying Wangf3b86352014-11-18 18:03:13 -0800625 copy_prop("system_journal_size", "journal_size")
Daniel Rosenbergf4eabc32014-07-10 15:42:38 -0700626 copy_prop("system_verity_block_device", "verity_block_device")
Tao Baof3282b42015-04-01 11:21:55 -0700627 copy_prop("system_root_image", "system_root_image")
628 copy_prop("ramdisk_dir", "ramdisk_dir")
Tao Bao84e75682015-07-19 02:38:53 -0700629 copy_prop("ramdisk_fs_config", "ramdisk_fs_config")
Tao Baoc7a6f1e2015-06-23 11:16:05 -0700630 copy_prop("has_ext4_reserved_blocks", "has_ext4_reserved_blocks")
Simon Wilsonf86e7ee2015-06-17 12:35:15 -0700631 copy_prop("system_squashfs_compressor", "squashfs_compressor")
632 copy_prop("system_squashfs_compressor_opt", "squashfs_compressor_opt")
Mohamad Ayyashdfec8152016-05-24 12:59:30 -0700633 copy_prop("system_squashfs_block_size", "squashfs_block_size")
Mohamad Ayyash1b6d3482016-06-15 15:53:07 -0700634 copy_prop("system_squashfs_disable_4k_align", "squashfs_disable_4k_align")
Mohamad Ayyashf8765552016-03-02 21:07:23 -0800635 copy_prop("system_base_fs_file", "base_fs_file")
David Zeuthen4014a9d2016-09-30 17:29:22 -0400636 copy_prop("system_avb_enable", "avb_enable")
637 copy_prop("system_avb_add_hashtree_footer_args",
638 "avb_add_hashtree_footer_args")
Alex Light4e358ab2016-06-16 14:47:10 -0700639 elif mount_point == "system_other":
640 # We inherit the selinux policies of /system since we contain some of its files.
641 d["mount_point"] = "system"
642 copy_prop("fs_type", "fs_type")
643 copy_prop("system_fs_type", "fs_type")
644 copy_prop("system_size", "partition_size")
645 copy_prop("system_journal_size", "journal_size")
646 copy_prop("system_verity_block_device", "verity_block_device")
647 copy_prop("has_ext4_reserved_blocks", "has_ext4_reserved_blocks")
648 copy_prop("system_squashfs_compressor", "squashfs_compressor")
649 copy_prop("system_squashfs_compressor_opt", "squashfs_compressor_opt")
650 copy_prop("system_squashfs_block_size", "squashfs_block_size")
651 copy_prop("system_base_fs_file", "base_fs_file")
David Zeuthen4e9c89a2016-10-04 18:53:34 -0400652 copy_prop("system_avb_enable", "avb_enable")
653 copy_prop("system_avb_add_hashtree_footer_args",
654 "avb_add_hashtree_footer_args")
Ying Wangbd93d422011-10-28 17:02:30 -0700655 elif mount_point == "data":
JP Abgrall5bfed5a2014-06-16 14:17:40 -0700656 # Copy the generic fs type first, override with specific one if available.
Ying Wang9f8e8db2011-11-04 11:37:01 -0700657 copy_prop("fs_type", "fs_type")
JP Abgrall5bfed5a2014-06-16 14:17:40 -0700658 copy_prop("userdata_fs_type", "fs_type")
Ying Wang9f8e8db2011-11-04 11:37:01 -0700659 copy_prop("userdata_size", "partition_size")
660 elif mount_point == "cache":
661 copy_prop("cache_fs_type", "fs_type")
662 copy_prop("cache_size", "partition_size")
Ying Wanga0febe52013-03-20 11:02:05 -0700663 elif mount_point == "vendor":
664 copy_prop("vendor_fs_type", "fs_type")
665 copy_prop("vendor_size", "partition_size")
Ying Wangf3b86352014-11-18 18:03:13 -0800666 copy_prop("vendor_journal_size", "journal_size")
Daniel Rosenbergf4eabc32014-07-10 15:42:38 -0700667 copy_prop("vendor_verity_block_device", "verity_block_device")
Tao Baoc7a6f1e2015-06-23 11:16:05 -0700668 copy_prop("has_ext4_reserved_blocks", "has_ext4_reserved_blocks")
Patrick Tjine11aa502016-02-09 15:40:38 -0800669 copy_prop("vendor_squashfs_compressor", "squashfs_compressor")
670 copy_prop("vendor_squashfs_compressor_opt", "squashfs_compressor_opt")
Mohamad Ayyashdfec8152016-05-24 12:59:30 -0700671 copy_prop("vendor_squashfs_block_size", "squashfs_block_size")
Mohamad Ayyash1b6d3482016-06-15 15:53:07 -0700672 copy_prop("vendor_squashfs_disable_4k_align", "squashfs_disable_4k_align")
Mohamad Ayyashf8765552016-03-02 21:07:23 -0800673 copy_prop("vendor_base_fs_file", "base_fs_file")
David Zeuthen4014a9d2016-09-30 17:29:22 -0400674 copy_prop("vendor_avb_enable", "avb_enable")
675 copy_prop("vendor_avb_add_hashtree_footer_args",
676 "avb_add_hashtree_footer_args")
Ying Wangb8888432014-03-11 17:13:27 -0700677 elif mount_point == "oem":
678 copy_prop("fs_type", "fs_type")
679 copy_prop("oem_size", "partition_size")
Ying Wangf3b86352014-11-18 18:03:13 -0800680 copy_prop("oem_journal_size", "journal_size")
Tao Baoc7a6f1e2015-06-23 11:16:05 -0700681 copy_prop("has_ext4_reserved_blocks", "has_ext4_reserved_blocks")
David Zeuthen4014a9d2016-09-30 17:29:22 -0400682 d["partition_name"] = mount_point
Ying Wangbd93d422011-10-28 17:02:30 -0700683 return d
684
685
686def LoadGlobalDict(filename):
687 """Load "name=value" pairs from filename"""
688 d = {}
689 f = open(filename)
690 for line in f:
691 line = line.strip()
692 if not line or line.startswith("#"):
693 continue
694 k, v = line.split("=", 1)
695 d[k] = v
696 f.close()
697 return d
698
699
700def main(argv):
Thierry Strudel74a81e62015-07-09 09:54:55 -0700701 if len(argv) != 4:
Ying Wangbd93d422011-10-28 17:02:30 -0700702 print __doc__
703 sys.exit(1)
704
705 in_dir = argv[0]
706 glob_dict_file = argv[1]
707 out_file = argv[2]
Thierry Strudel74a81e62015-07-09 09:54:55 -0700708 target_out = argv[3]
Ying Wangbd93d422011-10-28 17:02:30 -0700709
710 glob_dict = LoadGlobalDict(glob_dict_file)
Ying Wangae61f502015-03-12 18:30:39 -0700711 if "mount_point" in glob_dict:
Tao Baoc7a6f1e2015-06-23 11:16:05 -0700712 # The caller knows the mount point and provides a dictionay needed by
713 # BuildImage().
Ying Wangae61f502015-03-12 18:30:39 -0700714 image_properties = glob_dict
Ying Wang9f8e8db2011-11-04 11:37:01 -0700715 else:
Ying Wangae61f502015-03-12 18:30:39 -0700716 image_filename = os.path.basename(out_file)
717 mount_point = ""
718 if image_filename == "system.img":
719 mount_point = "system"
Alex Light4e358ab2016-06-16 14:47:10 -0700720 elif image_filename == "system_other.img":
721 mount_point = "system_other"
Ying Wangae61f502015-03-12 18:30:39 -0700722 elif image_filename == "userdata.img":
723 mount_point = "data"
724 elif image_filename == "cache.img":
725 mount_point = "cache"
726 elif image_filename == "vendor.img":
727 mount_point = "vendor"
728 elif image_filename == "oem.img":
729 mount_point = "oem"
730 else:
731 print >> sys.stderr, "error: unknown image file name ", image_filename
732 exit(1)
Ying Wangbd93d422011-10-28 17:02:30 -0700733
Ying Wangae61f502015-03-12 18:30:39 -0700734 image_properties = ImagePropFromGlobalDict(glob_dict, mount_point)
735
Thierry Strudel74a81e62015-07-09 09:54:55 -0700736 if not BuildImage(in_dir, image_properties, out_file, target_out):
Dan Albert8b72aef2015-03-23 19:13:21 -0700737 print >> sys.stderr, "error: failed to build %s from %s" % (out_file,
738 in_dir)
Ying Wangbd93d422011-10-28 17:02:30 -0700739 exit(1)
740
741
742if __name__ == '__main__':
743 main(sys.argv[1:])