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