build_image.py revision ff914f5dd0858552dad421b293f2dca0f2e8bb49
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 Append(target, file_to_append, error_message):
186  cmd = 'cat %s >> %s' % (file_to_append, target)
187  print cmd
188  status, output = commands.getstatusoutput(cmd)
189  if status:
190    print "%s: %s" % (error_message, output)
191    return False
192  return True
193
194def BuildVerifiedImage(data_image_path, verity_image_path,
195                       verity_metadata_path):
196  if not Append(verity_image_path, verity_metadata_path,
197                "Could not append verity metadata!"):
198    return False
199  if not Append2Simg(data_image_path, verity_image_path,
200                     "Could not append verity data!"):
201    return False
202  return True
203
204def UnsparseImage(sparse_image_path, replace=True):
205  img_dir = os.path.dirname(sparse_image_path)
206  unsparse_image_path = "unsparse_" + os.path.basename(sparse_image_path)
207  unsparse_image_path = os.path.join(img_dir, unsparse_image_path)
208  if os.path.exists(unsparse_image_path):
209    if replace:
210      os.unlink(unsparse_image_path)
211    else:
212      return True, unsparse_image_path
213  inflate_command = ["simg2img", sparse_image_path, unsparse_image_path]
214  (_, exit_code) = RunCommand(inflate_command)
215  if exit_code != 0:
216    os.remove(unsparse_image_path)
217    return False, None
218  return True, unsparse_image_path
219
220def MakeVerityEnabledImage(out_file, fec_supported, prop_dict):
221  """Creates an image that is verifiable using dm-verity.
222
223  Args:
224    out_file: the location to write the verifiable image at
225    prop_dict: a dictionary of properties required for image creation and
226               verification
227  Returns:
228    True on success, False otherwise.
229  """
230  # get properties
231  image_size = prop_dict["partition_size"]
232  block_dev = prop_dict["verity_block_device"]
233  signer_key = prop_dict["verity_key"] + ".pk8"
234  if OPTIONS.verity_signer_path is not None:
235    signer_path = OPTIONS.verity_signer_path + ' '
236    signer_path += ' '.join(OPTIONS.verity_signer_args)
237  else:
238    signer_path = prop_dict["verity_signer_cmd"]
239
240  # make a tempdir
241  tempdir_name = tempfile.mkdtemp(suffix="_verity_images")
242
243  # get partial image paths
244  verity_image_path = os.path.join(tempdir_name, "verity.img")
245  verity_metadata_path = os.path.join(tempdir_name, "verity_metadata.img")
246  verity_fec_path = os.path.join(tempdir_name, "verity_fec.img")
247
248  # build the verity tree and get the root hash and salt
249  if not BuildVerityTree(out_file, verity_image_path, prop_dict):
250    shutil.rmtree(tempdir_name, ignore_errors=True)
251    return False
252
253  # build the metadata blocks
254  root_hash = prop_dict["verity_root_hash"]
255  salt = prop_dict["verity_salt"]
256  if not BuildVerityMetadata(image_size, verity_metadata_path, root_hash, salt,
257                             block_dev, signer_path, signer_key):
258    shutil.rmtree(tempdir_name, ignore_errors=True)
259    return False
260
261  # build the full verified image
262  if not BuildVerifiedImage(out_file,
263                            verity_image_path,
264                            verity_metadata_path):
265    shutil.rmtree(tempdir_name, ignore_errors=True)
266    return False
267
268  if fec_supported:
269    # build FEC for the entire partition, including metadata
270    if not BuildVerityFEC(out_file, verity_fec_path, prop_dict):
271      shutil.rmtree(tempdir_name, ignore_errors=True)
272      return False
273
274    if not Append2Simg(out_file, verity_fec_path, "Could not append FEC!"):
275      shutil.rmtree(tempdir_name, ignore_errors=True)
276      return False
277
278  shutil.rmtree(tempdir_name, ignore_errors=True)
279  return True
280
281def BuildImage(in_dir, prop_dict, out_file, target_out=None):
282  """Build an image to out_file from in_dir with property prop_dict.
283
284  Args:
285    in_dir: path of input directory.
286    prop_dict: property dictionary.
287    out_file: path of the output image file.
288    target_out: path of the product out directory to read device specific FS config files.
289
290  Returns:
291    True iff the image is built successfully.
292  """
293  # system_root_image=true: build a system.img that combines the contents of
294  # /system and the ramdisk, and can be mounted at the root of the file system.
295  origin_in = in_dir
296  fs_config = prop_dict.get("fs_config")
297  if (prop_dict.get("system_root_image") == "true"
298      and prop_dict["mount_point"] == "system"):
299    in_dir = tempfile.mkdtemp()
300    # Change the mount point to "/"
301    prop_dict["mount_point"] = "/"
302    if fs_config:
303      # We need to merge the fs_config files of system and ramdisk.
304      fd, merged_fs_config = tempfile.mkstemp(prefix="root_fs_config",
305                                              suffix=".txt")
306      os.close(fd)
307      with open(merged_fs_config, "w") as fw:
308        if "ramdisk_fs_config" in prop_dict:
309          with open(prop_dict["ramdisk_fs_config"]) as fr:
310            fw.writelines(fr.readlines())
311        with open(fs_config) as fr:
312          fw.writelines(fr.readlines())
313      fs_config = merged_fs_config
314
315  build_command = []
316  fs_type = prop_dict.get("fs_type", "")
317  run_fsck = False
318
319  fs_spans_partition = True
320  if fs_type.startswith("squash"):
321    fs_spans_partition = False
322
323  is_verity_partition = "verity_block_device" in prop_dict
324  verity_supported = prop_dict.get("verity") == "true"
325  verity_fec_supported = prop_dict.get("verity_fec") == "true"
326
327  # Adjust the partition size to make room for the hashes if this is to be
328  # verified.
329  if verity_supported and is_verity_partition and fs_spans_partition:
330    partition_size = int(prop_dict.get("partition_size"))
331    adjusted_size = AdjustPartitionSizeForVerity(partition_size,
332                                                 verity_fec_supported)
333    if not adjusted_size:
334      return False
335    prop_dict["partition_size"] = str(adjusted_size)
336    prop_dict["original_partition_size"] = str(partition_size)
337
338  if fs_type.startswith("ext"):
339    build_command = ["mkuserimg.sh"]
340    if "extfs_sparse_flag" in prop_dict:
341      build_command.append(prop_dict["extfs_sparse_flag"])
342      run_fsck = True
343    build_command.extend([in_dir, out_file, fs_type,
344                          prop_dict["mount_point"]])
345    build_command.append(prop_dict["partition_size"])
346    if "journal_size" in prop_dict:
347      build_command.extend(["-j", prop_dict["journal_size"]])
348    if "timestamp" in prop_dict:
349      build_command.extend(["-T", str(prop_dict["timestamp"])])
350    if fs_config:
351      build_command.extend(["-C", fs_config])
352    if target_out:
353      build_command.extend(["-D", target_out])
354    if "block_list" in prop_dict:
355      build_command.extend(["-B", prop_dict["block_list"]])
356    build_command.extend(["-L", prop_dict["mount_point"]])
357    if "selinux_fc" in prop_dict:
358      build_command.append(prop_dict["selinux_fc"])
359  elif fs_type.startswith("squash"):
360    build_command = ["mksquashfsimage.sh"]
361    build_command.extend([in_dir, out_file])
362    if "squashfs_sparse_flag" in prop_dict:
363      build_command.extend([prop_dict["squashfs_sparse_flag"]])
364    build_command.extend(["-m", prop_dict["mount_point"]])
365    if target_out:
366      build_command.extend(["-d", target_out])
367    if "selinux_fc" in prop_dict:
368      build_command.extend(["-c", prop_dict["selinux_fc"]])
369    if "squashfs_compressor" in prop_dict:
370      build_command.extend(["-z", prop_dict["squashfs_compressor"]])
371    if "squashfs_compressor_opt" in prop_dict:
372      build_command.extend(["-zo", prop_dict["squashfs_compressor_opt"]])
373  elif fs_type.startswith("f2fs"):
374    build_command = ["mkf2fsuserimg.sh"]
375    build_command.extend([out_file, prop_dict["partition_size"]])
376  else:
377    build_command = ["mkyaffs2image", "-f"]
378    if prop_dict.get("mkyaffs2_extra_flags", None):
379      build_command.extend(prop_dict["mkyaffs2_extra_flags"].split())
380    build_command.append(in_dir)
381    build_command.append(out_file)
382    if "selinux_fc" in prop_dict:
383      build_command.append(prop_dict["selinux_fc"])
384      build_command.append(prop_dict["mount_point"])
385
386  if in_dir != origin_in:
387    # Construct a staging directory of the root file system.
388    ramdisk_dir = prop_dict.get("ramdisk_dir")
389    if ramdisk_dir:
390      shutil.rmtree(in_dir)
391      shutil.copytree(ramdisk_dir, in_dir, symlinks=True)
392    staging_system = os.path.join(in_dir, "system")
393    shutil.rmtree(staging_system, ignore_errors=True)
394    shutil.copytree(origin_in, staging_system, symlinks=True)
395
396  reserved_blocks = prop_dict.get("has_ext4_reserved_blocks") == "true"
397  ext4fs_output = None
398
399  try:
400    if reserved_blocks and fs_type.startswith("ext4"):
401      (ext4fs_output, exit_code) = RunCommand(build_command)
402    else:
403      (_, exit_code) = RunCommand(build_command)
404  finally:
405    if in_dir != origin_in:
406      # Clean up temporary directories and files.
407      shutil.rmtree(in_dir, ignore_errors=True)
408      if fs_config:
409        os.remove(fs_config)
410  if exit_code != 0:
411    return False
412
413  # Bug: 21522719, 22023465
414  # There are some reserved blocks on ext4 FS (lesser of 4096 blocks and 2%).
415  # We need to deduct those blocks from the available space, since they are
416  # not writable even with root privilege. It only affects devices using
417  # file-based OTA and a kernel version of 3.10 or greater (currently just
418  # sprout).
419  if reserved_blocks and fs_type.startswith("ext4"):
420    assert ext4fs_output is not None
421    ext4fs_stats = re.compile(
422        r'Created filesystem with .* (?P<used_blocks>[0-9]+)/'
423        r'(?P<total_blocks>[0-9]+) blocks')
424    m = ext4fs_stats.match(ext4fs_output.strip().split('\n')[-1])
425    used_blocks = int(m.groupdict().get('used_blocks'))
426    total_blocks = int(m.groupdict().get('total_blocks'))
427    reserved_blocks = min(4096, int(total_blocks * 0.02))
428    adjusted_blocks = total_blocks - reserved_blocks
429    if used_blocks > adjusted_blocks:
430      mount_point = prop_dict.get("mount_point")
431      print("Error: Not enough room on %s (total: %d blocks, used: %d blocks, "
432            "reserved: %d blocks, available: %d blocks)" % (
433                mount_point, total_blocks, used_blocks, reserved_blocks,
434                adjusted_blocks))
435      return False
436
437  if not fs_spans_partition:
438    mount_point = prop_dict.get("mount_point")
439    partition_size = int(prop_dict.get("partition_size"))
440    image_size = os.stat(out_file).st_size
441    if image_size > partition_size:
442      print("Error: %s image size of %d is larger than partition size of "
443            "%d" % (mount_point, image_size, partition_size))
444      return False
445    if verity_supported and is_verity_partition:
446      if 2 * image_size - AdjustPartitionSizeForVerity(image_size, verity_fec_supported) > partition_size:
447        print "Error: No more room on %s to fit verity data" % mount_point
448        return False
449    prop_dict["original_partition_size"] = prop_dict["partition_size"]
450    prop_dict["partition_size"] = str(image_size)
451
452  # create the verified image if this is to be verified
453  if verity_supported and is_verity_partition:
454    if not MakeVerityEnabledImage(out_file, verity_fec_supported, prop_dict):
455      return False
456
457  if run_fsck and prop_dict.get("skip_fsck") != "true":
458    success, unsparse_image = UnsparseImage(out_file, replace=False)
459    if not success:
460      return False
461
462    # Run e2fsck on the inflated image file
463    e2fsck_command = ["e2fsck", "-f", "-n", unsparse_image]
464    (_, exit_code) = RunCommand(e2fsck_command)
465
466    os.remove(unsparse_image)
467
468  return exit_code == 0
469
470
471def ImagePropFromGlobalDict(glob_dict, mount_point):
472  """Build an image property dictionary from the global dictionary.
473
474  Args:
475    glob_dict: the global dictionary from the build system.
476    mount_point: such as "system", "data" etc.
477  """
478  d = {}
479
480  if "build.prop" in glob_dict:
481    bp = glob_dict["build.prop"]
482    if "ro.build.date.utc" in bp:
483      d["timestamp"] = bp["ro.build.date.utc"]
484
485  def copy_prop(src_p, dest_p):
486    if src_p in glob_dict:
487      d[dest_p] = str(glob_dict[src_p])
488
489  common_props = (
490      "extfs_sparse_flag",
491      "squashfs_sparse_flag",
492      "mkyaffs2_extra_flags",
493      "selinux_fc",
494      "skip_fsck",
495      "verity",
496      "verity_key",
497      "verity_signer_cmd",
498      "verity_fec"
499      )
500  for p in common_props:
501    copy_prop(p, p)
502
503  d["mount_point"] = mount_point
504  if mount_point == "system":
505    copy_prop("fs_type", "fs_type")
506    # Copy the generic sysetem fs type first, override with specific one if
507    # available.
508    copy_prop("system_fs_type", "fs_type")
509    copy_prop("system_size", "partition_size")
510    copy_prop("system_journal_size", "journal_size")
511    copy_prop("system_verity_block_device", "verity_block_device")
512    copy_prop("system_root_image", "system_root_image")
513    copy_prop("ramdisk_dir", "ramdisk_dir")
514    copy_prop("ramdisk_fs_config", "ramdisk_fs_config")
515    copy_prop("has_ext4_reserved_blocks", "has_ext4_reserved_blocks")
516    copy_prop("system_squashfs_compressor", "squashfs_compressor")
517    copy_prop("system_squashfs_compressor_opt", "squashfs_compressor_opt")
518  elif mount_point == "data":
519    # Copy the generic fs type first, override with specific one if available.
520    copy_prop("fs_type", "fs_type")
521    copy_prop("userdata_fs_type", "fs_type")
522    copy_prop("userdata_size", "partition_size")
523  elif mount_point == "cache":
524    copy_prop("cache_fs_type", "fs_type")
525    copy_prop("cache_size", "partition_size")
526  elif mount_point == "vendor":
527    copy_prop("vendor_fs_type", "fs_type")
528    copy_prop("vendor_size", "partition_size")
529    copy_prop("vendor_journal_size", "journal_size")
530    copy_prop("vendor_verity_block_device", "verity_block_device")
531    copy_prop("has_ext4_reserved_blocks", "has_ext4_reserved_blocks")
532  elif mount_point == "oem":
533    copy_prop("fs_type", "fs_type")
534    copy_prop("oem_size", "partition_size")
535    copy_prop("oem_journal_size", "journal_size")
536    copy_prop("has_ext4_reserved_blocks", "has_ext4_reserved_blocks")
537
538  return d
539
540
541def LoadGlobalDict(filename):
542  """Load "name=value" pairs from filename"""
543  d = {}
544  f = open(filename)
545  for line in f:
546    line = line.strip()
547    if not line or line.startswith("#"):
548      continue
549    k, v = line.split("=", 1)
550    d[k] = v
551  f.close()
552  return d
553
554
555def main(argv):
556  if len(argv) != 4:
557    print __doc__
558    sys.exit(1)
559
560  in_dir = argv[0]
561  glob_dict_file = argv[1]
562  out_file = argv[2]
563  target_out = argv[3]
564
565  glob_dict = LoadGlobalDict(glob_dict_file)
566  if "mount_point" in glob_dict:
567    # The caller knows the mount point and provides a dictionay needed by
568    # BuildImage().
569    image_properties = glob_dict
570  else:
571    image_filename = os.path.basename(out_file)
572    mount_point = ""
573    if image_filename == "system.img":
574      mount_point = "system"
575    elif image_filename == "userdata.img":
576      mount_point = "data"
577    elif image_filename == "cache.img":
578      mount_point = "cache"
579    elif image_filename == "vendor.img":
580      mount_point = "vendor"
581    elif image_filename == "oem.img":
582      mount_point = "oem"
583    else:
584      print >> sys.stderr, "error: unknown image file name ", image_filename
585      exit(1)
586
587    image_properties = ImagePropFromGlobalDict(glob_dict, mount_point)
588
589  if not BuildImage(in_dir, image_properties, out_file, target_out):
590    print >> sys.stderr, "error: failed to build %s from %s" % (out_file,
591                                                                in_dir)
592    exit(1)
593
594
595if __name__ == '__main__':
596  main(sys.argv[1:])
597