Snap for 7183507 from 1bf1b4c3b17d3009c8e13979685bce563eaf2204 to sdk-release

Change-Id: I0ec70108f5cd2fa694925da10584de5da6458a3b
diff --git a/Android.bp b/Android.bp
index 113b5e6..60926e6 100644
--- a/Android.bp
+++ b/Android.bp
@@ -14,6 +14,37 @@
 // limitations under the License.
 //
 
+package {
+    default_applicable_licenses: ["external_avb_license"],
+}
+
+// Added automatically by a large-scale-change that took the approach of
+// 'apply every license found to every target'. While this makes sure we respect
+// every license restriction, it may not be entirely correct.
+//
+// e.g. GPL in an MIT project might only apply to the contrib/ directory.
+//
+// Please consider splitting the single license below into multiple licenses,
+// taking care not to lose any license_kind information, and overriding the
+// default license using the 'licenses: [...]' property on targets as needed.
+//
+// For unused files, consider creating a 'fileGroup' with "//visibility:private"
+// to attach the license to, and including a comment whether the files may be
+// used in the current project.
+// See: http://go/android-license-faq
+license {
+    name: "external_avb_license",
+    visibility: [":__subpackages__"],
+    license_kinds: [
+        "SPDX-license-identifier-Apache-2.0",
+        "SPDX-license-identifier-BSD",
+        "SPDX-license-identifier-MIT",
+    ],
+    license_text: [
+        "LICENSE",
+    ],
+}
+
 subdirs = [
     "test",
     "tools",
@@ -332,8 +363,15 @@
         "img2simg",
         "avbtool",
     ],
+    test_options: {
+        unit_test: true,
+    },
+    compile_multilib: "first",
     data: [
+        ":img2simg",
+        ":simg2img",
         "avbtool",
+        ":fec",
         "test/avbtool_signing_helper_test.py",
         "test/avbtool_signing_helper_with_files_test.py",
         "test/data/*",
diff --git a/README.md b/README.md
index 1f599c6..4a2bb72 100644
--- a/README.md
+++ b/README.md
@@ -404,6 +404,8 @@
         [--do_not_use_ab]                                                          \
         [--use_persistent_digest]
 
+Valid values for `HASH_ALG` above include `sha1` and `sha256`.
+
 An integrity footer containing the root digest and salt for a hashtree
 for a partition can be added to an existing image as follows. The
 hashtree is also appended to the image.
@@ -429,6 +431,8 @@
         [--no_hashtree]                                                            \
         [--use_persistent_digest]
 
+Valid values for `HASH_ALG` above include `sha1`, `sha256`, and `blake2b-256`.
+
 The size of an image with integrity footers can be changed using the
 `resize_image` command:
 
diff --git a/avbtool.py b/avbtool.py
index 1211df3..8647b29 100755
--- a/avbtool.py
+++ b/avbtool.py
@@ -642,6 +642,15 @@
   return True
 
 
+def create_avb_hashtree_hasher(algorithm, salt):
+  """Create the hasher for AVB hashtree based on the input algorithm."""
+
+  if algorithm.lower() == 'blake2b-256':
+    return hashlib.new('blake2b', salt, digest_size=32)
+
+  return hashlib.new(algorithm, salt)
+
+
 class ImageChunk(object):
   """Data structure used for representing chunks in Android sparse files.
 
@@ -1406,7 +1415,8 @@
       self.salt = data[(self.SIZE + o):(self.SIZE + o + salt_len)]
       o += salt_len
       self.root_digest = data[(self.SIZE + o):(self.SIZE + o + root_digest_len)]
-      if root_digest_len != len(hashlib.new(self.hash_algorithm).digest()):
+
+      if root_digest_len != self._hashtree_digest_size():
         if root_digest_len != 0:
           raise LookupError('root_digest_len doesn\'t match hash algorithm')
 
@@ -1426,6 +1436,9 @@
       self.root_digest = b''
       self.flags = 0
 
+  def _hashtree_digest_size(self):
+    return len(create_avb_hashtree_hasher(self.hash_algorithm, b'').digest())
+
   def print_desc(self, o):
     """Print the descriptor.
 
@@ -1496,7 +1509,7 @@
       image_filename = os.path.join(image_dir, self.partition_name + image_ext)
       image = ImageHandler(image_filename, read_only=True)
     # Generate the hashtree and checks that it matches what's in the file.
-    digest_size = len(hashlib.new(self.hash_algorithm).digest())
+    digest_size = self._hashtree_digest_size()
     digest_padding = round_to_pow2(digest_size) - digest_size
     (hash_level_offsets, tree_size) = calc_hash_level_offsets(
         self.image_size, self.data_block_size, digest_size + digest_padding)
@@ -3579,7 +3592,8 @@
       print('1.{}'.format(required_libavb_version_minor))
       return
 
-    digest_size = len(hashlib.new(hash_algorithm).digest())
+    digest_size = len(create_avb_hashtree_hasher(hash_algorithm, b'')
+                      .digest())
     digest_padding = round_to_pow2(digest_size) - digest_size
 
     # If |partition_size| is given (e.g. not 0), calculate the maximum image
@@ -4064,7 +4078,7 @@
     level_output_list = []
     remaining = hash_src_size
     while remaining > 0:
-      hasher = hashlib.new(hash_alg_name, salt)
+      hasher = create_avb_hashtree_hasher(hash_alg_name, salt)
       # Only read from the file for the first level - for subsequent
       # levels, access the array we're building.
       if level_num == 0:
@@ -4096,7 +4110,7 @@
     hash_src_size = len(level_output)
     level_num += 1
 
-  hasher = hashlib.new(hash_alg_name, salt)
+  hasher = create_avb_hashtree_hasher(hash_alg_name, salt)
   hasher.update(level_output)
   return hasher.digest(), bytes(hash_ret)
 
diff --git a/test/Android.bp b/test/Android.bp
index 057cd1e..a2dab37 100644
--- a/test/Android.bp
+++ b/test/Android.bp
@@ -14,6 +14,16 @@
 // limitations under the License.
 //
 
+package {
+    // See: http://go/android-license-faq
+    // A large-scale-change added 'default_applicable_licenses' to import
+    // all of the 'license_kinds' from "external_avb_license"
+    // to get the below license kinds:
+    //   SPDX-license-identifier-Apache-2.0
+    //   SPDX-license-identifier-MIT
+    default_applicable_licenses: ["external_avb_license"],
+}
+
 python_test_host {
     name: "at_auth_unlock_unittest",
     main: "at_auth_unlock_unittest.py",
diff --git a/test/avbtool_unittest.cc b/test/avbtool_unittest.cc
index 8749ea3..7fb89c4 100644
--- a/test/avbtool_unittest.cc
+++ b/test/avbtool_unittest.cc
@@ -53,6 +53,10 @@
   }
 
   void AddHashFooterTest(bool sparse_image);
+  void CreateRootfsWithHashtreeFooter(bool sparse_image,
+                                      const std::string& hash_algorithm,
+                                      const std::string& root_digest,
+                                      base::FilePath* rootfs_path);
   void AddHashtreeFooterTest(bool sparse_image);
   void AddHashtreeFooterFECTest(bool sparse_image);
 
@@ -934,7 +938,11 @@
       InfoImage(path));
 }
 
