Donate to e Foundation | Murena handsets with /e/OS | Own a part of Murena! Learn more

Commit 51216556 authored by Tao Bao's avatar Tao Bao
Browse files

releasetools: Track edify function API changes.

In particular, it replaces the generated calls to edify function of
`apply_patch()` and `apply_patch_check()` with `patch_partition()` and
`patch_partition_check()` instead.

It adds two functions to EdifyGenerator: PatchPartition() and
PatchPartitionCheck() for Python releasetools callers. It also tries to
handle the callers of obsolete EdifyGenerator.PatchCheck() and
EdifyGenerator.ApplyPatch(), if their inputs are in known format.
Otherwise it raises an exception to avoid generating an OTA that updater
doesn't understand.

It requires the matching updater changes in the same topic.

Bug: 110106408
Test: Generate an incremental package with the new script and updater.
      Apply the package on device.
Test: Revert the change in ota_from_target_files.py, so that it calls
      the obsolete EdifyGenerator functions. Check that it generates the
      same incremental package.
Change-Id: Ifc55cb40d3a45116fd4d408536d037eca249effa
parent 04552fed
Loading
Loading
Loading
Loading
+61 −20
Original line number Diff line number Diff line
@@ -163,15 +163,32 @@ class EdifyGenerator(object):
    [0,1]."""
    self.script.append("set_progress(%f);" % (frac,))

  def PatchCheck(self, filename, *sha1):
    """Check that the given file has one of the
    given *sha1 hashes, checking the version saved in cache if the
    file does not match."""
    self.script.append(
        'apply_patch_check("%s"' % (filename,) +
        "".join([', "%s"' % (i,) for i in sha1]) +
        ') || abort("E%d: \\"%s\\" has unexpected contents.");' % (
            common.ErrorCode.BAD_PATCH_FILE, filename))
  def PatchCheck(self, filename, *sha1):  # pylint: disable=unused-argument
    """Checks that the given partition has the desired checksum.

    The call to this function is being deprecated in favor of
    PatchPartitionCheck(). It will try to parse and handle the old format,
    unless the format is unknown.
    """
    tokens = filename.split(':')
    assert len(tokens) == 6 and tokens[0] == 'EMMC', \
        "Failed to handle unknown format. Use PatchPartitionCheck() instead."
    source = '{}:{}:{}:{}'.format(tokens[0], tokens[1], tokens[2], tokens[3])
    target = '{}:{}:{}:{}'.format(tokens[0], tokens[1], tokens[4], tokens[5])
    self.PatchPartitionCheck(target, source)

  def PatchPartitionCheck(self, target, source):
    """Checks whether updater can patch the given partitions.

    It checks the checksums of the given partitions. If none of them matches the
    expected checksum, updater will additionally look for a backup on /cache.
    """
    self.script.append(self.WordWrap((
        'patch_partition_check("{target}",\0"{source}") ||\n    abort('
        '"E{code}: \\"{target}\\" or \\"{source}\\" has unexpected '
        'contents.");').format(
            target=target, source=source,
            code=common.ErrorCode.BAD_PATCH_FILE)))

  def CacheFreeSpaceCheck(self, amount):
    """Check that there's at least 'amount' space that can be made
