add_img_to_target_files.py revision 2f80e83e98c5d727bd484b8078ec99eb415158eb
1#!/usr/bin/env python
2#
3# Copyright (C) 2014 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"""
18Given a target-files zipfile that does not contain images (ie, does
19not have an IMAGES/ top-level subdirectory), produce the images and
20add them to the zipfile.
21
22Usage:  add_img_to_target_files [flag] target_files
23
24  -a  (--add_missing)
25      Build and add missing images to "IMAGES/". If this option is
26      not specified, this script will simply exit when "IMAGES/"
27      directory exists in the target file.
28
29  -r  (--rebuild_recovery)
30      Rebuild the recovery patch and write it to the system image. Only
31      meaningful when system image needs to be rebuilt.
32
33  --replace_verity_private_key
34      Replace the private key used for verity signing. (same as the option
35      in sign_target_files_apks)
36
37  --replace_verity_public_key
38       Replace the certificate (public key) used for verity verification. (same
39       as the option in sign_target_files_apks)
40
41  --is_signing
42      Skip building & adding the images for "userdata" and "cache" if we
43      are signing the target files.
44"""
45
46from __future__ import print_function
47
48import sys
49
50if sys.hexversion < 0x02070000:
51  print("Python 2.7 or newer is required.", file=sys.stderr)
52  sys.exit(1)
53
54import datetime
55import errno
56import os
57import shlex
58import shutil
59import subprocess
60import tempfile
61import zipfile
62
63import build_image
64import common
65import rangelib
66import sparse_img
67
68OPTIONS = common.OPTIONS
69
70OPTIONS.add_missing = False
71OPTIONS.rebuild_recovery = False
72OPTIONS.replace_verity_public_key = False
73OPTIONS.replace_verity_private_key = False
74OPTIONS.is_signing = False
75
76
77class OutputFile(object):
78  def __init__(self, output_zip, input_dir, prefix, name):
79    self._output_zip = output_zip
80    self.input_name = os.path.join(input_dir, prefix, name)
81
82    if self._output_zip:
83      self._zip_name = os.path.join(prefix, name)
84
85      root, suffix = os.path.splitext(name)
86      self.name = common.MakeTempFile(prefix=root + '-', suffix=suffix)
87    else:
88      self.name = self.input_name
89
90  def Write(self):
91    if self._output_zip:
92      common.ZipWrite(self._output_zip, self.name, self._zip_name)
93
94
95def GetCareMap(which, imgname):
96  """Generate care_map of system (or vendor) partition"""
97
98  assert which in ("system", "vendor")
99
100  simg = sparse_img.SparseImage(imgname)
101  care_map_list = []
102  care_map_list.append(which)
103
104  care_map_ranges = simg.care_map
105  key = which + "_adjusted_partition_size"
106  adjusted_blocks = OPTIONS.info_dict.get(key)
107  if adjusted_blocks:
108    assert adjusted_blocks > 0, "blocks should be positive for " + which
109    care_map_ranges = care_map_ranges.intersect(rangelib.RangeSet(
110        "0-%d" % (adjusted_blocks,)))
111
112  care_map_list.append(care_map_ranges.to_string_raw())
113  return care_map_list
114
115
116def AddSystem(output_zip, prefix="IMAGES/", recovery_img=None, boot_img=None):
117  """Turn the contents of SYSTEM into a system image and store it in
118  output_zip. Returns the name of the system image file."""
119
120  img = OutputFile(output_zip, OPTIONS.input_tmp, prefix, "system.img")
121  if os.path.exists(img.input_name):
122    print("system.img already exists in %s, no need to rebuild..." % (prefix,))
123    return img.input_name
124
125  def output_sink(fn, data):
126    ofile = open(os.path.join(OPTIONS.input_tmp, "SYSTEM", fn), "w")
127    ofile.write(data)
128    ofile.close()
129
130  if OPTIONS.rebuild_recovery:
131    print("Building new recovery patch")
132    common.MakeRecoveryPatch(OPTIONS.input_tmp, output_sink, recovery_img,
133                             boot_img, info_dict=OPTIONS.info_dict)
134
135  block_list = OutputFile(output_zip, OPTIONS.input_tmp, prefix, "system.map")
136  CreateImage(OPTIONS.input_tmp, OPTIONS.info_dict, "system", img,
137              block_list=block_list)
138
139  return img.name
140
141
142def AddSystemOther(output_zip, prefix="IMAGES/"):
143  """Turn the contents of SYSTEM_OTHER into a system_other image
144  and store it in output_zip."""
145
146  img = OutputFile(output_zip, OPTIONS.input_tmp, prefix, "system_other.img")
147  if os.path.exists(img.input_name):
148    print("system_other.img already exists in %s, no need to rebuild..." % (
149        prefix,))
150    return
151
152  CreateImage(OPTIONS.input_tmp, OPTIONS.info_dict, "system_other", img)
153
154
155def AddVendor(output_zip, prefix="IMAGES/"):
156  """Turn the contents of VENDOR into a vendor image and store in it
157  output_zip."""
158
159  img = OutputFile(output_zip, OPTIONS.input_tmp, prefix, "vendor.img")
160  if os.path.exists(img.input_name):
161    print("vendor.img already exists in %s, no need to rebuild..." % (prefix,))
162    return img.input_name
163
164  block_list = OutputFile(output_zip, OPTIONS.input_tmp, prefix, "vendor.map")
165  CreateImage(OPTIONS.input_tmp, OPTIONS.info_dict, "vendor", img,
166              block_list=block_list)
167  return img.name
168
169
170def CreateImage(input_dir, info_dict, what, output_file, block_list=None):
171  print("creating " + what + ".img...")
172
173  # The name of the directory it is making an image out of matters to
174  # mkyaffs2image.  It wants "system" but we have a directory named
175  # "SYSTEM", so create a symlink.
176  temp_dir = tempfile.mkdtemp()
177  OPTIONS.tempfiles.append(temp_dir)
178  try:
179    os.symlink(os.path.join(input_dir, what.upper()),
180               os.path.join(temp_dir, what))
181  except OSError as e:
182    # bogus error on my mac version?
183    #   File "./build/tools/releasetools/img_from_target_files"
184    #     os.path.join(OPTIONS.input_tmp, "system"))
185    # OSError: [Errno 17] File exists
186    if e.errno == errno.EEXIST:
187      pass
188
189  image_props = build_image.ImagePropFromGlobalDict(info_dict, what)
190  fstab = info_dict["fstab"]
191  mount_point = "/" + what
192  if fstab and mount_point in fstab:
193    image_props["fs_type"] = fstab[mount_point].fs_type
194
195  # Use a fixed timestamp (01/01/2009) when packaging the image.
196  # Bug: 24377993
197  epoch = datetime.datetime.fromtimestamp(0)
198  timestamp = (datetime.datetime(2009, 1, 1) - epoch).total_seconds()
199  image_props["timestamp"] = int(timestamp)
200
201  if what == "system":
202    fs_config_prefix = ""
203  else:
204    fs_config_prefix = what + "_"
205
206  fs_config = os.path.join(
207      input_dir, "META/" + fs_config_prefix + "filesystem_config.txt")
208  if not os.path.exists(fs_config):
209    fs_config = None
210
211  # Override values loaded from info_dict.
212  if fs_config:
213    image_props["fs_config"] = fs_config
214  if block_list:
215    image_props["block_list"] = block_list.name
216
217  succ = build_image.BuildImage(os.path.join(temp_dir, what),
218                                image_props, output_file.name)
219  assert succ, "build " + what + ".img image failed"
220
221  output_file.Write()
222  if block_list:
223    block_list.Write()
224
225  is_verity_partition = "verity_block_device" in image_props
226  verity_supported = image_props.get("verity") == "true"
227  if is_verity_partition and verity_supported:
228    adjusted_blocks_value = image_props.get("partition_size")
229    if adjusted_blocks_value:
230      adjusted_blocks_key = what + "_adjusted_partition_size"
231      info_dict[adjusted_blocks_key] = int(adjusted_blocks_value)/4096 - 1
232
233
234def AddUserdata(output_zip, prefix="IMAGES/"):
235  """Create a userdata image and store it in output_zip.
236
237  In most case we just create and store an empty userdata.img;
238  But the invoker can also request to create userdata.img with real
239  data from the target files, by setting "userdata_img_with_data=true"
240  in OPTIONS.info_dict.
241  """
242
243  img = OutputFile(output_zip, OPTIONS.input_tmp, prefix, "userdata.img")
244  if os.path.exists(img.input_name):
245    print("userdata.img already exists in %s, no need to rebuild..." % (
246        prefix,))
247    return
248
249  # Skip userdata.img if no size.
250  image_props = build_image.ImagePropFromGlobalDict(OPTIONS.info_dict, "data")
251  if not image_props.get("partition_size"):
252    return
253
254  print("creating userdata.img...")
255
256  # Use a fixed timestamp (01/01/2009) when packaging the image.
257  # Bug: 24377993
258  epoch = datetime.datetime.fromtimestamp(0)
259  timestamp = (datetime.datetime(2009, 1, 1) - epoch).total_seconds()
260  image_props["timestamp"] = int(timestamp)
261
262  # The name of the directory it is making an image out of matters to
263  # mkyaffs2image.  So we create a temp dir, and within it we create an
264  # empty dir named "data", or a symlink to the DATA dir,
265  # and build the image from that.
266  temp_dir = tempfile.mkdtemp()
267  OPTIONS.tempfiles.append(temp_dir)
268  user_dir = os.path.join(temp_dir, "data")
269  empty = (OPTIONS.info_dict.get("userdata_img_with_data") != "true")
270  if empty:
271    # Create an empty dir.
272    os.mkdir(user_dir)
273  else:
274    # Symlink to the DATA dir.
275    os.symlink(os.path.join(OPTIONS.input_tmp, "DATA"),
276               user_dir)
277
278  fstab = OPTIONS.info_dict["fstab"]
279  if fstab:
280    image_props["fs_type"] = fstab["/data"].fs_type
281  succ = build_image.BuildImage(user_dir, image_props, img.name)
282  assert succ, "build userdata.img image failed"
283
284  common.CheckSize(img.name, "userdata.img", OPTIONS.info_dict)
285  img.Write()
286
287
288def AddVBMeta(output_zip, boot_img_path, system_img_path, prefix="IMAGES/"):
289  """Create a VBMeta image and store it in output_zip."""
290  img = OutputFile(output_zip, OPTIONS.input_tmp, prefix, "vbmeta.img")
291  avbtool = os.getenv('AVBTOOL') or "avbtool"
292  cmd = [avbtool, "make_vbmeta_image",
293         "--output", img.name,
294         "--include_descriptors_from_image", boot_img_path,
295         "--include_descriptors_from_image", system_img_path,
296         "--generate_dm_verity_cmdline_from_hashtree", system_img_path]
297  common.AppendAVBSigningArgs(cmd)
298  args = OPTIONS.info_dict.get("board_avb_make_vbmeta_image_args", None)
299  if args and args.strip():
300    cmd.extend(shlex.split(args))
301  p = common.Run(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
302  p.communicate()
303  assert p.returncode == 0, "avbtool make_vbmeta_image failed"
304  img.Write()
305
306
307def AddPartitionTable(output_zip, prefix="IMAGES/"):
308  """Create a partition table image and store it in output_zip."""
309
310  img = OutputFile(output_zip, OPTIONS.input_tmp, prefix, "partition-table.img")
311  bpt = OutputFile(output_zip, OPTIONS.input_tmp, prefix, "partition-table.bpt")
312
313  # use BPTTOOL from environ, or "bpttool" if empty or not set.
314  bpttool = os.getenv("BPTTOOL") or "bpttool"
315  cmd = [bpttool, "make_table", "--output_json", bpt.name,
316         "--output_gpt", img.name]
317  input_files_str = OPTIONS.info_dict["board_bpt_input_files"]
318  input_files = input_files_str.split(" ")
319  for i in input_files:
320    cmd.extend(["--input", i])
321  disk_size = OPTIONS.info_dict.get("board_bpt_disk_size")
322  if disk_size:
323    cmd.extend(["--disk_size", disk_size])
324  args = OPTIONS.info_dict.get("board_bpt_make_table_args")
325  if args:
326    cmd.extend(shlex.split(args))
327
328  p = common.Run(cmd, stdout=subprocess.PIPE)
329  p.communicate()
330  assert p.returncode == 0, "bpttool make_table failed"
331
332  img.Write()
333  bpt.Write()
334
335
336def AddCache(output_zip, prefix="IMAGES/"):
337  """Create an empty cache image and store it in output_zip."""
338
339  img = OutputFile(output_zip, OPTIONS.input_tmp, prefix, "cache.img")
340  if os.path.exists(img.input_name):
341    print("cache.img already exists in %s, no need to rebuild..." % (prefix,))
342    return
343
344  image_props = build_image.ImagePropFromGlobalDict(OPTIONS.info_dict, "cache")
345  # The build system has to explicitly request for cache.img.
346  if "fs_type" not in image_props:
347    return
348
349  print("creating cache.img...")
350
351  # Use a fixed timestamp (01/01/2009) when packaging the image.
352  # Bug: 24377993
353  epoch = datetime.datetime.fromtimestamp(0)
354  timestamp = (datetime.datetime(2009, 1, 1) - epoch).total_seconds()
355  image_props["timestamp"] = int(timestamp)
356
357  # The name of the directory it is making an image out of matters to
358  # mkyaffs2image.  So we create a temp dir, and within it we create an
359  # empty dir named "cache", and build the image from that.
360  temp_dir = tempfile.mkdtemp()
361  OPTIONS.tempfiles.append(temp_dir)
362  user_dir = os.path.join(temp_dir, "cache")
363  os.mkdir(user_dir)
364
365  fstab = OPTIONS.info_dict["fstab"]
366  if fstab:
367    image_props["fs_type"] = fstab["/cache"].fs_type
368  succ = build_image.BuildImage(user_dir, image_props, img.name)
369  assert succ, "build cache.img image failed"
370
371  common.CheckSize(img.name, "cache.img", OPTIONS.info_dict)
372  img.Write()
373
374
375def AddImagesToTargetFiles(filename):
376  if os.path.isdir(filename):
377    OPTIONS.input_tmp = os.path.abspath(filename)
378    input_zip = None
379  else:
380    OPTIONS.input_tmp, input_zip = common.UnzipTemp(filename)
381
382  if not OPTIONS.add_missing:
383    if os.path.isdir(os.path.join(OPTIONS.input_tmp, "IMAGES")):
384      print("target_files appears to already contain images.")
385      sys.exit(1)
386
387  has_vendor = os.path.isdir(os.path.join(OPTIONS.input_tmp, "VENDOR"))
388  has_system_other = os.path.isdir(os.path.join(OPTIONS.input_tmp,
389                                                "SYSTEM_OTHER"))
390
391  if input_zip:
392    OPTIONS.info_dict = common.LoadInfoDict(input_zip, OPTIONS.input_tmp)
393
394    common.ZipClose(input_zip)
395    output_zip = zipfile.ZipFile(filename, "a",
396                                 compression=zipfile.ZIP_DEFLATED,
397                                 allowZip64=True)
398  else:
399    OPTIONS.info_dict = common.LoadInfoDict(filename, filename)
400    output_zip = None
401    images_dir = os.path.join(OPTIONS.input_tmp, "IMAGES")
402    if not os.path.isdir(images_dir):
403      os.makedirs(images_dir)
404    images_dir = None
405
406  has_recovery = (OPTIONS.info_dict.get("no_recovery") != "true")
407
408  def banner(s):
409    print("\n\n++++ " + s + " ++++\n\n")
410
411  prebuilt_path = os.path.join(OPTIONS.input_tmp, "IMAGES", "boot.img")
412  boot_image = None
413  if os.path.exists(prebuilt_path):
414    banner("boot")
415    print("boot.img already exists in IMAGES/, no need to rebuild...")
416    if OPTIONS.rebuild_recovery:
417      boot_image = common.GetBootableImage(
418          "IMAGES/boot.img", "boot.img", OPTIONS.input_tmp, "BOOT")
419  else:
420    banner("boot")
421    boot_image = common.GetBootableImage(
422        "IMAGES/boot.img", "boot.img", OPTIONS.input_tmp, "BOOT")
423    if boot_image:
424      if output_zip:
425        boot_image.AddToZip(output_zip)
426      else:
427        boot_image.WriteToDir(OPTIONS.input_tmp)
428
429  recovery_image = None
430  if has_recovery:
431    banner("recovery")
432    prebuilt_path = os.path.join(OPTIONS.input_tmp, "IMAGES", "recovery.img")
433    if os.path.exists(prebuilt_path):
434      print("recovery.img already exists in IMAGES/, no need to rebuild...")
435      if OPTIONS.rebuild_recovery:
436        recovery_image = common.GetBootableImage(
437            "IMAGES/recovery.img", "recovery.img", OPTIONS.input_tmp,
438            "RECOVERY")
439    else:
440      recovery_image = common.GetBootableImage(
441          "IMAGES/recovery.img", "recovery.img", OPTIONS.input_tmp, "RECOVERY")
442      if recovery_image:
443        if output_zip:
444          recovery_image.AddToZip(output_zip)
445        else:
446          recovery_image.WriteToDir(OPTIONS.input_tmp)
447
448      banner("recovery (two-step image)")
449      # The special recovery.img for two-step package use.
450      recovery_two_step_image = common.GetBootableImage(
451          "IMAGES/recovery-two-step.img", "recovery-two-step.img",
452          OPTIONS.input_tmp, "RECOVERY", two_step_image=True)
453      if recovery_two_step_image:
454        if output_zip:
455          recovery_two_step_image.AddToZip(output_zip)
456        else:
457          recovery_two_step_image.WriteToDir(OPTIONS.input_tmp)
458
459  banner("system")
460  system_img_path = AddSystem(
461    output_zip, recovery_img=recovery_image, boot_img=boot_image)
462  vendor_img_path = None
463  if has_vendor:
464    banner("vendor")
465    vendor_img_path = AddVendor(output_zip)
466  if has_system_other:
467    banner("system_other")
468    AddSystemOther(output_zip)
469  if not OPTIONS.is_signing:
470    banner("userdata")
471    AddUserdata(output_zip)
472    banner("cache")
473    AddCache(output_zip)
474  if OPTIONS.info_dict.get("board_bpt_enable", None) == "true":
475    banner("partition-table")
476    AddPartitionTable(output_zip)
477  if OPTIONS.info_dict.get("board_avb_enable", None) == "true":
478    banner("vbmeta")
479    boot_contents = boot_image.WriteToTemp()
480    AddVBMeta(output_zip, boot_contents.name, system_img_path)
481
482  # For devices using A/B update, copy over images from RADIO/ and/or
483  # VENDOR_IMAGES/ to IMAGES/ and make sure we have all the needed
484  # images ready under IMAGES/. All images should have '.img' as extension.
485  banner("radio")
486  ab_partitions = os.path.join(OPTIONS.input_tmp, "META", "ab_partitions.txt")
487  if os.path.exists(ab_partitions):
488    with open(ab_partitions, 'r') as f:
489      lines = f.readlines()
490    # For devices using A/B update, generate care_map for system and vendor
491    # partitions (if present), then write this file to target_files package.
492    care_map_list = []
493    for line in lines:
494      if line.strip() == "system" and OPTIONS.info_dict.get(
495          "system_verity_block_device", None) is not None:
496        assert os.path.exists(system_img_path)
497        care_map_list += GetCareMap("system", system_img_path)
498      if line.strip() == "vendor" and OPTIONS.info_dict.get(
499          "vendor_verity_block_device", None) is not None:
500        assert os.path.exists(vendor_img_path)
501        care_map_list += GetCareMap("vendor", vendor_img_path)
502
503      img_name = line.strip() + ".img"
504      prebuilt_path = os.path.join(OPTIONS.input_tmp, "IMAGES", img_name)
505      if os.path.exists(prebuilt_path):
506        print("%s already exists, no need to overwrite..." % (img_name,))
507        continue
508
509      img_radio_path = os.path.join(OPTIONS.input_tmp, "RADIO", img_name)
510      img_vendor_dir = os.path.join(
511        OPTIONS.input_tmp, "VENDOR_IMAGES")
512      if os.path.exists(img_radio_path):
513        if output_zip:
514          common.ZipWrite(output_zip, img_radio_path,
515                          os.path.join("IMAGES", img_name))
516        else:
517          shutil.copy(img_radio_path, prebuilt_path)
518      else:
519        for root, _, files in os.walk(img_vendor_dir):
520          if img_name in files:
521            if output_zip:
522              common.ZipWrite(output_zip, os.path.join(root, img_name),
523                os.path.join("IMAGES", img_name))
524            else:
525              shutil.copy(os.path.join(root, img_name), prebuilt_path)
526            break
527
528      if output_zip:
529        # Zip spec says: All slashes MUST be forward slashes.
530        img_path = 'IMAGES/' + img_name
531        assert img_path in output_zip.namelist(), "cannot find " + img_name
532      else:
533        img_path = os.path.join(OPTIONS.input_tmp, "IMAGES", img_name)
534        assert os.path.exists(img_path), "cannot find " + img_name
535
536    if care_map_list:
537      file_path = "META/care_map.txt"
538      if output_zip:
539        common.ZipWriteStr(output_zip, file_path, '\n'.join(care_map_list))
540      else:
541        with open(os.path.join(OPTIONS.input_tmp, file_path), 'w') as fp:
542          fp.write('\n'.join(care_map_list))
543
544  if output_zip:
545    common.ZipClose(output_zip)
546
547def main(argv):
548  def option_handler(o, a):
549    if o in ("-a", "--add_missing"):
550      OPTIONS.add_missing = True
551    elif o in ("-r", "--rebuild_recovery",):
552      OPTIONS.rebuild_recovery = True
553    elif o == "--replace_verity_private_key":
554      OPTIONS.replace_verity_private_key = (True, a)
555    elif o == "--replace_verity_public_key":
556      OPTIONS.replace_verity_public_key = (True, a)
557    elif o == "--is_signing":
558      OPTIONS.is_signing = True
559    else:
560      return False
561    return True
562
563  args = common.ParseOptions(
564      argv, __doc__, extra_opts="ar",
565      extra_long_opts=["add_missing", "rebuild_recovery",
566                       "replace_verity_public_key=",
567                       "replace_verity_private_key=",
568                       "is_signing"],
569      extra_option_handler=option_handler)
570
571
572  if len(args) != 1:
573    common.Usage(__doc__)
574    sys.exit(1)
575
576  AddImagesToTargetFiles(args[0])
577  print("done.")
578
579if __name__ == '__main__':
580  try:
581    common.CloseInheritedPipes()
582    main(sys.argv[1:])
583  except common.ExternalError as e:
584    print("\n   ERROR: %s\n" % (e,))
585    sys.exit(1)
586  finally:
587    common.Cleanup()
588