Пример #1
0
def main(argv):
    def option_handler(o, a):
        if o in ("-a", "--add_missing"):
            OPTIONS.add_missing = True
        elif o in (
                "-r",
                "--rebuild_recovery",
        ):
            OPTIONS.rebuild_recovery = True
        elif o == "--replace_verity_private_key":
            OPTIONS.replace_verity_private_key = (True, a)
        elif o == "--replace_verity_public_key":
            OPTIONS.replace_verity_public_key = (True, a)
        elif o == "--is_signing":
            OPTIONS.is_signing = True
        elif o == "--verity_signer_path":
            OPTIONS.verity_signer_path = a
        else:
            return False
        return True

    args = common.ParseOptions(argv,
                               __doc__,
                               extra_opts="ar",
                               extra_long_opts=[
                                   "add_missing", "rebuild_recovery",
                                   "replace_verity_public_key=",
                                   "replace_verity_private_key=", "is_signing",
                                   "verity_signer_path="
                               ],
                               extra_option_handler=option_handler)

    if len(args) != 1:
        common.Usage(__doc__)
        sys.exit(1)

    AddImagesToTargetFiles(args[0])
    print "done."
Пример #2
0
def main(argv):

  key_mapping_options = []

  def option_handler(o, a):
    if o in ("-e", "--extra_apks"):
      names, key = a.split("=")
      names = names.split(",")
      for n in names:
        OPTIONS.extra_apks[n] = key
    elif o in ("-d", "--default_key_mappings"):
      key_mapping_options.append((None, a))
    elif o in ("-k", "--key_mapping"):
      key_mapping_options.append(a.split("=", 1))
    elif o in ("-o", "--replace_ota_keys"):
      OPTIONS.replace_ota_keys = True
    elif o in ("-t", "--tag_changes"):
      new = []
      for i in a.split(","):
        i = i.strip()
        if not i or i[0] not in "-+":
          raise ValueError("Bad tag change '%s'" % (i,))
        new.append(i[0] + i[1:].strip())
      OPTIONS.tag_changes = tuple(new)
    elif o == "--replace_verity_public_key":
      OPTIONS.replace_verity_public_key = (True, a)
    elif o == "--replace_verity_private_key":
      OPTIONS.replace_verity_private_key = (True, a)
    elif o == "--replace_verity_keyid":
      OPTIONS.replace_verity_keyid = (True, a)
    else:
      return False
    return True

  args = common.ParseOptions(argv, __doc__,
                             extra_opts="e:d:k:ot:",
                             extra_long_opts=["extra_apks=",
                                              "default_key_mappings=",
                                              "key_mapping=",
                                              "replace_ota_keys",
                                              "tag_changes=",
                                              "replace_verity_public_key=",
                                              "replace_verity_private_key=",
                                              "replace_verity_keyid="],
                             extra_option_handler=option_handler)

  if len(args) != 2:
    common.Usage(__doc__)
    sys.exit(1)

  input_zip = zipfile.ZipFile(args[0], "r")
  output_zip = zipfile.ZipFile(args[1], "w")

  misc_info = common.LoadInfoDict(input_zip)

  BuildKeyMap(misc_info, key_mapping_options)

  apk_key_map = GetApkCerts(input_zip)
  CheckAllApksSigned(input_zip, apk_key_map)

  key_passwords = common.GetKeyPasswords(set(apk_key_map.values()))
  platform_api_level, platform_codename = GetApiLevelAndCodename(input_zip)
  codename_to_api_level_map = GetCodenameToApiLevelMap(input_zip)
  # Android N will be API Level 24, but isn't yet.
  # TODO: Remove this workaround once Android N is officially API Level 24.
  if platform_api_level == 23 and platform_codename == "N":
    platform_api_level = 24

  ProcessTargetFiles(input_zip, output_zip, misc_info,
                     apk_key_map, key_passwords,
                     platform_api_level,
                     codename_to_api_level_map)

  common.ZipClose(input_zip)
  common.ZipClose(output_zip)

  add_img_to_target_files.AddImagesToTargetFiles(args[1])

  print "done."
Пример #3
0
def main(argv):
    bootable_only = [False]

    def option_handler(o, _):
        if o in ("-z", "--bootable_zip"):
            bootable_only[0] = True
        else:
            return False
        return True

    args = common.ParseOptions(argv,
                               __doc__,
                               extra_opts="z",
                               extra_long_opts=["bootable_zip"],
                               extra_option_handler=option_handler)

    bootable_only = bootable_only[0]

    if len(args) != 2:
        common.Usage(__doc__)
        sys.exit(1)

    OPTIONS.input_tmp, input_zip = common.UnzipTemp(args[0])
    output_zip = zipfile.ZipFile(args[1],
                                 "w",
                                 compression=zipfile.ZIP_DEFLATED)
    CopyInfo(output_zip)
    AddRadio(output_zip)

    try:
        done = False
        images_path = os.path.join(OPTIONS.input_tmp, "IMAGES")
        if os.path.exists(images_path):
            # If this is a new target-files, it already contains the images,
            # and all we have to do is copy them to the output zip.
            # Skip oem.img files since they are not needed in fastboot images.
            images = os.listdir(images_path)
            if images:
                for image in images:
                    if bootable_only and image not in ("boot.img",
                                                       "recovery.img"):
                        continue
                    if not image.endswith(".img"):
                        continue
                    if image == "oem.img" or image == "recovery-two-step.img":
                        continue
                    common.ZipWrite(output_zip,
                                    os.path.join(images_path, image), image)
                done = True

        if not done:
            # We have an old target-files that doesn't already contain the
            # images, so build them.
            import add_img_to_target_files

            OPTIONS.info_dict = common.LoadInfoDict(input_zip,
                                                    OPTIONS.input_tmp)

            boot_image = common.GetBootableImage("boot.img", "boot.img",
                                                 OPTIONS.input_tmp, "BOOT")
            if boot_image:
                boot_image.AddToZip(output_zip)

            if OPTIONS.info_dict.get("no_recovery") != "true":
                recovery_image = common.GetBootableImage(
                    "recovery.img", "recovery.img", OPTIONS.input_tmp,
                    "RECOVERY")
                if recovery_image:
                    recovery_image.AddToZip(output_zip)

            def banner(s):
                print("\n\n++++ " + s + " ++++\n\n")

            if not bootable_only:
                banner("AddSystem")
                add_img_to_target_files.AddSystem(output_zip, prefix="")
                try:
                    input_zip.getinfo("VENDOR/")
                    banner("AddVendor")
                    add_img_to_target_files.AddVendor(output_zip, prefix="")
                except KeyError:
                    pass  # no vendor partition for this device
                banner("AddUserdata")
                add_img_to_target_files.AddUserdata(output_zip, prefix="")
                banner("AddUserdataExtra")
                add_img_to_target_files.AddUserdataExtra(output_zip, prefix="")
                banner("AddCache")
                add_img_to_target_files.AddCache(output_zip, prefix="")

    finally:
        print("cleaning up...")
        common.ZipClose(output_zip)
        shutil.rmtree(OPTIONS.input_tmp)

    print("done.")
