build_image.py revision f99b53143d3a25bf157ac32a8fe80378ab57d7a8
1#!/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""" 18Build image output_image_file from input_directory and properties_file. 19 20Usage: build_image input_directory properties_file output_image_file 21 22""" 23import os 24import os.path 25import re 26import subprocess 27import sys 28import commands 29import common 30import shutil 31import tempfile 32 33OPTIONS = common.OPTIONS 34 35FIXED_SALT = "aee087a5be3b982978c923f566a94613496b417f2af592639bc80d141e34dfe7" 36BLOCK_SIZE = 4096 37 38def RunCommand(cmd): 39 """Echo and run the given command. 40 41 Args: 42 cmd: the command represented as a list of strings. 43 Returns: 44 A tuple of the output and the exit code. 45 """ 46 print "Running: ", " ".join(cmd) 47 p = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.STDOUT) 48 output, _ = p.communicate() 49 print "%s" % (output.rstrip(),) 50 return (output, p.returncode) 51 52def GetVerityFECSize(partition_size): 53 cmd = "fec -s %d" % partition_size 54 status, output = commands.getstatusoutput(cmd) 55 if status: 56 print output 57 return False, 0 58 return True, int(output) 59 60def GetVerityTreeSize(partition_size): 61 cmd = "build_verity_tree -s %d" 62 cmd %= partition_size 63 status, output = commands.getstatusoutput(cmd) 64 if status: 65 print output 66 return False, 0 67 return True, int(output) 68 69def GetVerityMetadataSize(partition_size): 70 cmd = "system/extras/verity/build_verity_metadata.py -s %d" 71 cmd %= partition_size 72 73 status, output = commands.getstatusoutput(cmd) 74 if status: 75 print output 76 return False, 0 77 return True, int(output) 78 79def GetVeritySize(partition_size, fec_supported): 80 success, verity_tree_size = GetVerityTreeSize(partition_size) 81 if not success: 82 return 0 83 success, verity_metadata_size = GetVerityMetadataSize(partition_size) 84 if not success: 85 return 0 86 verity_size = verity_tree_size + verity_metadata_size 87 if fec_supported: 88 success, fec_size = GetVerityFECSize(partition_size + verity_size) 89 if not success: 90 return 0 91 return verity_size + fec_size 92 return verity_size 93 94def AdjustPartitionSizeForVerity(partition_size, fec_supported): 95 """Modifies the provided partition size to account for the verity metadata. 96 97 This information is used to size the created image appropriately. 98 Args: 99 partition_size: the size of the partition to be verified. 100 Returns: 101 The size of the partition adjusted for verity metadata. 102 """ 103 key = "%d %d" % (partition_size, fec_supported) 104 if key in AdjustPartitionSizeForVerity.results: 105 return AdjustPartitionSizeForVerity.results[key] 106 107 hi = partition_size 108 if hi % BLOCK_SIZE != 0: 109 hi = (hi // BLOCK_SIZE) * BLOCK_SIZE 110 111 # verity tree and fec sizes depend on the partition size, which 112 # means this estimate is always going to be unnecessarily small 113 lo = partition_size - GetVeritySize(hi, fec_supported) 114 result = lo 115 116 # do a binary search for the optimal size 117 while lo < hi: 118 i = ((lo + hi) // (2 * BLOCK_SIZE)) * BLOCK_SIZE 119 size = i + GetVeritySize(i, fec_supported) 120 if size <= partition_size: 121 if result < i: 122 result = i 123 lo = i + BLOCK_SIZE 124 else: 125 hi = i 126 127 AdjustPartitionSizeForVerity.results[key] = result 128 return result 129 130AdjustPartitionSizeForVerity.results = {} 131 132def BuildVerityFEC(sparse_image_path, verity_fec_path, prop_dict): 133 cmd = "fec -e %s %s" % (sparse_image_path, verity_fec_path) 134 print cmd 135 status, output = commands.getstatusoutput(cmd) 136 if status: 137 print "Could not build FEC data! Error: %s" % output 138 return False 139 return True 140 141def BuildVerityTree(sparse_image_path, verity_image_path, prop_dict): 142 cmd = "build_verity_tree -A %s %s %s" % ( 143 FIXED_SALT, sparse_image_path, verity_image_path) 144 print cmd 145 status, output = commands.getstatusoutput(cmd) 146 if status: 147 print "Could not build verity tree! Error: %s" % output 148 return False 149 root, salt = output.split() 150 prop_dict["verity_root_hash"] = root 151 prop_dict["verity_salt"] = salt 152 return True 153 154def BuildVerityMetadata(image_size, verity_metadata_path, root_hash, salt, 155 block_device, signer_path, key): 156 cmd_template = ( 157 "system/extras/verity/build_verity_metadata.py %s %s %s %s %s %s %s") 158 cmd = cmd_template % (image_size, verity_metadata_path, root_hash, salt, 159 block_device, signer_path, key) 160 print cmd 161 status, output = commands.getstatusoutput(cmd) 162 if status: 163 print "Could not build verity metadata! Error: %s" % output 164 return False 165 return True 166 167def Append2Simg(sparse_image_path, unsparse_image_path, error_message): 168 """Appends the unsparse image to the given sparse image. 169 170 Args: 171 sparse_image_path: the path to the (sparse) image 172 unsparse_image_path: the path to the (unsparse) image 173 Returns: 174 True on success, False on failure. 175 """ 176 cmd = "append2simg %s %s" 177 cmd %= (sparse_image_path, unsparse_image_path) 178 print cmd 179 status, output = commands.getstatusoutput(cmd) 180 if status: 181 print "%s: %s" % (error_message, output) 182 return False 183 return True 184 185def BuildVerifiedImage(data_image_path, verity_image_path, 186 verity_metadata_path): 187 if not Append2Simg(data_image_path, verity_image_path, 188 "Could not append verity tree!"): 189 return False 190 if not Append2Simg(data_image_path, verity_metadata_path, 191 "Could not append verity metadata!"): 192 return False 193 return True 194 195def UnsparseImage(sparse_image_path, replace=True): 196 img_dir = os.path.dirname(sparse_image_path) 197 unsparse_image_path = "unsparse_" + os.path.basename(sparse_image_path) 198 unsparse_image_path = os.path.join(img_dir, unsparse_image_path) 199 if os.path.exists(unsparse_image_path): 200 if replace: 201 os.unlink(unsparse_image_path) 202 else: 203 return True, unsparse_image_path 204 inflate_command = ["simg2img", sparse_image_path, unsparse_image_path] 205 (_, exit_code) = RunCommand(inflate_command) 206 if exit_code != 0: 207 os.remove(unsparse_image_path) 208 return False, None 209 return True, unsparse_image_path 210 211def MakeVerityEnabledImage(out_file, fec_supported, prop_dict): 212 """Creates an image that is verifiable using dm-verity. 213 214 Args: 215 out_file: the location to write the verifiable image at 216 prop_dict: a dictionary of properties required for image creation and 217 verification 218 Returns: 219 True on success, False otherwise. 220 """ 221 # get properties 222 image_size = prop_dict["partition_size"] 223 block_dev = prop_dict["verity_block_device"] 224 signer_key = prop_dict["verity_key"] + ".pk8" 225 if OPTIONS.verity_signer_path is not None: 226 signer_path = OPTIONS.verity_signer_path + ' ' 227 signer_path += ' '.join(OPTIONS.verity_signer_args) 228 else: 229 signer_path = prop_dict["verity_signer_cmd"] 230 231 # make a tempdir 232 tempdir_name = tempfile.mkdtemp(suffix="_verity_images") 233 234 # get partial image paths 235 verity_image_path = os.path.join(tempdir_name, "verity.img") 236 verity_metadata_path = os.path.join(tempdir_name, "verity_metadata.img") 237 verity_fec_path = os.path.join(tempdir_name, "verity_fec.img") 238 239 # build the verity tree and get the root hash and salt 240 if not BuildVerityTree(out_file, verity_image_path, prop_dict): 241 shutil.rmtree(tempdir_name, ignore_errors=True) 242 return False 243 244 # build the metadata blocks 245 root_hash = prop_dict["verity_root_hash"] 246 salt = prop_dict["verity_salt"] 247 if not BuildVerityMetadata(image_size, verity_metadata_path, root_hash, salt, 248 block_dev, signer_path, signer_key): 249 shutil.rmtree(tempdir_name, ignore_errors=True) 250 return False 251 252 # build the full verified image 253 if not BuildVerifiedImage(out_file, 254 verity_image_path, 255 verity_metadata_path): 256 shutil.rmtree(tempdir_name, ignore_errors=True) 257 return False 258 259 if fec_supported: 260 # build FEC for the entire partition, including metadata 261 if not BuildVerityFEC(out_file, verity_fec_path, prop_dict): 262 shutil.rmtree(tempdir_name, ignore_errors=True) 263 return False 264 265 if not Append2Simg(out_file, verity_fec_path, "Could not append FEC!"): 266 shutil.rmtree(tempdir_name, ignore_errors=True) 267 return False 268 269 shutil.rmtree(tempdir_name, ignore_errors=True) 270 return True 271 272def BuildImage(in_dir, prop_dict, out_file, target_out=None): 273 """Build an image to out_file from in_dir with property prop_dict. 274 275 Args: 276 in_dir: path of input directory. 277 prop_dict: property dictionary. 278 out_file: path of the output image file. 279 target_out: path of the product out directory to read device specific FS config files. 280 281 Returns: 282 True iff the image is built successfully. 283 """ 284 # system_root_image=true: build a system.img that combines the contents of 285 # /system and the ramdisk, and can be mounted at the root of the file system. 286 origin_in = in_dir 287 fs_config = prop_dict.get("fs_config") 288 if (prop_dict.get("system_root_image") == "true" 289 and prop_dict["mount_point"] == "system"): 290 in_dir = tempfile.mkdtemp() 291 # Change the mount point to "/" 292 prop_dict["mount_point"] = "/" 293 if fs_config: 294 # We need to merge the fs_config files of system and ramdisk. 295 fd, merged_fs_config = tempfile.mkstemp(prefix="root_fs_config", 296 suffix=".txt") 297 os.close(fd) 298 with open(merged_fs_config, "w") as fw: 299 if "ramdisk_fs_config" in prop_dict: 300 with open(prop_dict["ramdisk_fs_config"]) as fr: 301 fw.writelines(fr.readlines()) 302 with open(fs_config) as fr: 303 fw.writelines(fr.readlines()) 304 fs_config = merged_fs_config 305 306 build_command = [] 307 fs_type = prop_dict.get("fs_type", "") 308 run_fsck = False 309 310 fs_spans_partition = True 311 if fs_type.startswith("squash"): 312 fs_spans_partition = False 313 314 is_verity_partition = "verity_block_device" in prop_dict 315 verity_supported = prop_dict.get("verity") == "true" 316 verity_fec_supported = prop_dict.get("verity_fec") == "true" 317 318 # Adjust the partition size to make room for the hashes if this is to be 319 # verified. 320 if verity_supported and is_verity_partition and fs_spans_partition: 321 partition_size = int(prop_dict.get("partition_size")) 322 adjusted_size = AdjustPartitionSizeForVerity(partition_size, 323 verity_fec_supported) 324 if not adjusted_size: 325 return False 326 prop_dict["partition_size"] = str(adjusted_size) 327 prop_dict["original_partition_size"] = str(partition_size) 328 329 if fs_type.startswith("ext"): 330 build_command = ["mkuserimg.sh"] 331 if "extfs_sparse_flag" in prop_dict: 332 build_command.append(prop_dict["extfs_sparse_flag"]) 333 run_fsck = True 334 build_command.extend([in_dir, out_file, fs_type, 335 prop_dict["mount_point"]]) 336 build_command.append(prop_dict["partition_size"]) 337 if "journal_size" in prop_dict: 338 build_command.extend(["-j", prop_dict["journal_size"]]) 339 if "timestamp" in prop_dict: 340 build_command.extend(["-T", str(prop_dict["timestamp"])]) 341 if fs_config: 342 build_command.extend(["-C", fs_config]) 343 if target_out: 344 build_command.extend(["-D", target_out]) 345 if "block_list" in prop_dict: 346 build_command.extend(["-B", prop_dict["block_list"]]) 347 build_command.extend(["-L", prop_dict["mount_point"]]) 348 if "selinux_fc" in prop_dict: 349 build_command.append(prop_dict["selinux_fc"]) 350 elif fs_type.startswith("squash"): 351 build_command = ["mksquashfsimage.sh"] 352 build_command.extend([in_dir, out_file]) 353 build_command.extend(["-s"]) 354 build_command.extend(["-m", prop_dict["mount_point"]]) 355 if target_out: 356 build_command.extend(["-d", target_out]) 357 if "selinux_fc" in prop_dict: 358 build_command.extend(["-c", prop_dict["selinux_fc"]]) 359 if "squashfs_compressor" in prop_dict: 360 build_command.extend(["-z", prop_dict["squashfs_compressor"]]) 361 if "squashfs_compressor_opt" in prop_dict: 362 build_command.extend(["-zo", prop_dict["squashfs_compressor_opt"]]) 363 elif fs_type.startswith("f2fs"): 364 build_command = ["mkf2fsuserimg.sh"] 365 build_command.extend([out_file, prop_dict["partition_size"]]) 366 else: 367 build_command = ["mkyaffs2image", "-f"] 368 if prop_dict.get("mkyaffs2_extra_flags", None): 369 build_command.extend(prop_dict["mkyaffs2_extra_flags"].split()) 370 build_command.append(in_dir) 371 build_command.append(out_file) 372 if "selinux_fc" in prop_dict: 373 build_command.append(prop_dict["selinux_fc"]) 374 build_command.append(prop_dict["mount_point"]) 375 376 if in_dir != origin_in: 377 # Construct a staging directory of the root file system. 378 ramdisk_dir = prop_dict.get("ramdisk_dir") 379 if ramdisk_dir: 380 shutil.rmtree(in_dir) 381 shutil.copytree(ramdisk_dir, in_dir, symlinks=True) 382 staging_system = os.path.join(in_dir, "system") 383 shutil.rmtree(staging_system, ignore_errors=True) 384 shutil.copytree(origin_in, staging_system, symlinks=True) 385 386 reserved_blocks = prop_dict.get("has_ext4_reserved_blocks") == "true" 387 ext4fs_output = None 388 389 try: 390 if reserved_blocks and fs_type.startswith("ext4"): 391 (ext4fs_output, exit_code) = RunCommand(build_command) 392 else: 393 (_, exit_code) = RunCommand(build_command) 394 finally: 395 if in_dir != origin_in: 396 # Clean up temporary directories and files. 397 shutil.rmtree(in_dir, ignore_errors=True) 398 if fs_config: 399 os.remove(fs_config) 400 if exit_code != 0: 401 return False 402 403 # Bug: 21522719, 22023465 404 # There are some reserved blocks on ext4 FS (lesser of 4096 blocks and 2%). 405 # We need to deduct those blocks from the available space, since they are 406 # not writable even with root privilege. It only affects devices using 407 # file-based OTA and a kernel version of 3.10 or greater (currently just 408 # sprout). 409 if reserved_blocks and fs_type.startswith("ext4"): 410 assert ext4fs_output is not None 411 ext4fs_stats = re.compile( 412 r'Created filesystem with .* (?P<used_blocks>[0-9]+)/' 413 r'(?P<total_blocks>[0-9]+) blocks') 414 m = ext4fs_stats.match(ext4fs_output.strip().split('\n')[-1]) 415 used_blocks = int(m.groupdict().get('used_blocks')) 416 total_blocks = int(m.groupdict().get('total_blocks')) 417 reserved_blocks = min(4096, int(total_blocks * 0.02)) 418 adjusted_blocks = total_blocks - reserved_blocks 419 if used_blocks > adjusted_blocks: 420 mount_point = prop_dict.get("mount_point") 421 print("Error: Not enough room on %s (total: %d blocks, used: %d blocks, " 422 "reserved: %d blocks, available: %d blocks)" % ( 423 mount_point, total_blocks, used_blocks, reserved_blocks, 424 adjusted_blocks)) 425 return False 426 427 if not fs_spans_partition: 428 mount_point = prop_dict.get("mount_point") 429 partition_size = int(prop_dict.get("partition_size")) 430 image_size = os.stat(out_file).st_size 431 if image_size > partition_size: 432 print("Error: %s image size of %d is larger than partition size of " 433 "%d" % (mount_point, image_size, partition_size)) 434 return False 435 if verity_supported and is_verity_partition: 436 if 2 * image_size - AdjustPartitionSizeForVerity(image_size, verity_fec_supported) > partition_size: 437 print "Error: No more room on %s to fit verity data" % mount_point 438 return False 439 prop_dict["original_partition_size"] = prop_dict["partition_size"] 440 prop_dict["partition_size"] = str(image_size) 441 442 # create the verified image if this is to be verified 443 if verity_supported and is_verity_partition: 444 if not MakeVerityEnabledImage(out_file, verity_fec_supported, prop_dict): 445 return False 446 447 if run_fsck and prop_dict.get("skip_fsck") != "true": 448 success, unsparse_image = UnsparseImage(out_file, replace=False) 449 if not success: 450 return False 451 452 # Run e2fsck on the inflated image file 453 e2fsck_command = ["e2fsck", "-f", "-n", unsparse_image] 454 (_, exit_code) = RunCommand(e2fsck_command) 455 456 os.remove(unsparse_image) 457 458 return exit_code == 0 459 460 461def ImagePropFromGlobalDict(glob_dict, mount_point): 462 """Build an image property dictionary from the global dictionary. 463 464 Args: 465 glob_dict: the global dictionary from the build system. 466 mount_point: such as "system", "data" etc. 467 """ 468 d = {} 469 470 if "build.prop" in glob_dict: 471 bp = glob_dict["build.prop"] 472 if "ro.build.date.utc" in bp: 473 d["timestamp"] = bp["ro.build.date.utc"] 474 475 def copy_prop(src_p, dest_p): 476 if src_p in glob_dict: 477 d[dest_p] = str(glob_dict[src_p]) 478 479 common_props = ( 480 "extfs_sparse_flag", 481 "mkyaffs2_extra_flags", 482 "selinux_fc", 483 "skip_fsck", 484 "verity", 485 "verity_key", 486 "verity_signer_cmd", 487 "verity_fec" 488 ) 489 for p in common_props: 490 copy_prop(p, p) 491 492 d["mount_point"] = mount_point 493 if mount_point == "system": 494 copy_prop("fs_type", "fs_type") 495 # Copy the generic sysetem fs type first, override with specific one if 496 # available. 497 copy_prop("system_fs_type", "fs_type") 498 copy_prop("system_size", "partition_size") 499 copy_prop("system_journal_size", "journal_size") 500 copy_prop("system_verity_block_device", "verity_block_device") 501 copy_prop("system_root_image", "system_root_image") 502 copy_prop("ramdisk_dir", "ramdisk_dir") 503 copy_prop("ramdisk_fs_config", "ramdisk_fs_config") 504 copy_prop("has_ext4_reserved_blocks", "has_ext4_reserved_blocks") 505 copy_prop("system_squashfs_compressor", "squashfs_compressor") 506 copy_prop("system_squashfs_compressor_opt", "squashfs_compressor_opt") 507 elif mount_point == "data": 508 # Copy the generic fs type first, override with specific one if available. 509 copy_prop("fs_type", "fs_type") 510 copy_prop("userdata_fs_type", "fs_type") 511 copy_prop("userdata_size", "partition_size") 512 elif mount_point == "cache": 513 copy_prop("cache_fs_type", "fs_type") 514 copy_prop("cache_size", "partition_size") 515 elif mount_point == "vendor": 516 copy_prop("vendor_fs_type", "fs_type") 517 copy_prop("vendor_size", "partition_size") 518 copy_prop("vendor_journal_size", "journal_size") 519 copy_prop("vendor_verity_block_device", "verity_block_device") 520 copy_prop("has_ext4_reserved_blocks", "has_ext4_reserved_blocks") 521 elif mount_point == "oem": 522 copy_prop("fs_type", "fs_type") 523 copy_prop("oem_size", "partition_size") 524 copy_prop("oem_journal_size", "journal_size") 525 copy_prop("has_ext4_reserved_blocks", "has_ext4_reserved_blocks") 526 527 return d 528 529 530def LoadGlobalDict(filename): 531 """Load "name=value" pairs from filename""" 532 d = {} 533 f = open(filename) 534 for line in f: 535 line = line.strip() 536 if not line or line.startswith("#"): 537 continue 538 k, v = line.split("=", 1) 539 d[k] = v 540 f.close() 541 return d 542 543 544def main(argv): 545 if len(argv) != 4: 546 print __doc__ 547 sys.exit(1) 548 549 in_dir = argv[0] 550 glob_dict_file = argv[1] 551 out_file = argv[2] 552 target_out = argv[3] 553 554 glob_dict = LoadGlobalDict(glob_dict_file) 555 if "mount_point" in glob_dict: 556 # The caller knows the mount point and provides a dictionay needed by 557 # BuildImage(). 558 image_properties = glob_dict 559 else: 560 image_filename = os.path.basename(out_file) 561 mount_point = "" 562 if image_filename == "system.img": 563 mount_point = "system" 564 elif image_filename == "userdata.img": 565 mount_point = "data" 566 elif image_filename == "cache.img": 567 mount_point = "cache" 568 elif image_filename == "vendor.img": 569 mount_point = "vendor" 570 elif image_filename == "oem.img": 571 mount_point = "oem" 572 else: 573 print >> sys.stderr, "error: unknown image file name ", image_filename 574 exit(1) 575 576 image_properties = ImagePropFromGlobalDict(glob_dict, mount_point) 577 578 if not BuildImage(in_dir, image_properties, out_file, target_out): 579 print >> sys.stderr, "error: failed to build %s from %s" % (out_file, 580 in_dir) 581 exit(1) 582 583 584if __name__ == '__main__': 585 main(sys.argv[1:]) 586