@@ -251,17 +268,41 @@ class EdifyGenerator(object):
  def ApplyPatch(self, srcfile, tgtfile, tgtsize, tgtsha1, *patchpairs):
    """Apply binary patches (in *patchpairs) to the given srcfile to
    produce tgtfile (which may be "-" to indicate overwriting the
    source file."""
    if len(patchpairs) % 2 != 0 or len(patchpairs) == 0:
      raise ValueError("bad patches given to ApplyPatch")
    cmd = ['apply_patch("%s",\0"%s",\0%s,\0%d'
           % (srcfile, tgtfile, tgtsha1, tgtsize)]
    for i in range(0, len(patchpairs), 2):
      cmd.append(',\0%s,\0package_extract_file("%s")' % patchpairs[i:i+2])
    cmd.append(') ||\n    abort("E%d: Failed to apply patch to %s");' % (
        common.ErrorCode.APPLY_PATCH_FAILURE, srcfile))
    cmd_str = "".join(cmd)
    self.script.append(self.WordWrap(cmd_str))
    source file.

    This edify function is being deprecated in favor of PatchPartition(). It
    will try to redirect calls to PatchPartition() if possible. On unknown /
    invalid inputs, raises an exception.
    """
    tokens = srcfile.split(':')
    assert (len(tokens) == 6 and tokens[0] == 'EMMC' and tgtfile == '-' and
            len(patchpairs) == 2), \
        "Failed to handle unknown format. Use PatchPartition() instead."

    # Also sanity check the args.
    assert tokens[3] == patchpairs[0], \
        "Found mismatching values for source SHA-1: {} vs {}".format(
            tokens[3], patchpairs[0])
    assert int(tokens[4]) == tgtsize, \
        "Found mismatching values for target size: {} vs {}".format(
            tokens[4], tgtsize)
    assert tokens[5] == tgtsha1, \
        "Found mismatching values for target SHA-1: {} vs {}".format(
            tokens[5], tgtsha1)

    source = '{}:{}:{}:{}'.format(tokens[0], tokens[1], tokens[2], tokens[3])
    target = '{}:{}:{}:{}'.format(tokens[0], tokens[1], tokens[4], tokens[5])
    patch = patchpairs[1]
    self.PatchPartition(target, source, patch)

  def PatchPartition(self, target, source, patch):
    """Applies the patch to the source partition and writes it to target."""
    self.script.append(self.WordWrap((
        'patch_partition("{target}",\0"{source}",\0'
        'package_extract_file("{patch}")) ||\n'
        '    abort("E{code}: Failed to apply patch to {source}");').format(
            target=target, source=source, patch=patch,
            code=common.ErrorCode.APPLY_PATCH_FAILURE)))

  def WriteRawImage(self, mount_point, fn, mapfn=None):
    """Write the given package file into the partition for the given
+14 −19
Original line number Diff line number Diff line
@@ -1523,18 +1523,14 @@ else if get_stage("%(bcb_dev)s") != "3/3" then
      print("boot      target: %d  source: %d  diff: %d" % (
          target_boot.size, source_boot.size, len(d)))

      common.ZipWriteStr(output_zip, "patch/boot.img.p", d)

      # TODO(b/110106408): Remove after properly handling the SHA-1 embedded in
      # the filename argument in updater code. Prior to that, explicitly list
      # the SHA-1 of the source image, in case the updater tries to find a
      # matching backup from /cache. Similarly for the call to
      # script.ApplyPatch() below.
      script.PatchCheck("%s:%s:%d:%s:%d:%s" %
                        (boot_type, boot_device,
                         source_boot.size, source_boot.sha1,
                         target_boot.size, target_boot.sha1),
                        source_boot.sha1)
      common.ZipWriteStr(output_zip, "boot.img.p", d)

      script.PatchPartitionCheck(
          "{}:{}:{}:{}".format(
              boot_type, boot_device, target_boot.size, target_boot.sha1),
          "{}:{}:{}:{}".format(
              boot_type, boot_device, source_boot.size, source_boot.sha1))

      size.append(target_boot.size)

  if size:
@@ -1590,13 +1586,12 @@ else
        print("boot image changed; including patch.")
        script.Print("Patching boot image...")
        script.ShowProgress(0.1, 10)
        script.ApplyPatch("%s:%s:%d:%s:%d:%s"
                          % (boot_type, boot_device,
                             source_boot.size, source_boot.sha1,
                             target_boot.size, target_boot.sha1),
                          "-",
                          target_boot.size, target_boot.sha1,
                          source_boot.sha1, "patch/boot.img.p")
        script.PatchPartition(
            '{}:{}:{}:{}'.format(
                boot_type, boot_device, target_boot.size, target_boot.sha1),
            '{}:{}:{}:{}'.format(
                boot_type, boot_device, source_boot.size, source_boot.sha1),
            'boot.img.p')
    else:
      print("boot image unchanged; skipping.")