Пример #4
0
def main(argv):

  key_mapping_options = []

  def option_handler(o, a):
    if o in ("-e", "--extra_apks"):
      names, key = a.split("=")
      names = names.split(",")
      for n in names:
        OPTIONS.extra_apks[n] = key
    elif o in ("-d", "--default_key_mappings"):
      key_mapping_options.append((None, a))
    elif o in ("-k", "--key_mapping"):
      key_mapping_options.append(a.split("=", 1))
    elif o in ("-o", "--replace_ota_keys"):
      OPTIONS.replace_ota_keys = True
    elif o in ("-t", "--tag_changes"):
      new = []
      for i in a.split(","):
        i = i.strip()
        if not i or i[0] not in "-+":
          raise ValueError("Bad tag change '%s'" % (i,))
        new.append(i[0] + i[1:].strip())
      OPTIONS.tag_changes = tuple(new)
    elif o == "--replace_verity_public_key":
      OPTIONS.replace_verity_public_key = (True, a)
    elif o == "--replace_verity_private_key":
      OPTIONS.replace_verity_private_key = (True, a)
    elif o == "--replace_verity_keyid":
      OPTIONS.replace_verity_keyid = (True, a)
    elif o == "--avb_vbmeta_key":
      OPTIONS.avb_keys['vbmeta'] = a
    elif o == "--avb_vbmeta_algorithm":
      OPTIONS.avb_algorithms['vbmeta'] = a
    elif o == "--avb_vbmeta_extra_args":
      OPTIONS.avb_extra_args['vbmeta'] = a
    elif o == "--avb_boot_key":
      OPTIONS.avb_keys['boot'] = a
    elif o == "--avb_boot_algorithm":
      OPTIONS.avb_algorithms['boot'] = a
    elif o == "--avb_boot_extra_args":
      OPTIONS.avb_extra_args['boot'] = a
    elif o == "--avb_dtbo_key":
      OPTIONS.avb_keys['dtbo'] = a
    elif o == "--avb_dtbo_algorithm":
      OPTIONS.avb_algorithms['dtbo'] = a
    elif o == "--avb_dtbo_extra_args":
      OPTIONS.avb_extra_args['dtbo'] = a
    elif o == "--avb_system_key":
      OPTIONS.avb_keys['system'] = a
    elif o == "--avb_system_algorithm":
      OPTIONS.avb_algorithms['system'] = a
    elif o == "--avb_system_extra_args":
      OPTIONS.avb_extra_args['system'] = a
    elif o == "--avb_vendor_key":
      OPTIONS.avb_keys['vendor'] = a
    elif o == "--avb_vendor_algorithm":
      OPTIONS.avb_algorithms['vendor'] = a
    elif o == "--avb_vendor_extra_args":
      OPTIONS.avb_extra_args['vendor'] = a
    else:
      return False
    return True

  args = common.ParseOptions(
      argv, __doc__,
      extra_opts="e:d:k:ot:",
      extra_long_opts=[
        "extra_apks=",
        "default_key_mappings=",
        "key_mapping=",
        "replace_ota_keys",
        "tag_changes=",
        "replace_verity_public_key=",
        "replace_verity_private_key=",
        "replace_verity_keyid=",
        "avb_vbmeta_algorithm=",
        "avb_vbmeta_key=",
        "avb_vbmeta_extra_args=",
        "avb_boot_algorithm=",
        "avb_boot_key=",
        "avb_boot_extra_args=",
        "avb_dtbo_algorithm=",
        "avb_dtbo_key=",
        "avb_dtbo_extra_args=",
        "avb_system_algorithm=",
        "avb_system_key=",
        "avb_system_extra_args=",
        "avb_vendor_algorithm=",
        "avb_vendor_key=",
        "avb_vendor_extra_args=",
      ],
      extra_option_handler=option_handler)

  if len(args) != 2:
    common.Usage(__doc__)
    sys.exit(1)

  input_zip = zipfile.ZipFile(args[0], "r")
  output_zip = zipfile.ZipFile(args[1], "w")

  misc_info = common.LoadInfoDict(input_zip)

  BuildKeyMap(misc_info, key_mapping_options)

  apk_key_map = GetApkCerts(input_zip)
  CheckAllApksSigned(input_zip, apk_key_map)

  key_passwords = common.GetKeyPasswords(set(apk_key_map.values()))
  platform_api_level, _ = GetApiLevelAndCodename(input_zip)
  codename_to_api_level_map = GetCodenameToApiLevelMap(input_zip)

  ProcessTargetFiles(input_zip, output_zip, misc_info,
                     apk_key_map, key_passwords,
                     platform_api_level,
                     codename_to_api_level_map)

  common.ZipClose(input_zip)
  common.ZipClose(output_zip)

  # Skip building userdata.img and cache.img when signing the target files.
  new_args = ["--is_signing"]
  # add_img_to_target_files builds the system image from scratch, so the
  # recovery patch is guaranteed to be regenerated there.
  if OPTIONS.rebuild_recovery:
    new_args.append("--rebuild_recovery")
  new_args.append(args[1])
  add_img_to_target_files.main(new_args)

  print "done."