-void AvbToolTest::AddHashtreeFooterTest(bool sparse_image) {
+void AvbToolTest::CreateRootfsWithHashtreeFooter(
+    bool sparse_image,
+    const std::string& hash_algorithm,
+    const std::string& root_digest,
+    base::FilePath* output_rootfs_path) {
   const size_t rootfs_size = 1028 * 1024;
   const size_t partition_size = 1536 * 1024;
 
@@ -969,6 +977,7 @@
   for (int n = 0; n < 2; n++) {
     EXPECT_COMMAND(0,
                    "./avbtool add_hashtree_footer --salt d00df00d --image %s "
+                   "--hash_algorithm %s "
                    "--partition_size %d --partition_name foobar "
                    "--algorithm SHA256_RSA2048 "
                    "--key test/data/testkey_rsa2048.pem "
@@ -976,6 +985,7 @@
                    "--internal_release_string \"\" "
                    "--do_not_generate_fec",
                    rootfs_path.value().c_str(),
+                   hash_algorithm.c_str(),
                    (int)partition_size,
                    external_vbmeta_path.value().c_str());
 
@@ -1007,44 +1017,48 @@
                                  "      FEC num roots:         0\n"
                                  "      FEC offset:            0\n"
                                  "      FEC size:              0 bytes\n"
-                                 "      Hash Algorithm:        sha1\n"
+                                 "      Hash Algorithm:        %s\n"
                                  "      Partition Name:        foobar\n"
                                  "      Salt:                  d00df00d\n"
                                  "      Root Digest:           "
-                                 "e811611467dcd6e8dc4324e45f706c2bdd51db67\n"
+                                 "%s\n"
                                  "      Flags:                 0\n",
-                                 sparse_image ? " (Sparse)" : ""),
+                                 sparse_image ? " (Sparse)" : "",
+                                 hash_algorithm.c_str(),
+                                 root_digest.c_str()),
               InfoImage(rootfs_path));
 
