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