def main():
    """The main function.

  Process command line arguments, then call merge_target_files to
  perform the heavy lifting.
  """

    common.InitLogging()

    def option_handler(o, a):
        if o == '--system-target-files':
            logger.warning(
                '--system-target-files has been renamed to --framework-target-files'
            )
            OPTIONS.framework_target_files = a
        elif o == '--framework-target-files':
            OPTIONS.framework_target_files = a
        elif o == '--system-item-list':
            logger.warning(
                '--system-item-list has been renamed to --framework-item-list')
            OPTIONS.framework_item_list = a
        elif o == '--framework-item-list':
            OPTIONS.framework_item_list = a
        elif o == '--system-misc-info-keys':
            logger.warning('--system-misc-info-keys has been renamed to '
                           '--framework-misc-info-keys')
            OPTIONS.framework_misc_info_keys = a
        elif o == '--framework-misc-info-keys':
            OPTIONS.framework_misc_info_keys = a
        elif o == '--other-target-files':
            logger.warning(
                '--other-target-files has been renamed to --vendor-target-files'
            )
            OPTIONS.vendor_target_files = a
        elif o == '--vendor-target-files':
            OPTIONS.vendor_target_files = a
        elif o == '--other-item-list':
            logger.warning(
                '--other-item-list has been renamed to --vendor-item-list')
            OPTIONS.vendor_item_list = a
        elif o == '--vendor-item-list':
            OPTIONS.vendor_item_list = a
        elif o == '--output-target-files':
            OPTIONS.output_target_files = a
        elif o == '--output-dir':
            OPTIONS.output_dir = a
        elif o == '--output-item-list':
            OPTIONS.output_item_list = a
        elif o == '--output-ota':
            OPTIONS.output_ota = a
        elif o == '--output-img':
            OPTIONS.output_img = a
        elif o == '--output-super-empty':
            OPTIONS.output_super_empty = a
        elif o == '--rebuild_recovery':
            OPTIONS.rebuild_recovery = True
        elif o == '--keep-tmp':
            OPTIONS.keep_tmp = True
        else:
            return False
        return True

    args = common.ParseOptions(sys.argv[1:],
                               __doc__,
                               extra_long_opts=[
                                   'system-target-files=',
                                   'framework-target-files=',
                                   'system-item-list=',
                                   'framework-item-list=',
                                   'system-misc-info-keys=',
                                   'framework-misc-info-keys=',
                                   'other-target-files=',
                                   'vendor-target-files=',
                                   'other-item-list=',
                                   'vendor-item-list=',
                                   'output-target-files=',
                                   'output-dir=',
                                   'output-item-list=',
                                   'output-ota=',
                                   'output-img=',
                                   'output-super-empty=',
                                   'rebuild_recovery',
                                   'keep-tmp',
                               ],
                               extra_option_handler=option_handler)

    # pylint: disable=too-many-boolean-expressions
    if (args or OPTIONS.framework_target_files is None
            or OPTIONS.vendor_target_files is None or
        (OPTIONS.output_target_files is None and OPTIONS.output_dir is None) or
        (OPTIONS.output_dir is not None and OPTIONS.output_item_list is None)):
        common.Usage(__doc__)
        sys.exit(1)

    # Always turn on verbose logging.
    OPTIONS.verbose = True

    if OPTIONS.framework_item_list:
        framework_item_list = common.LoadListFromFile(
            OPTIONS.framework_item_list)
    else:
        framework_item_list = DEFAULT_FRAMEWORK_ITEM_LIST

    if OPTIONS.framework_misc_info_keys:
        framework_misc_info_keys = common.LoadListFromFile(
            OPTIONS.framework_misc_info_keys)
    else:
        framework_misc_info_keys = DEFAULT_FRAMEWORK_MISC_INFO_KEYS

    if OPTIONS.vendor_item_list:
        vendor_item_list = common.LoadListFromFile(OPTIONS.vendor_item_list)
    else:
        vendor_item_list = DEFAULT_VENDOR_ITEM_LIST

    if OPTIONS.output_item_list:
        output_item_list = common.LoadListFromFile(OPTIONS.output_item_list)
    else:
        output_item_list = None

    if not validate_config_lists(
            framework_item_list=framework_item_list,
            framework_misc_info_keys=framework_misc_info_keys,
            vendor_item_list=vendor_item_list):
        sys.exit(1)

    call_func_with_temp_dir(
        lambda temp_dir: merge_target_files(
            temp_dir=temp_dir,
            framework_target_files=OPTIONS.framework_target_files,
            framework_item_list=framework_item_list,
            framework_misc_info_keys=framework_misc_info_keys,
            vendor_target_files=OPTIONS.vendor_target_files,
            vendor_item_list=vendor_item_list,
            output_target_files=OPTIONS.output_target_files,
            output_dir=OPTIONS.output_dir,
            output_item_list=output_item_list,
            output_ota=OPTIONS.output_ota,
            output_img=OPTIONS.output_img,
            output_super_empty=OPTIONS.output_super_empty,
            rebuild_recovery=OPTIONS.rebuild_recovery), OPTIONS.keep_tmp)