-    ASSERT_EQ(
-        "Minimum libavb version:   1.0\n"
-        "Header Block:             256 bytes\n"
-        "Authentication Block:     320 bytes\n"
-        "Auxiliary Block:          768 bytes\n"
-        "Public key (sha1):        cdbb77177f731920bbe0a0f94f84d9038ae0617d\n"
-        "Algorithm:                SHA256_RSA2048\n"
-        "Rollback Index:           0\n"
-        "Flags:                    0\n"
-        "Rollback Index Location:  0\n"
-        "Release String:           ''\n"
-        "Descriptors:\n"
-        "    Hashtree descriptor:\n"
-        "      Version of dm-verity:  1\n"
-        "      Image Size:            1052672 bytes\n"
-        "      Tree Offset:           1052672\n"
-        "      Tree Size:             16384 bytes\n"
-        "      Data Block Size:       4096 bytes\n"
-        "      Hash Block Size:       4096 bytes\n"
-        "      FEC num roots:         0\n"
-        "      FEC offset:            0\n"
-        "      FEC size:              0 bytes\n"
-        "      Hash Algorithm:        sha1\n"
-        "      Partition Name:        foobar\n"
-        "      Salt:                  d00df00d\n"
-        "      Root Digest:           "
-        "e811611467dcd6e8dc4324e45f706c2bdd51db67\n"
-        "      Flags:                 0\n",
-        InfoImage(external_vbmeta_path));
+    ASSERT_EQ(base::StringPrintf("Minimum libavb version:   1.0\n"
+                                 "Header Block:             256 bytes\n"
+                                 "Authentication Block:     320 bytes\n"
+                                 "Auxiliary Block:          768 bytes\n"
+                                 "Public key (sha1):        "
+                                 "cdbb77177f731920bbe0a0f94f84d9038ae0617d\n"
+                                 "Algorithm:                SHA256_RSA2048\n"
+                                 "Rollback Index:           0\n"
+                                 "Flags:                    0\n"
+                                 "Rollback Index Location:  0\n"
+                                 "Release String:           ''\n"
+                                 "Descriptors:\n"
+                                 "    Hashtree descriptor:\n"
+                                 "      Version of dm-verity:  1\n"
+                                 "      Image Size:            1052672 bytes\n"
+                                 "      Tree Offset:           1052672\n"
+                                 "      Tree Size:             16384 bytes\n"
+                                 "      Data Block Size:       4096 bytes\n"
+                                 "      Hash Block Size:       4096 bytes\n"
+                                 "      FEC num roots:         0\n"
+                                 "      FEC offset:            0\n"
+                                 "      FEC size:              0 bytes\n"
+                                 "      Hash Algorithm:        %s\n"
+                                 "      Partition Name:        foobar\n"
+                                 "      Salt:                  d00df00d\n"
+                                 "      Root Digest:           "
+                                 "%s\n"
+                                 "      Flags:                 0\n",
+                                 hash_algorithm.c_str(),
+                                 root_digest.c_str()),
+              InfoImage(external_vbmeta_path));
 
     // Check that the extracted vbmeta matches the externally generally one.
     EXPECT_COMMAND(0,
@@ -1058,6 +1072,16 @@
                    extracted_vbmeta_path.value().c_str());
   }
 
+  *output_rootfs_path = rootfs_path;
+}
+
+void AvbToolTest::AddHashtreeFooterTest(bool sparse_image) {
+  base::FilePath rootfs_path;
+  CreateRootfsWithHashtreeFooter(sparse_image,
+                                 "sha1",
+                                 "e811611467dcd6e8dc4324e45f706c2bdd51db67",
+                                 &rootfs_path);
+
   /* Zero the hashtree on a copy of the image. */
   EXPECT_COMMAND(0,
                  "cp %s %s.zht",
@@ -1247,6 +1271,9 @@
   ASSERT_TRUE(base::GetFileSize(rootfs_path, &erased_footer_file_size));
   EXPECT_EQ(static_cast<size_t>(erased_footer_file_size), 1069056UL);
 
+  const size_t rootfs_size = 1028 * 1024;
+  const size_t partition_size = 1536 * 1024;
+  base::FilePath external_vbmeta_path = testdir_.Append("external_vbmeta.bin");
   // Check that --do_not_append_vbmeta_image works as intended.
   //
   // For this we need to reset the size of the image to the original
@@ -1281,6 +1308,15 @@
   AddHashtreeFooterTest(true);
 }
 
+TEST_F(AvbToolTest, AddHashtreeFooterSparseWithBlake2b256) {
+  base::FilePath rootfs_path;
+  CreateRootfsWithHashtreeFooter(
+      true,
+      "blake2b-256",
+      "9ed423dda921619181bf1889746fe2dd28ae1e673be8d802b4713122e3209513",
+      &rootfs_path);
+}
+
 void AvbToolTest::AddHashtreeFooterFECTest(bool sparse_image) {
   const size_t rootfs_size = 1028 * 1024;
   const size_t partition_size = 1536 * 1024;
diff --git a/tools/Android.bp b/tools/Android.bp
index a511fbb..cd705dc 100644
--- a/tools/Android.bp
+++ b/tools/Android.bp
@@ -14,6 +14,16 @@
 // limitations under the License.
 //
 
+package {
+    // See: http://go/android-license-faq
+    // A large-scale-change added 'default_applicable_licenses' to import
+    // all of the 'license_kinds' from "external_avb_license"
+    // to get the below license kinds:
+    //   SPDX-license-identifier-Apache-2.0
+    //   SPDX-license-identifier-MIT
+    default_applicable_licenses: ["external_avb_license"],
+}
+
 python_library_host {
     name: "at_auth_unlock",
     srcs: [