Пример #6
0
def main(argv):

  key_mapping_options = []

  def option_handler(o, a):
    if o in ("-e", "--extra_apks"):
      names, key = a.split("=")
      names = names.split(",")
      for n in names:
        OPTIONS.extra_apks[n] = key
    elif o == "--extra_apex_payload_key":
      apex_name, key = a.split("=")
      OPTIONS.extra_apex_payload_keys[apex_name] = key
    elif o == "--skip_apks_with_path_prefix":
      # Sanity check the prefix, which must be in all upper case.
      prefix = a.split('/')[0]
      if not prefix or prefix != prefix.upper():
        raise ValueError("Invalid path prefix '%s'" % (a,))
      OPTIONS.skip_apks_with_path_prefix.add(a)
    elif o in ("-d", "--default_key_mappings"):
      key_mapping_options.append((None, a))
    elif o in ("-k", "--key_mapping"):
      key_mapping_options.append(a.split("=", 1))
    elif o in ("-o", "--replace_ota_keys"):
      OPTIONS.replace_ota_keys = True
    elif o in ("-t", "--tag_changes"):
      new = []
      for i in a.split(","):
        i = i.strip()
        if not i or i[0] not in "-+":
          raise ValueError("Bad tag change '%s'" % (i,))
        new.append(i[0] + i[1:].strip())
      OPTIONS.tag_changes = tuple(new)
    elif o == "--replace_verity_public_key":
      OPTIONS.replace_verity_public_key = (True, a)
    elif o == "--replace_verity_private_key":
      OPTIONS.replace_verity_private_key = (True, a)
    elif o == "--replace_verity_keyid":
      OPTIONS.replace_verity_keyid = (True, a)
    elif o == "--avb_vbmeta_key":
      OPTIONS.avb_keys['vbmeta'] = a
    elif o == "--avb_vbmeta_algorithm":
      OPTIONS.avb_algorithms['vbmeta'] = a
    elif o == "--avb_vbmeta_extra_args":
      OPTIONS.avb_extra_args['vbmeta'] = a
    elif o == "--avb_boot_key":
      OPTIONS.avb_keys['boot'] = a
    elif o == "--avb_boot_algorithm":
      OPTIONS.avb_algorithms['boot'] = a
    elif o == "--avb_boot_extra_args":
      OPTIONS.avb_extra_args['boot'] = a
    elif o == "--avb_dtbo_key":
      OPTIONS.avb_keys['dtbo'] = a
    elif o == "--avb_dtbo_algorithm":
      OPTIONS.avb_algorithms['dtbo'] = a
    elif o == "--avb_dtbo_extra_args":
      OPTIONS.avb_extra_args['dtbo'] = a
    elif o == "--avb_system_key":
      OPTIONS.avb_keys['system'] = a
    elif o == "--avb_system_algorithm":
      OPTIONS.avb_algorithms['system'] = a
    elif o == "--avb_system_extra_args":
      OPTIONS.avb_extra_args['system'] = a
    elif o == "--avb_system_other_key":
      OPTIONS.avb_keys['system_other'] = a
    elif o == "--avb_system_other_algorithm":
      OPTIONS.avb_algorithms['system_other'] = a
    elif o == "--avb_system_other_extra_args":
      OPTIONS.avb_extra_args['system_other'] = a
    elif o == "--avb_vendor_key":
      OPTIONS.avb_keys['vendor'] = a
    elif o == "--avb_vendor_algorithm":
      OPTIONS.avb_algorithms['vendor'] = a
    elif o == "--avb_vendor_extra_args":
      OPTIONS.avb_extra_args['vendor'] = a
    elif o == "--avb_vbmeta_system_key":
      OPTIONS.avb_keys['vbmeta_system'] = a
    elif o == "--avb_vbmeta_system_algorithm":
      OPTIONS.avb_algorithms['vbmeta_system'] = a
    elif o == "--avb_vbmeta_system_extra_args":
      OPTIONS.avb_extra_args['vbmeta_system'] = a
    elif o == "--avb_vbmeta_vendor_key":
      OPTIONS.avb_keys['vbmeta_vendor'] = a
    elif o == "--avb_vbmeta_vendor_algorithm":
      OPTIONS.avb_algorithms['vbmeta_vendor'] = a
    elif o == "--avb_vbmeta_vendor_extra_args":
      OPTIONS.avb_extra_args['vbmeta_vendor'] = a
    elif o == "--avb_apex_extra_args":
      OPTIONS.avb_extra_args['apex'] = a
    else:
      return False
    return True

  args = common.ParseOptions(
      argv, __doc__,
      extra_opts="e:d:k:ot:",
      extra_long_opts=[
          "extra_apks=",
          "extra_apex_payload_key=",
          "skip_apks_with_path_prefix=",
          "default_key_mappings=",
          "key_mapping=",
          "replace_ota_keys",
          "tag_changes=",
          "replace_verity_public_key=",
          "replace_verity_private_key=",
          "replace_verity_keyid=",
          "avb_apex_extra_args=",
          "avb_vbmeta_algorithm=",
          "avb_vbmeta_key=",
          "avb_vbmeta_extra_args=",
          "avb_boot_algorithm=",
          "avb_boot_key=",
          "avb_boot_extra_args=",
          "avb_dtbo_algorithm=",
          "avb_dtbo_key=",
          "avb_dtbo_extra_args=",
          "avb_system_algorithm=",
          "avb_system_key=",
          "avb_system_extra_args=",
          "avb_system_other_algorithm=",
          "avb_system_other_key=",
          "avb_system_other_extra_args=",
          "avb_vendor_algorithm=",
          "avb_vendor_key=",
          "avb_vendor_extra_args=",
          "avb_vbmeta_system_algorithm=",
          "avb_vbmeta_system_key=",
          "avb_vbmeta_system_extra_args=",
          "avb_vbmeta_vendor_algorithm=",
          "avb_vbmeta_vendor_key=",
          "avb_vbmeta_vendor_extra_args=",
      ],
      extra_option_handler=option_handler)

  if len(args) != 2:
    common.Usage(__doc__)
    sys.exit(1)

  common.InitLogging()

  input_zip = zipfile.ZipFile(args[0], "r")
  output_zip = zipfile.ZipFile(args[1], "w",
                               compression=zipfile.ZIP_DEFLATED,
                               allowZip64=True)

  misc_info = common.LoadInfoDict(input_zip)

  BuildKeyMap(misc_info, key_mapping_options)

  apk_keys_info, compressed_extension = common.ReadApkCerts(input_zip)
  apk_keys = GetApkCerts(apk_keys_info)

  apex_keys_info = ReadApexKeysInfo(input_zip)
  apex_keys = GetApexKeys(apex_keys_info, apk_keys)

  CheckApkAndApexKeysAvailable(
      input_zip,
      set(apk_keys.keys()) | set(apex_keys.keys()),
      compressed_extension,
      apex_keys)

  key_passwords = common.GetKeyPasswords(
      set(apk_keys.values()) | set(itertools.chain(*apex_keys.values())))
  platform_api_level, _ = GetApiLevelAndCodename(input_zip)
  codename_to_api_level_map = GetCodenameToApiLevelMap(input_zip)

  ProcessTargetFiles(input_zip, output_zip, misc_info,
                     apk_keys, apex_keys, key_passwords,
                     platform_api_level, codename_to_api_level_map,
                     compressed_extension)

  common.ZipClose(input_zip)
  common.ZipClose(output_zip)

  # Skip building userdata.img and cache.img when signing the target files.
  new_args = ["--is_signing"]
  # add_img_to_target_files builds the system image from scratch, so the
  # recovery patch is guaranteed to be regenerated there.
  if OPTIONS.rebuild_recovery:
    new_args.append("--rebuild_recovery")
  new_args.append(args[1])
  add_img_to_target_files.main(new_args)

  print("done.")
Пример #7
0
def main(argv):

  options = {}

  def option_handler(o, a):
    if o == '--avbtool':
      options['avbtool'] = a
    elif o == '--container_key':
      # Strip the suffix if any, as common.SignFile expects no suffix.
      DEFAULT_CONTAINER_KEY_SUFFIX = '.x509.pem'
      if a.endswith(DEFAULT_CONTAINER_KEY_SUFFIX):
        a = a[:-len(DEFAULT_CONTAINER_KEY_SUFFIX)]
      options['container_key'] = a
    elif o == '--payload_key':
      options['payload_key'] = a
    elif o == '--payload_extra_args':
      options['payload_extra_args'] = a
    elif o == '--codename_to_api_level_map':
      versions = a.split(",")
      for v in versions:
        key, value = v.split(":")
        if 'codename_to_api_level_map' not in options:
          options['codename_to_api_level_map'] = {}
        options['codename_to_api_level_map'].update({key: value})
    elif o in ("-e", "--extra_apks"):
      names, key = a.split("=")
      names = names.split(",")
      for n in names:
        if 'extra_apks' not in options:
          options['extra_apks'] = {}
        options['extra_apks'].update({n: key})
    elif o == '--sign_tool':
      options['sign_tool'] = a
    else:
      return False
    return True

  args = common.ParseOptions(
      argv, __doc__,
      extra_opts='e:',
      extra_long_opts=[
          'avbtool=',
          'codename_to_api_level_map=',
          'container_key=',
          'payload_extra_args=',
          'payload_key=',
          'extra_apks=',
          'sign_tool=',
      ],
      extra_option_handler=option_handler)

  if (len(args) != 2 or 'container_key' not in options or
      'payload_key' not in options):
    common.Usage(__doc__)
    sys.exit(1)

  common.InitLogging()

  signed_apex = SignApexFile(
      options.get('avbtool', 'avbtool'),
      args[0],
      options['payload_key'],
      options['container_key'],
      no_hashtree=False,
      apk_keys=options.get('extra_apks', {}),
      signing_args=options.get('payload_extra_args'),
      codename_to_api_level_map=options.get(
          'codename_to_api_level_map', {}),
      sign_tool=options.get('sign_tool', None))
  shutil.copyfile(signed_apex, args[1])
  logger.info("done.")
Пример #8
0
def main(argv):
    bootable_only = [False]

    def option_handler(o, a):
        if o in ("-z", "--bootable_zip"):
            bootable_only[0] = True
        else:
            return False
        return True

    args = common.ParseOptions(argv,
                               __doc__,
                               extra_opts="z",
                               extra_long_opts=["bootable_zip"],
                               extra_option_handler=option_handler)

    bootable_only = bootable_only[0]

    if len(args) != 2:
        common.Usage(__doc__)
        sys.exit(1)

    OPTIONS.input_tmp, input_zip = common.UnzipTemp(args[0])
    output_zip = zipfile.ZipFile(args[1],
                                 "w",
                                 compression=zipfile.ZIP_DEFLATED,
                                 allowZip64=True)
    CopyInfo(output_zip)

    try:
        done = False
        images_path = os.path.join(OPTIONS.input_tmp, "IMAGES")
        if os.path.exists(images_path):
            # If this is a new target-files, it already contains the images,
            # and all we have to do is copy them to the output zip.
            images = os.listdir(images_path)
            if images:
                for i in images:
                    if bootable_only and i not in ("boot.img", "recovery.img"):
                        continue
                    if not i.endswith(".img"): continue
                    with open(os.path.join(images_path, i), "r") as f:
                        common.ZipWriteStr(output_zip, i, f.read())
                done = True

        if not done:
            # We have an old target-files that doesn't already contain the
            # images, so build them.
            import add_img_to_target_files

            OPTIONS.info_dict = common.LoadInfoDict(input_zip)

            # If this image was originally labelled with SELinux contexts,
            # make sure we also apply the labels in our new image. During
            # building, the "file_contexts" is in the out/ directory tree,
            # but for repacking from target-files.zip it's in the root
            # directory of the ramdisk.
            if "selinux_fc" in OPTIONS.info_dict:
                OPTIONS.info_dict["selinux_fc"] = os.path.join(
                    OPTIONS.input_tmp, "BOOT", "RAMDISK", "file_contexts")

            boot_image = common.GetBootableImage("boot.img", "boot.img",
                                                 OPTIONS.input_tmp, "BOOT")
            if boot_image:
                boot_image.AddToZip(output_zip)
            recovery_image = common.GetBootableImage("recovery.img",
                                                     "recovery.img",
                                                     OPTIONS.input_tmp,
                                                     "RECOVERY")
            if recovery_image:
                recovery_image.AddToZip(output_zip)

            def banner(s):
                print "\n\n++++ " + s + " ++++\n\n"

            if not bootable_only:
                banner("AddSystem")
                add_img_to_target_files.AddSystem(output_zip, prefix="")
                try:
                    input_zip.getinfo("VENDOR/")
                    banner("AddVendor")
                    add_img_to_target_files.AddVendor(output_zip, prefix="")
                except KeyError:
                    pass  # no vendor partition for this device
                try:
                    input_zip.getinfo("CUSTOM/")
                    banner("AddCustom")
                    add_img_to_target_files.AddCustom(output_zip, prefix="")
                except KeyError:
                    pass  # no custom partition for this device
                banner("AddUserdata")
                add_img_to_target_files.AddUserdata(output_zip, prefix="")
                banner("AddCache")
                add_img_to_target_files.AddCache(output_zip, prefix="")

    finally:
        print "cleaning up..."
        output_zip.close()
        shutil.rmtree(OPTIONS.input_tmp)

    print "done."
Пример #9
0
def main(argv):

    key_mapping_options = []

    def option_handler(o, a):
        if o in ("-e", "--extra_apks"):
            names, key = a.split("=")
            names = names.split(",")
            for n in names:
                OPTIONS.extra_apks[n] = key
        elif o in ("-d", "--default_key_mappings"):
            key_mapping_options.append((None, a))
        elif o in ("-k", "--key_mapping"):
            key_mapping_options.append(a.split("=", 1))
        elif o in ("-o", "--replace_ota_keys"):
            OPTIONS.replace_ota_keys = True
        elif o in ("-t", "--tag_changes"):
            new = []
            for i in a.split(","):
                i = i.strip()
                if not i or i[0] not in "-+":
                    raise ValueError("Bad tag change '%s'" % (i, ))
                new.append(i[0] + i[1:].strip())
            OPTIONS.tag_changes = tuple(new)
        elif o == "--replace_verity_public_key":
            OPTIONS.replace_verity_public_key = (True, a)
        elif o == "--replace_verity_private_key":
            OPTIONS.replace_verity_private_key = (True, a)
        else:
            return False
        return True

    args = common.ParseOptions(argv,
                               __doc__,
                               extra_opts="e:d:k:ot:",
                               extra_long_opts=[
                                   "extra_apks=", "default_key_mappings=",
                                   "key_mapping=", "replace_ota_keys",
                                   "tag_changes=",
                                   "replace_verity_public_key=",
                                   "replace_verity_private_key="
                               ],
                               extra_option_handler=option_handler)

    if len(args) != 2:
        common.Usage(__doc__)
        sys.exit(1)

    input_zip = zipfile.ZipFile(args[0], "r")
    output_zip = zipfile.ZipFile(args[1], "w")

    misc_info = common.LoadInfoDict(input_zip)

    BuildKeyMap(misc_info, key_mapping_options)

    apk_key_map = GetApkCerts(input_zip)
    CheckAllApksSigned(input_zip, apk_key_map)

    key_passwords = common.GetKeyPasswords(set(apk_key_map.values()))
    ProcessTargetFiles(input_zip, output_zip, misc_info, apk_key_map,
                       key_passwords)

    common.ZipClose(input_zip)
    common.ZipClose(output_zip)

    add_img_to_target_files.AddImagesToTargetFiles(args[1],
                                                   rebuild_recovery=True)

    print("done.")
Пример #10
0
def main():
    """The main function.

  Process command line arguments, then call merge_target_files to
  perform the heavy lifting.
  """

    common.InitLogging()

    def option_handler(o, a):
        if o == '--system-target-files':
            OPTIONS.system_target_files = a
        elif o == '--system-item-list':
            OPTIONS.system_item_list = a
        elif o == '--system-misc-info-keys':
            OPTIONS.system_misc_info_keys = a
        elif o == '--other-target-files':
            OPTIONS.other_target_files = a
        elif o == '--other-item-list':
            OPTIONS.other_item_list = a
        elif o == '--output-target-files':
            OPTIONS.output_target_files = a
        elif o == '--output-dir':
            OPTIONS.output_dir = a
        elif o == '--output-item-list':
            OPTIONS.output_item_list = a
        elif o == '--output-ota':
            OPTIONS.output_ota = a
        elif o == '--output-img':
            OPTIONS.output_img = a
        elif o == '--output-super-empty':
            OPTIONS.output_super_empty = a
        elif o == '--rebuild_recovery':
            OPTIONS.rebuild_recovery = True
        elif o == '--keep-tmp':
            OPTIONS.keep_tmp = True
        else:
            return False
        return True

    args = common.ParseOptions(sys.argv[1:],
                               __doc__,
                               extra_long_opts=[
                                   'system-target-files=',
                                   'system-item-list=',
                                   'system-misc-info-keys=',
                                   'other-target-files=',
                                   'other-item-list=',
                                   'output-target-files=',
                                   'output-dir=',
                                   'output-item-list=',
                                   'output-ota=',
                                   'output-img=',
                                   'output-super-empty=',
                                   'rebuild_recovery',
                                   'keep-tmp',
                               ],
                               extra_option_handler=option_handler)

    if (args or OPTIONS.system_target_files is None
            or OPTIONS.other_target_files is None or
        (OPTIONS.output_target_files is None and OPTIONS.output_dir is None) or
        (OPTIONS.output_dir is not None and OPTIONS.output_item_list is None)):
        common.Usage(__doc__)
        sys.exit(1)

    if OPTIONS.system_item_list:
        system_item_list = read_config_list(OPTIONS.system_item_list)
    else:
        system_item_list = default_system_item_list

    if OPTIONS.system_misc_info_keys:
        system_misc_info_keys = read_config_list(OPTIONS.system_misc_info_keys)
    else:
        system_misc_info_keys = default_system_misc_info_keys

    if OPTIONS.other_item_list:
        other_item_list = read_config_list(OPTIONS.other_item_list)
    else:
        other_item_list = default_other_item_list

    if OPTIONS.output_item_list:
        output_item_list = read_config_list(OPTIONS.output_item_list)
    else:
        output_item_list = None

    if not validate_config_lists(system_item_list=system_item_list,
                                 system_misc_info_keys=system_misc_info_keys,
                                 other_item_list=other_item_list):
        sys.exit(1)

    call_func_with_temp_dir(
        lambda temp_dir: merge_target_files(
            temp_dir=temp_dir,
            system_target_files=OPTIONS.system_target_files,
            system_item_list=system_item_list,
            system_misc_info_keys=system_misc_info_keys,
            other_target_files=OPTIONS.other_target_files,
            other_item_list=other_item_list,
            output_target_files=OPTIONS.output_target_files,
            output_dir=OPTIONS.output_dir,
            output_item_list=output_item_list,
            output_ota=OPTIONS.output_ota,
            output_img=OPTIONS.output_img,
            output_super_empty=OPTIONS.output_super_empty,
            rebuild_recovery=OPTIONS.rebuild_recovery), OPTIONS.keep_tmp)
Пример #11
0
def main(argv):
    def option_handler(o, a):
        if o in ("-k", "--package_key"):
            OPTIONS.package_key = a
        elif o in ("-i", "--incremental_from"):
            OPTIONS.incremental_source = a
        elif o == "--full_radio":
            OPTIONS.full_radio = True
        elif o == "--full_bootloader":
            OPTIONS.full_bootloader = True
        elif o == "--wipe_user_data":
            OPTIONS.wipe_user_data = True
        elif o == "--downgrade":
            OPTIONS.downgrade = True
            OPTIONS.wipe_user_data = True
        elif o == "--override_timestamp":
            OPTIONS.downgrade = True
        elif o in ("-o", "--oem_settings"):
            OPTIONS.oem_source = a.split(',')
        elif o == "--oem_no_mount":
            OPTIONS.oem_no_mount = True
        elif o in ("-e", "--extra_script"):
            OPTIONS.extra_script = a
        elif o in ("-t", "--worker_threads"):
            if a.isdigit():
                OPTIONS.worker_threads = int(a)
            else:
                raise ValueError("Cannot parse value %r for option %r - only "
                                 "integers are allowed." % (a, o))
        elif o in ("-2", "--two_step"):
            OPTIONS.two_step = True
        elif o == "--include_secondary":
            OPTIONS.include_secondary = True
        elif o == "--no_signing":
            OPTIONS.no_signing = True
        elif o == "--verify":
            OPTIONS.verify = True
        elif o == "--block":
            OPTIONS.block_based = True
        elif o in ("-b", "--binary"):
            OPTIONS.updater_binary = a
        elif o == "--stash_threshold":
            try:
                OPTIONS.stash_threshold = float(a)
            except ValueError:
                raise ValueError(
                    "Cannot parse value %r for option %r - expecting "
                    "a float" % (a, o))
        elif o == "--log_diff":
            OPTIONS.log_diff = a
        elif o == "--payload_signer":
            OPTIONS.payload_signer = a
        elif o == "--payload_signer_args":
            OPTIONS.payload_signer_args = shlex.split(a)
        elif o == "--payload_signer_maximum_signature_size":
            OPTIONS.payload_signer_maximum_signature_size = a
        elif o == "--payload_signer_key_size":
            # TODO(Xunchang) remove this option after cleaning up the callers.
            logger.warning(
                "The option '--payload_signer_key_size' is deprecated."
                " Use '--payload_signer_maximum_signature_size' instead.")
            OPTIONS.payload_signer_maximum_signature_size = a
        elif o == "--extracted_input_target_files":
            OPTIONS.extracted_input = a
        elif o == "--skip_postinstall":
            OPTIONS.skip_postinstall = True
        elif o == "--retrofit_dynamic_partitions":
            OPTIONS.retrofit_dynamic_partitions = True
        elif o == "--skip_compatibility_check":
            OPTIONS.skip_compatibility_check = True
        elif o == "--output_metadata_path":
            OPTIONS.output_metadata_path = a
        elif o == "--disable_fec_computation":
            OPTIONS.disable_fec_computation = True
        elif o == "--force_non_ab":
            OPTIONS.force_non_ab = True
        elif o == "--boot_variable_file":
            OPTIONS.boot_variable_file = a
        else:
            return False
        return True

    args = common.ParseOptions(argv,
                               __doc__,
                               extra_opts="b:k:i:d:e:t:2o:",
                               extra_long_opts=[
                                   "package_key=",
                                   "incremental_from=",
                                   "full_radio",
                                   "full_bootloader",
                                   "wipe_user_data",
                                   "downgrade",
                                   "override_timestamp",
                                   "extra_script=",
                                   "worker_threads=",
                                   "two_step",
                                   "include_secondary",
                                   "no_signing",
                                   "block",
                                   "binary=",
                                   "oem_settings=",
                                   "oem_no_mount",
                                   "verify",
                                   "stash_threshold=",
                                   "log_diff=",
                                   "payload_signer=",
                                   "payload_signer_args=",
                                   "payload_signer_maximum_signature_size=",
                                   "payload_signer_key_size=",
                                   "extracted_input_target_files=",
                                   "skip_postinstall",
                                   "retrofit_dynamic_partitions",
                                   "skip_compatibility_check",
                                   "output_metadata_path=",
                                   "disable_fec_computation",
                                   "force_non_ab",
                                   "boot_variable_file=",
                               ],
                               extra_option_handler=option_handler)

    if len(args) != 2:
        common.Usage(__doc__)
        sys.exit(1)

    common.InitLogging()

    if OPTIONS.downgrade:
        # We should only allow downgrading incrementals (as opposed to full).
        # Otherwise the device may go back from arbitrary build with this full
        # OTA package.
        if OPTIONS.incremental_source is None:
            raise ValueError("Cannot generate downgradable full OTAs")

    # Load the build info dicts from the zip directly or the extracted input
    # directory. We don't need to unzip the entire target-files zips, because they
    # won't be needed for A/B OTAs (brillo_update_payload does that on its own).
    # When loading the info dicts, we don't need to provide the second parameter
    # to common.LoadInfoDict(). Specifying the second parameter allows replacing
    # some properties with their actual paths, such as 'selinux_fc',
    # 'ramdisk_dir', which won't be used during OTA generation.
    if OPTIONS.extracted_input is not None:
        OPTIONS.info_dict = common.LoadInfoDict(OPTIONS.extracted_input)
    else:
        with zipfile.ZipFile(args[0], 'r') as input_zip:
            OPTIONS.info_dict = common.LoadInfoDict(input_zip)

    logger.info("--- target info ---")
    common.DumpInfoDict(OPTIONS.info_dict)

    # Load the source build dict if applicable.
    if OPTIONS.incremental_source is not None:
        OPTIONS.target_info_dict = OPTIONS.info_dict
        with zipfile.ZipFile(OPTIONS.incremental_source, 'r') as source_zip:
            OPTIONS.source_info_dict = common.LoadInfoDict(source_zip)

        logger.info("--- source info ---")
        common.DumpInfoDict(OPTIONS.source_info_dict)

    # Load OEM dicts if provided.
    OPTIONS.oem_dicts = _LoadOemDicts(OPTIONS.oem_source)

    # Assume retrofitting dynamic partitions when base build does not set
    # use_dynamic_partitions but target build does.
    if (OPTIONS.source_info_dict and
            OPTIONS.source_info_dict.get("use_dynamic_partitions") != "true"
            and OPTIONS.target_info_dict.get("use_dynamic_partitions")
            == "true"):
        if OPTIONS.target_info_dict.get(
                "dynamic_partition_retrofit") != "true":
            raise common.ExternalError(
                "Expect to generate incremental OTA for retrofitting dynamic "
                "partitions, but dynamic_partition_retrofit is not set in target "
                "build.")
        logger.info("Implicitly generating retrofit incremental OTA.")
        OPTIONS.retrofit_dynamic_partitions = True

    # Skip postinstall for retrofitting dynamic partitions.
    if OPTIONS.retrofit_dynamic_partitions:
        OPTIONS.skip_postinstall = True

    ab_update = OPTIONS.info_dict.get("ab_update") == "true"
    allow_non_ab = OPTIONS.info_dict.get("allow_non_ab") == "true"
    if OPTIONS.force_non_ab:
        assert allow_non_ab, "--force_non_ab only allowed on devices that supports non-A/B"
        assert ab_update, "--force_non_ab only allowed on A/B devices"

    generate_ab = not OPTIONS.force_non_ab and ab_update

    # Use the default key to sign the package if not specified with package_key.
    # package_keys are needed on ab_updates, so always define them if an
    # A/B update is getting created.
    if not OPTIONS.no_signing or generate_ab:
        if OPTIONS.package_key is None:
            OPTIONS.package_key = OPTIONS.info_dict.get(
                "default_system_dev_certificate",
                "build/make/target/product/security/testkey")
        # Get signing keys
        OPTIONS.key_passwords = common.GetKeyPasswords([OPTIONS.package_key])

    if generate_ab:
        GenerateAbOtaPackage(target_file=args[0],
                             output_file=args[1],
                             source_file=OPTIONS.incremental_source)

    else:
        GenerateNonAbOtaPackage(target_file=args[0],
                                output_file=args[1],
                                source_file=OPTIONS.incremental_source)

    # Post OTA generation works.
    if OPTIONS.incremental_source is not None and OPTIONS.log_diff:
        logger.info("Generating diff logs...")
        logger.info("Unzipping target-files for diffing...")
        target_dir = common.UnzipTemp(args[0], TARGET_DIFFING_UNZIP_PATTERN)
        source_dir = common.UnzipTemp(OPTIONS.incremental_source,
                                      TARGET_DIFFING_UNZIP_PATTERN)

        with open(OPTIONS.log_diff, 'w') as out_file:
            target_files_diff.recursiveDiff('', source_dir, target_dir,
                                            out_file)

    logger.info("done.")
Пример #12
0
    return True

  args = common.ParseOptions(argv, __doc__,
                             extra_opts="e:d:k:ot:",
                             extra_long_opts=["extra_apks=",
                                              "default_key_mappings=",
                                              "key_mapping=",
                                              "replace_ota_keys",
                                              "tag_changes=",
                                              "replace_verity_public_key=",
                                              "replace_verity_private_key=",
                                              "replace_verity_keyid="],
                             extra_option_handler=option_handler)

  if len(args) != 2:
    common.Usage(__doc__)
    sys.exit(1)

  input_zip = zipfile.ZipFile(args[0], "r")
  output_zip = zipfile.ZipFile(args[1], "w")

  misc_info = common.LoadInfoDict(input_zip)

  BuildKeyMap(misc_info, key_mapping_options)

  apk_key_map = GetApkCerts(input_zip)
  CheckAllApksSigned(input_zip, apk_key_map)

  key_passwords = common.GetKeyPasswords(set(apk_key_map.values()))
  platform_api_level, platform_codename = GetApiLevelAndCodename(input_zip)
  codename_to_api_level_map = GetCodenameToApiLevelMap(input_zip)
Пример #13
0
def main(argv):
    def option_handler(o, a):
        if o in ("-c", "--compare_with"):
            OPTIONS.compare_with = a
        elif o in ("-l", "--local_cert_dirs"):
            OPTIONS.local_cert_dirs = [i.strip() for i in a.split(",")]
        elif o in ("-t", "--text"):
            OPTIONS.text = True
        else:
            return False
        return True

    args = common.ParseOptions(
        argv,
        __doc__,
        extra_opts="c:l:t",
        extra_long_opts=["compare_with=", "local_cert_dirs="],
        extra_option_handler=option_handler)

    if len(args) != 1:
        common.Usage(__doc__)
        sys.exit(1)

    common.InitLogging()

    ALL_CERTS.FindLocalCerts()

    Push("input target_files:")
    try:
        target_files = TargetFiles()
        target_files.LoadZipFile(args[0])
    finally:
        Pop()

    compare_files = None
    if OPTIONS.compare_with:
        Push("comparison target_files:")
        try:
            compare_files = TargetFiles()
            compare_files.LoadZipFile(OPTIONS.compare_with)
        finally:
            Pop()

    if OPTIONS.text or not compare_files:
        Banner("target files")
        target_files.PrintCerts()
    target_files.CheckSharedUids()
    target_files.CheckExternalSignatures()
    if compare_files:
        if OPTIONS.text:
            Banner("comparison files")
            compare_files.PrintCerts()
        target_files.CompareWith(compare_files)

    if PROBLEMS:
        print "%d problem(s) found:\n" % (len(PROBLEMS), )
        for p in PROBLEMS:
            print p
        return 1

    return 0
Пример #14
0
def main():
    """The main function.

  Process command line arguments, then call merge_target_files to
  perform the heavy lifting.
  """

    common.InitLogging()

    def option_handler(o, a):
        if o == '--system-target-files':
            OPTIONS.system_target_files = a
        elif o == '--system-item-list':
            OPTIONS.system_item_list = a
        elif o == '--system-misc-info-keys':
            OPTIONS.system_misc_info_keys = a
        elif o == '--other-target-files':
            OPTIONS.other_target_files = a
        elif o == '--other-item-list':
            OPTIONS.other_item_list = a
        elif o == '--output-target-files':
            OPTIONS.output_target_files = a
        elif o == '--keep_tmp':
            OPTIONS.keep_tmp = True
        else:
            return False
        return True

    args = common.ParseOptions(sys.argv[1:],
                               __doc__,
                               extra_long_opts=[
                                   'system-target-files=',
                                   'system-item-list=',
                                   'system-misc-info-keys=',
                                   'other-target-files=',
                                   'other-item-list=',
                                   'output-target-files=',
                                   "keep_tmp",
                               ],
                               extra_option_handler=option_handler)

    if (len(args) != 0 or OPTIONS.system_target_files is None
            or OPTIONS.other_target_files is None
            or OPTIONS.output_target_files is None):
        common.Usage(__doc__)
        sys.exit(1)

    if OPTIONS.system_item_list:
        system_item_list = read_config_list(OPTIONS.system_item_list)
    else:
        system_item_list = default_system_item_list

    if OPTIONS.system_misc_info_keys:
        system_misc_info_keys = read_config_list(OPTIONS.system_misc_info_keys)
    else:
        system_misc_info_keys = default_system_misc_info_keys

    if OPTIONS.other_item_list:
        other_item_list = read_config_list(OPTIONS.other_item_list)
    else:
        other_item_list = default_other_item_list

    call_func_with_temp_dir(
        lambda temp_dir: merge_target_files(
            temp_dir=temp_dir,
            system_target_files=OPTIONS.system_target_files,
            system_item_list=system_item_list,
            system_misc_info_keys=system_misc_info_keys,
            other_target_files=OPTIONS.other_target_files,
            other_item_list=other_item_list,
            output_target_files=OPTIONS.output_target_files), OPTIONS.keep_tmp)
Пример #15
0
def main(argv):
    def option_handler(o, a):
        if o in ("-b", "--board_config"):
            pass  # deprecated
        elif o in ("-k", "--package_key"):
            OPTIONS.package_key = a
        elif o in ("-i", "--incremental_from"):
            OPTIONS.incremental_source = a
        elif o in ("-w", "--wipe_user_data"):
            OPTIONS.wipe_user_data = True
        elif o in ("-n", "--no_prereq"):
            OPTIONS.omit_prereq = True
        elif o in ("-e", "--extra_script"):
            OPTIONS.extra_script = a
        elif o in ("-a", "--aslr_mode"):
            if a in ("on", "On", "true", "True", "yes", "Yes"):
                OPTIONS.aslr_mode = True
            else:
                OPTIONS.aslr_mode = False
        elif o in ("--worker_threads"):
            OPTIONS.worker_threads = int(a)
        elif o in ("--backup"):
            OPTIONS.backuptool = bool(a.lower() == 'true')
        elif o in ("--override_device"):
            OPTIONS.override_device = a
        elif o in ("--override_prop"):
            OPTIONS.override_prop = bool(a.lower() == 'true')
        else:
            return False
        return True

    args = common.ParseOptions(argv,
                               __doc__,
                               extra_opts="b:k:i:d:wne:a:",
                               extra_long_opts=[
                                   "board_config=", "package_key=",
                                   "incremental_from=", "wipe_user_data",
                                   "no_prereq", "extra_script=",
                                   "worker_threads=", "aslr_mode=", "backup=",
                                   "override_device=", "override_prop="
                               ],
                               extra_option_handler=option_handler)

    if len(args) < 2:
        common.Usage(__doc__)
        sys.exit(1)

    for arg in args[2:]:
        OPTIONS.require_verbatim.add(arg)
    print "OPTIONS.require_verbatim: %r" % OPTIONS.require_verbatim

    if OPTIONS.extra_script is not None:
        OPTIONS.extra_script = open(OPTIONS.extra_script).read()

    print "unzipping target target-files..."
    OPTIONS.input_tmp, input_zip = common.UnzipTemp(args[0])

    OPTIONS.target_tmp = OPTIONS.input_tmp
    OPTIONS.info_dict = common.LoadInfoDict(input_zip)

    # If this image was originally labelled with SELinux contexts, make sure we
    # also apply the labels in our new image. During building, the "file_contexts"
    # is in the out/ directory tree, but for repacking from target-files.zip it's
    # in the root directory of the ramdisk.
    if "selinux_fc" in OPTIONS.info_dict:
        OPTIONS.info_dict["selinux_fc"] = os.path.join(OPTIONS.input_tmp,
                                                       "BOOT", "RAMDISK",
                                                       "file_contexts")

    if OPTIONS.verbose:
        print "--- target info ---"
        common.DumpInfoDict(OPTIONS.info_dict)

    if OPTIONS.device_specific is None:
        OPTIONS.device_specific = OPTIONS.info_dict.get(
            "tool_extensions", None)
    if OPTIONS.device_specific is not None:
        OPTIONS.device_specific = os.path.normpath(OPTIONS.device_specific)
        print "using device-specific extensions in", OPTIONS.device_specific

    temp_zip_file = tempfile.NamedTemporaryFile()
    output_zip = zipfile.ZipFile(temp_zip_file,
                                 "w",
                                 compression=zipfile.ZIP_DEFLATED)

    if OPTIONS.incremental_source is None:
        WriteFullOTAPackage(input_zip, output_zip)
        if OPTIONS.package_key is None:
            OPTIONS.package_key = OPTIONS.info_dict.get(
                "default_system_dev_certificate",
                "build/target/product/security/testkey")
    else:
        print "unzipping source target-files..."
        OPTIONS.source_tmp, source_zip = common.UnzipTemp(
            OPTIONS.incremental_source)
        OPTIONS.target_info_dict = OPTIONS.info_dict
        OPTIONS.source_info_dict = common.LoadInfoDict(source_zip)
        if OPTIONS.package_key is None:
            OPTIONS.package_key = OPTIONS.source_info_dict.get(
                "default_system_dev_certificate",
                "build/target/product/security/testkey")
        if OPTIONS.verbose:
            print "--- source info ---"
            common.DumpInfoDict(OPTIONS.source_info_dict)
        WriteIncrementalOTAPackage(input_zip, source_zip, output_zip)

    output_zip.close()

    SignOutput(temp_zip_file.name, args[1])
    temp_zip_file.close()

    common.Cleanup()

    print "done."