Merge "vm_shell: don't promt the selection if only one CID is available"
diff --git a/libs/apkverify/src/v3.rs b/libs/apkverify/src/v3.rs
index fcd966b..e1b728d 100644
--- a/libs/apkverify/src/v3.rs
+++ b/libs/apkverify/src/v3.rs
@@ -110,7 +110,7 @@
 ) -> Result<(Signer, ApkSections<R>)> {
     let mut sections = ApkSections::new(apk)?;
     let mut block = sections.find_signature(APK_SIGNATURE_SCHEME_V3_BLOCK_ID).context(
-        "Fallback to v2 when v3 block not found is not yet implemented. See b/197052981.",
+        "Fallback to v2 when v3 block not found is not yet implemented.", // b/197052981
     )?;
     let mut supported = block
         .read::<Signers>()?
@@ -135,7 +135,7 @@
             .iter()
             .filter(|sig| sig.signature_algorithm_id.map_or(false, |algo| algo.is_supported()))
             .max_by_key(|sig| sig.signature_algorithm_id.unwrap().content_digest_algorithm())
-            .context("No supported signatures found")?)
+            .context("No supported APK signatures found; DSA is not supported")?)
     }
 
     pub(crate) fn find_digest_by_algorithm(
diff --git a/libs/apkverify/tests/apkverify_test.rs b/libs/apkverify/tests/apkverify_test.rs
index 047538c..baf7c42 100644
--- a/libs/apkverify/tests/apkverify_test.rs
+++ b/libs/apkverify/tests/apkverify_test.rs
@@ -44,7 +44,7 @@
     for key_name in KEY_NAMES_DSA.iter() {
         let res = verify(format!("tests/data/v3-only-with-dsa-sha256-{}.apk", key_name));
         assert!(res.is_err(), "DSA algorithm is not supported for verification. See b/197052981.");
-        assert_contains(&res.unwrap_err().to_string(), "No supported signatures found");
+        assert_contains(&res.unwrap_err().to_string(), "No supported APK signatures found");
     }
 }
 
@@ -151,7 +151,7 @@
 fn test_verify_v3_no_supported_sig_algs() {
     let res = verify("tests/data/v3-only-no-supported-sig-algs.apk");
     assert!(res.is_err());
-    assert_contains(&res.unwrap_err().to_string(), "No supported signatures found");
+    assert_contains(&res.unwrap_err().to_string(), "No supported APK signatures found");
 }
 
 #[test]
diff --git a/microdroid_manager/src/main.rs b/microdroid_manager/src/main.rs
index f48611b..24a12f7 100644
--- a/microdroid_manager/src/main.rs
+++ b/microdroid_manager/src/main.rs
@@ -77,6 +77,7 @@
     "/sys/firmware/devicetree/base/virtualization/guest/debug-microdroid,no-verified-boot";
 
 const APEX_CONFIG_DONE_PROP: &str = "apex_config.done";
+const TOMBSTONE_TRANSMIT_DONE_PROP: &str = "tombstone_transmit.init_done";
 const DEBUGGABLE_PROP: &str = "ro.boot.microdroid.debuggable";
 
 // SYNC WITH virtualizationservice/src/crosvm.rs
@@ -435,6 +436,10 @@
 
     register_vm_payload_service(allow_restricted_apis, service.clone(), dice_context)?;
 
+    if config.export_tombstones {
+        wait_for_tombstone_transmit_done()?;
+    }
+
     // Wait for encryptedstore to finish mounting the storage (if enabled) before setting
     // microdroid_manager.init_done. Reason is init stops uneventd after that.
     // Encryptedstore, however requires ueventd
@@ -723,6 +728,11 @@
     wait_for_property_true(APEX_CONFIG_DONE_PROP).context("Failed waiting for apex config done")
 }
 
+fn wait_for_tombstone_transmit_done() -> Result<()> {
+    wait_for_property_true(TOMBSTONE_TRANSMIT_DONE_PROP)
+        .context("Failed waiting for tombstone transmit done")
+}
+
 fn wait_for_property_true(property_name: &str) -> Result<()> {
     let mut prop = PropertyWatcher::new(property_name)?;
     loop {
diff --git a/pvmfw/avb/Android.bp b/pvmfw/avb/Android.bp
index 0527dfb..837f747 100644
--- a/pvmfw/avb/Android.bp
+++ b/pvmfw/avb/Android.bp
@@ -27,7 +27,7 @@
 rust_test {
     name: "libpvmfw_avb.integration_test",
     crate_name: "pvmfw_avb_test",
-    srcs: ["tests/*_test.rs"],
+    srcs: ["tests/*.rs"],
     test_suites: ["general-tests"],
     data: [
         ":avb_testkey_rsa2048_pub_bin",
diff --git a/pvmfw/avb/src/lib.rs b/pvmfw/avb/src/lib.rs
index 6a5b16d..8142674 100644
--- a/pvmfw/avb/src/lib.rs
+++ b/pvmfw/avb/src/lib.rs
@@ -19,6 +19,8 @@
 #![feature(mixed_integer_ops)]
 
 mod error;
+mod partition;
+mod utils;
 mod verify;
 
 pub use error::AvbSlotVerifyError;
diff --git a/pvmfw/avb/src/partition.rs b/pvmfw/avb/src/partition.rs
new file mode 100644
index 0000000..82d89f8
--- /dev/null
+++ b/pvmfw/avb/src/partition.rs
@@ -0,0 +1,86 @@
+// Copyright 2023, The Android Open Source Project
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+//     http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+//! Struct and functions relating to well-known partition names.
+
+use crate::error::AvbIOError;
+use crate::utils::is_not_null;
+use core::ffi::{c_char, CStr};
+
+#[derive(Clone, Debug, PartialEq, Eq)]
+pub(crate) enum PartitionName {
+    Kernel,
+    InitrdNormal,
+    InitrdDebug,
+}
+
+impl PartitionName {
+    const KERNEL_PARTITION_NAME: &[u8] = b"boot\0";
+    const INITRD_NORMAL_PARTITION_NAME: &[u8] = b"initrd_normal\0";
+    const INITRD_DEBUG_PARTITION_NAME: &[u8] = b"initrd_debug\0";
+
+    pub(crate) fn as_cstr(&self) -> &CStr {
+        CStr::from_bytes_with_nul(self.as_bytes()).unwrap()
+    }
+
+    fn as_non_null_terminated_bytes(&self) -> &[u8] {
+        let partition_name = self.as_bytes();
+        &partition_name[..partition_name.len() - 1]
+    }
+
+    fn as_bytes(&self) -> &[u8] {
+        match self {
+            Self::Kernel => Self::KERNEL_PARTITION_NAME,
+            Self::InitrdNormal => Self::INITRD_NORMAL_PARTITION_NAME,
+            Self::InitrdDebug => Self::INITRD_DEBUG_PARTITION_NAME,
+        }
+    }
+}
+
+impl TryFrom<*const c_char> for PartitionName {
+    type Error = AvbIOError;
+
+    fn try_from(partition_name: *const c_char) -> Result<Self, Self::Error> {
+        is_not_null(partition_name)?;
+        // SAFETY: It is safe as the raw pointer `partition_name` is a nonnull pointer.
+        let partition_name = unsafe { CStr::from_ptr(partition_name) };
+        partition_name.try_into()
+    }
+}
+
+impl TryFrom<&CStr> for PartitionName {
+    type Error = AvbIOError;
+
+    fn try_from(partition_name: &CStr) -> Result<Self, Self::Error> {
+        match partition_name.to_bytes_with_nul() {
+            Self::KERNEL_PARTITION_NAME => Ok(Self::Kernel),
+            Self::INITRD_NORMAL_PARTITION_NAME => Ok(Self::InitrdNormal),
+            Self::INITRD_DEBUG_PARTITION_NAME => Ok(Self::InitrdDebug),
+            _ => Err(AvbIOError::NoSuchPartition),
+        }
+    }
+}
+
+impl TryFrom<&[u8]> for PartitionName {
+    type Error = AvbIOError;
+
+    fn try_from(non_null_terminated_name: &[u8]) -> Result<Self, Self::Error> {
+        match non_null_terminated_name {
+            x if x == Self::Kernel.as_non_null_terminated_bytes() => Ok(Self::Kernel),
+            x if x == Self::InitrdNormal.as_non_null_terminated_bytes() => Ok(Self::InitrdNormal),
+            x if x == Self::InitrdDebug.as_non_null_terminated_bytes() => Ok(Self::InitrdDebug),
+            _ => Err(AvbIOError::NoSuchPartition),
+        }
+    }
+}
diff --git a/pvmfw/avb/src/utils.rs b/pvmfw/avb/src/utils.rs
new file mode 100644
index 0000000..bb27497
--- /dev/null
+++ b/pvmfw/avb/src/utils.rs
@@ -0,0 +1,53 @@
+// Copyright 2023, The Android Open Source Project
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+//     http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+//! Common utility functions.
+
+use crate::error::AvbIOError;
+use core::ptr::NonNull;
+
+pub(crate) fn write<T>(ptr: *mut T, value: T) -> Result<(), AvbIOError> {
+    let ptr = to_nonnull(ptr)?;
+    // SAFETY: It is safe as the raw pointer `ptr` is a nonnull pointer.
+    unsafe {
+        *ptr.as_ptr() = value;
+    }
+    Ok(())
+}
+
+pub(crate) fn as_ref<'a, T>(ptr: *mut T) -> Result<&'a T, AvbIOError> {
+    let ptr = to_nonnull(ptr)?;
+    // SAFETY: It is safe as the raw pointer `ptr` is a nonnull pointer.
+    unsafe { Ok(ptr.as_ref()) }
+}
+
+pub(crate) fn to_nonnull<T>(ptr: *mut T) -> Result<NonNull<T>, AvbIOError> {
+    NonNull::new(ptr).ok_or(AvbIOError::NoSuchValue)
+}
+
+pub(crate) fn is_not_null<T>(ptr: *const T) -> Result<(), AvbIOError> {
+    if ptr.is_null() {
+        Err(AvbIOError::NoSuchValue)
+    } else {
+        Ok(())
+    }
+}
+
+pub(crate) fn to_usize<T: TryInto<usize>>(num: T) -> Result<usize, AvbIOError> {
+    num.try_into().map_err(|_| AvbIOError::InvalidValueSize)
+}
+
+pub(crate) fn usize_checked_add(x: usize, y: usize) -> Result<usize, AvbIOError> {
+    x.checked_add(y).ok_or(AvbIOError::InvalidValueSize)
+}
diff --git a/pvmfw/avb/src/verify.rs b/pvmfw/avb/src/verify.rs
index 9d40075..b6519cd 100644
--- a/pvmfw/avb/src/verify.rs
+++ b/pvmfw/avb/src/verify.rs
@@ -17,6 +17,8 @@
 use crate::error::{
     slot_verify_result_to_verify_payload_result, to_avb_io_result, AvbIOError, AvbSlotVerifyError,
 };
+use crate::partition::PartitionName;
+use crate::utils::{as_ref, is_not_null, to_nonnull, to_usize, usize_checked_add, write};
 use avb_bindgen::{
     avb_descriptor_foreach, avb_hash_descriptor_validate_and_byteswap, avb_slot_verify,
     avb_slot_verify_data_free, AvbDescriptor, AvbHashDescriptor, AvbHashtreeErrorMode, AvbIOResult,
@@ -25,8 +27,7 @@
 use core::{
     ffi::{c_char, c_void, CStr},
     mem::{size_of, MaybeUninit},
-    ptr::{self, NonNull},
-    slice,
+    ptr, slice,
 };
 
 const NULL_BYTE: &[u8] = b"\0";
@@ -276,108 +277,6 @@
     }
 }
 
-fn to_usize<T: TryInto<usize>>(num: T) -> Result<usize, AvbIOError> {
-    num.try_into().map_err(|_| AvbIOError::InvalidValueSize)
-}
-
-fn usize_checked_add(x: usize, y: usize) -> Result<usize, AvbIOError> {
-    x.checked_add(y).ok_or(AvbIOError::InvalidValueSize)
-}
-
-fn write<T>(ptr: *mut T, value: T) -> Result<(), AvbIOError> {
-    let ptr = to_nonnull(ptr)?;
-    // SAFETY: It is safe as the raw pointer `ptr` is a nonnull pointer.
-    unsafe {
-        *ptr.as_ptr() = value;
-    }
-    Ok(())
-}
-
-fn as_ref<'a, T>(ptr: *mut T) -> Result<&'a T, AvbIOError> {
-    let ptr = to_nonnull(ptr)?;
-    // SAFETY: It is safe as the raw pointer `ptr` is a nonnull pointer.
-    unsafe { Ok(ptr.as_ref()) }
-}
-
-fn to_nonnull<T>(ptr: *mut T) -> Result<NonNull<T>, AvbIOError> {
-    NonNull::new(ptr).ok_or(AvbIOError::NoSuchValue)
-}
-
-fn is_not_null<T>(ptr: *const T) -> Result<(), AvbIOError> {
-    if ptr.is_null() {
-        Err(AvbIOError::NoSuchValue)
-    } else {
-        Ok(())
-    }
-}
-
-#[derive(Clone, Debug, PartialEq, Eq)]
-enum PartitionName {
-    Kernel,
-    InitrdNormal,
-    InitrdDebug,
-}
-
-impl PartitionName {
-    const KERNEL_PARTITION_NAME: &[u8] = b"boot\0";
-    const INITRD_NORMAL_PARTITION_NAME: &[u8] = b"initrd_normal\0";
-    const INITRD_DEBUG_PARTITION_NAME: &[u8] = b"initrd_debug\0";
-
-    fn as_cstr(&self) -> &CStr {
-        CStr::from_bytes_with_nul(self.as_bytes()).unwrap()
-    }
-
-    fn as_non_null_terminated_bytes(&self) -> &[u8] {
-        let partition_name = self.as_bytes();
-        &partition_name[..partition_name.len() - 1]
-    }
-
-    fn as_bytes(&self) -> &[u8] {
-        match self {
-            Self::Kernel => Self::KERNEL_PARTITION_NAME,
-            Self::InitrdNormal => Self::INITRD_NORMAL_PARTITION_NAME,
-            Self::InitrdDebug => Self::INITRD_DEBUG_PARTITION_NAME,
-        }
-    }
-}
-
-impl TryFrom<*const c_char> for PartitionName {
-    type Error = AvbIOError;
-
-    fn try_from(partition_name: *const c_char) -> Result<Self, Self::Error> {
-        is_not_null(partition_name)?;
-        // SAFETY: It is safe as the raw pointer `partition_name` is a nonnull pointer.
-        let partition_name = unsafe { CStr::from_ptr(partition_name) };
-        partition_name.try_into()
-    }
-}
-
-impl TryFrom<&CStr> for PartitionName {
-    type Error = AvbIOError;
-
-    fn try_from(partition_name: &CStr) -> Result<Self, Self::Error> {
-        match partition_name.to_bytes_with_nul() {
-            Self::KERNEL_PARTITION_NAME => Ok(Self::Kernel),
-            Self::INITRD_NORMAL_PARTITION_NAME => Ok(Self::InitrdNormal),
-            Self::INITRD_DEBUG_PARTITION_NAME => Ok(Self::InitrdDebug),
-            _ => Err(AvbIOError::NoSuchPartition),
-        }
-    }
-}
-
-impl TryFrom<&[u8]> for PartitionName {
-    type Error = AvbIOError;
-
-    fn try_from(non_null_terminated_name: &[u8]) -> Result<Self, Self::Error> {
-        match non_null_terminated_name {
-            x if x == Self::Kernel.as_non_null_terminated_bytes() => Ok(Self::Kernel),
-            x if x == Self::InitrdNormal.as_non_null_terminated_bytes() => Ok(Self::InitrdNormal),
-            x if x == Self::InitrdDebug.as_non_null_terminated_bytes() => Ok(Self::InitrdDebug),
-            _ => Err(AvbIOError::NoSuchPartition),
-        }
-    }
-}
-
 struct AvbSlotVerifyDataWrap(*mut AvbSlotVerifyData);
 
 impl TryFrom<*mut AvbSlotVerifyData> for AvbSlotVerifyDataWrap {
diff --git a/pvmfw/avb/tests/api_test.rs b/pvmfw/avb/tests/api_test.rs
index 872ad63..6b98dfb 100644
--- a/pvmfw/avb/tests/api_test.rs
+++ b/pvmfw/avb/tests/api_test.rs
@@ -14,54 +14,48 @@
  * limitations under the License.
  */
 
-use anyhow::Result;
-use avb_bindgen::{
-    avb_footer_validate_and_byteswap, avb_vbmeta_image_header_to_host_byte_order, AvbFooter,
-    AvbVBMetaImageHeader,
-};
-use pvmfw_avb::{verify_payload, AvbSlotVerifyError};
-use std::{
-    fs,
-    mem::{size_of, transmute, MaybeUninit},
-    ptr,
-};
+mod utils;
 
-const MICRODROID_KERNEL_IMG_PATH: &str = "microdroid_kernel";
-const INITRD_NORMAL_IMG_PATH: &str = "microdroid_initrd_normal.img";
-const INITRD_DEBUG_IMG_PATH: &str = "microdroid_initrd_debuggable.img";
+use anyhow::Result;
+use avb_bindgen::{AvbFooter, AvbVBMetaImageHeader};
+use pvmfw_avb::AvbSlotVerifyError;
+use std::{fs, mem::size_of, ptr};
+use utils::*;
+
 const TEST_IMG_WITH_ONE_HASHDESC_PATH: &str = "test_image_with_one_hashdesc.img";
 const TEST_IMG_WITH_PROP_DESC_PATH: &str = "test_image_with_prop_desc.img";
 const TEST_IMG_WITH_NON_INITRD_HASHDESC_PATH: &str = "test_image_with_non_initrd_hashdesc.img";
 const UNSIGNED_TEST_IMG_PATH: &str = "unsigned_test.img";
 
-const PUBLIC_KEY_RSA2048_PATH: &str = "data/testkey_rsa2048_pub.bin";
-const PUBLIC_KEY_RSA4096_PATH: &str = "data/testkey_rsa4096_pub.bin";
 const RANDOM_FOOTER_POS: usize = 30;
 
 /// This test uses the Microdroid payload compiled on the fly to check that
 /// the latest payload can be verified successfully.
 #[test]
 fn latest_normal_payload_passes_verification() -> Result<()> {
-    assert_payload_verification_succeeds(
+    assert_payload_verification_with_initrd_eq(
         &load_latest_signed_kernel()?,
         &load_latest_initrd_normal()?,
         &load_trusted_public_key()?,
+        Ok(()),
     )
 }
 
 #[test]
 fn latest_debug_payload_passes_verification() -> Result<()> {
-    assert_payload_verification_succeeds(
+    assert_payload_verification_with_initrd_eq(
         &load_latest_signed_kernel()?,
         &load_latest_initrd_debug()?,
         &load_trusted_public_key()?,
+        Ok(()),
     )
 }
 
 #[test]
 fn payload_expecting_no_initrd_passes_verification_with_no_initrd() -> Result<()> {
-    assert_payload_verification_with_no_initrd_eq(
+    assert_payload_verification_eq(
         &fs::read(TEST_IMG_WITH_ONE_HASHDESC_PATH)?,
+        /*initrd=*/ None,
         &load_trusted_public_key()?,
         Ok(()),
     )
@@ -69,8 +63,9 @@
 
 #[test]
 fn payload_with_non_initrd_descriptor_passes_verification_with_no_initrd() -> Result<()> {
-    assert_payload_verification_with_no_initrd_eq(
+    assert_payload_verification_eq(
         &fs::read(TEST_IMG_WITH_NON_INITRD_HASHDESC_PATH)?,
+        /*initrd=*/ None,
         &load_trusted_public_key()?,
         Ok(()),
     )
@@ -78,8 +73,9 @@
 
 #[test]
 fn payload_with_prop_descriptor_fails_verification_with_no_initrd() -> Result<()> {
-    assert_payload_verification_with_no_initrd_eq(
+    assert_payload_verification_eq(
         &fs::read(TEST_IMG_WITH_PROP_DESC_PATH)?,
+        /*initrd=*/ None,
         &load_trusted_public_key()?,
         Err(AvbSlotVerifyError::InvalidMetadata),
     )
@@ -87,8 +83,9 @@
 
 #[test]
 fn payload_expecting_initrd_fails_verification_with_no_initrd() -> Result<()> {
-    assert_payload_verification_with_no_initrd_eq(
+    assert_payload_verification_eq(
         &load_latest_signed_kernel()?,
+        /*initrd=*/ None,
         &load_trusted_public_key()?,
         Err(AvbSlotVerifyError::InvalidMetadata),
     )
@@ -96,41 +93,41 @@
 
 #[test]
 fn payload_with_empty_public_key_fails_verification() -> Result<()> {
-    assert_payload_verification_fails(
+    assert_payload_verification_with_initrd_eq(
         &load_latest_signed_kernel()?,
         &load_latest_initrd_normal()?,
         /*trusted_public_key=*/ &[0u8; 0],
-        AvbSlotVerifyError::PublicKeyRejected,
+        Err(AvbSlotVerifyError::PublicKeyRejected),
     )
 }
 
 #[test]
 fn payload_with_an_invalid_public_key_fails_verification() -> Result<()> {
-    assert_payload_verification_fails(
+    assert_payload_verification_with_initrd_eq(
         &load_latest_signed_kernel()?,
         &load_latest_initrd_normal()?,
         /*trusted_public_key=*/ &[0u8; 512],
-        AvbSlotVerifyError::PublicKeyRejected,
+        Err(AvbSlotVerifyError::PublicKeyRejected),
     )
 }
 
 #[test]
 fn payload_with_a_different_valid_public_key_fails_verification() -> Result<()> {
-    assert_payload_verification_fails(
+    assert_payload_verification_with_initrd_eq(
         &load_latest_signed_kernel()?,
         &load_latest_initrd_normal()?,
         &fs::read(PUBLIC_KEY_RSA2048_PATH)?,
-        AvbSlotVerifyError::PublicKeyRejected,
+        Err(AvbSlotVerifyError::PublicKeyRejected),
     )
 }
 
 #[test]
 fn unsigned_kernel_fails_verification() -> Result<()> {
-    assert_payload_verification_fails(
+    assert_payload_verification_with_initrd_eq(
         &fs::read(UNSIGNED_TEST_IMG_PATH)?,
         &load_latest_initrd_normal()?,
         &load_trusted_public_key()?,
-        AvbSlotVerifyError::Io,
+        Err(AvbSlotVerifyError::Io),
     )
 }
 
@@ -139,25 +136,58 @@
     let mut kernel = load_latest_signed_kernel()?;
     kernel[1] = !kernel[1]; // Flip the bits
 
-    assert_payload_verification_fails(
+    assert_payload_verification_with_initrd_eq(
         &kernel,
         &load_latest_initrd_normal()?,
         &load_trusted_public_key()?,
-        AvbSlotVerifyError::Verification,
+        Err(AvbSlotVerifyError::Verification),
     )
 }
 
 #[test]
+fn kernel_footer_with_vbmeta_offset_overwritten_fails_verification() -> Result<()> {
+    // Arrange.
+    let mut kernel = load_latest_signed_kernel()?;
+    let total_len = kernel.len() as u64;
+    let footer = extract_avb_footer(&kernel)?;
+    assert!(footer.vbmeta_offset < total_len);
+    let vbmeta_offset_addr = ptr::addr_of!(footer.vbmeta_offset) as *const u8;
+    // SAFETY: It is safe as both raw pointers `vbmeta_offset_addr` and `footer` are not null.
+    let vbmeta_offset_start =
+        unsafe { vbmeta_offset_addr.offset_from(ptr::addr_of!(footer) as *const u8) };
+    let footer_start = kernel.len() - size_of::<AvbFooter>();
+    let vbmeta_offset_start = footer_start + usize::try_from(vbmeta_offset_start)?;
+
+    let wrong_offsets = [total_len, u64::MAX];
+    for &wrong_offset in wrong_offsets.iter() {
+        // Act.
+        kernel[vbmeta_offset_start..(vbmeta_offset_start + size_of::<u64>())]
+            .copy_from_slice(&wrong_offset.to_be_bytes());
+
+        // Assert.
+        let footer = extract_avb_footer(&kernel)?;
+        assert_eq!(wrong_offset, footer.vbmeta_offset as u64);
+        assert_payload_verification_with_initrd_eq(
+            &kernel,
+            &load_latest_initrd_normal()?,
+            &load_trusted_public_key()?,
+            Err(AvbSlotVerifyError::Io),
+        )?;
+    }
+    Ok(())
+}
+
+#[test]
 fn tampered_kernel_footer_fails_verification() -> Result<()> {
     let mut kernel = load_latest_signed_kernel()?;
     let avb_footer_index = kernel.len() - size_of::<AvbFooter>() + RANDOM_FOOTER_POS;
     kernel[avb_footer_index] = !kernel[avb_footer_index];
 
-    assert_payload_verification_fails(
+    assert_payload_verification_with_initrd_eq(
         &kernel,
         &load_latest_initrd_normal()?,
         &load_trusted_public_key()?,
-        AvbSlotVerifyError::InvalidMetadata,
+        Err(AvbSlotVerifyError::InvalidMetadata),
     )
 }
 
@@ -169,11 +199,11 @@
 
     kernel[vbmeta_index] = !kernel[vbmeta_index]; // Flip the bits
 
-    assert_payload_verification_fails(
+    assert_payload_verification_with_initrd_eq(
         &kernel,
         &load_latest_initrd_normal()?,
         &load_trusted_public_key()?,
-        AvbSlotVerifyError::InvalidMetadata,
+        Err(AvbSlotVerifyError::InvalidMetadata),
     )
 }
 
@@ -192,17 +222,17 @@
     kernel[public_key_offset..(public_key_offset + public_key_size)]
         .copy_from_slice(&empty_public_key);
 
-    assert_payload_verification_fails(
+    assert_payload_verification_with_initrd_eq(
         &kernel,
         &load_latest_initrd_normal()?,
         &empty_public_key,
-        AvbSlotVerifyError::Verification,
+        Err(AvbSlotVerifyError::Verification),
     )?;
-    assert_payload_verification_fails(
+    assert_payload_verification_with_initrd_eq(
         &kernel,
         &load_latest_initrd_normal()?,
         &load_trusted_public_key()?,
-        AvbSlotVerifyError::Verification,
+        Err(AvbSlotVerifyError::Verification),
     )
 }
 
@@ -234,81 +264,10 @@
         AVB_VBMETA_IMAGE_FLAGS_VERIFICATION_DISABLED, vbmeta_header.flags as u32,
         "VBMeta verification flag should be disabled now."
     );
-    assert_payload_verification_fails(
+    assert_payload_verification_with_initrd_eq(
         &kernel,
         &load_latest_initrd_normal()?,
         &load_trusted_public_key()?,
-        AvbSlotVerifyError::Verification,
+        Err(AvbSlotVerifyError::Verification),
     )
 }
-
-fn extract_avb_footer(kernel: &[u8]) -> Result<AvbFooter> {
-    let footer_start = kernel.len() - size_of::<AvbFooter>();
-    // SAFETY: The slice is the same size as the struct which only contains simple data types.
-    let mut footer = unsafe {
-        transmute::<[u8; size_of::<AvbFooter>()], AvbFooter>(kernel[footer_start..].try_into()?)
-    };
-    // SAFETY: The function updates the struct in-place.
-    unsafe {
-        avb_footer_validate_and_byteswap(&footer, &mut footer);
-    }
-    Ok(footer)
-}
-
-fn extract_vbmeta_header(kernel: &[u8], footer: &AvbFooter) -> Result<AvbVBMetaImageHeader> {
-    let vbmeta_offset: usize = footer.vbmeta_offset.try_into()?;
-    let vbmeta_size: usize = footer.vbmeta_size.try_into()?;
-    let vbmeta_src = &kernel[vbmeta_offset..(vbmeta_offset + vbmeta_size)];
-    // SAFETY: The latest kernel has a valid VBMeta header at the position specified in footer.
-    let vbmeta_header = unsafe {
-        let mut header = MaybeUninit::uninit();
-        let src = vbmeta_src.as_ptr() as *const _ as *const AvbVBMetaImageHeader;
-        avb_vbmeta_image_header_to_host_byte_order(src, header.as_mut_ptr());
-        header.assume_init()
-    };
-    Ok(vbmeta_header)
-}
-
-fn assert_payload_verification_with_no_initrd_eq(
-    kernel: &[u8],
-    trusted_public_key: &[u8],
-    expected_result: Result<(), AvbSlotVerifyError>,
-) -> Result<()> {
-    assert_eq!(expected_result, verify_payload(kernel, /*initrd=*/ None, trusted_public_key));
-    Ok(())
-}
-
-fn assert_payload_verification_fails(
-    kernel: &[u8],
-    initrd: &[u8],
-    trusted_public_key: &[u8],
-    expected_error: AvbSlotVerifyError,
-) -> Result<()> {
-    assert_eq!(Err(expected_error), verify_payload(kernel, Some(initrd), trusted_public_key));
-    Ok(())
-}
-
-fn assert_payload_verification_succeeds(
-    kernel: &[u8],
-    initrd: &[u8],
-    trusted_public_key: &[u8],
-) -> Result<()> {
-    assert_eq!(Ok(()), verify_payload(kernel, Some(initrd), trusted_public_key));
-    Ok(())
-}
-
-fn load_latest_signed_kernel() -> Result<Vec<u8>> {
-    Ok(fs::read(MICRODROID_KERNEL_IMG_PATH)?)
-}
-
-fn load_latest_initrd_normal() -> Result<Vec<u8>> {
-    Ok(fs::read(INITRD_NORMAL_IMG_PATH)?)
-}
-
-fn load_latest_initrd_debug() -> Result<Vec<u8>> {
-    Ok(fs::read(INITRD_DEBUG_IMG_PATH)?)
-}
-
-fn load_trusted_public_key() -> Result<Vec<u8>> {
-    Ok(fs::read(PUBLIC_KEY_RSA4096_PATH)?)
-}
diff --git a/pvmfw/avb/tests/utils.rs b/pvmfw/avb/tests/utils.rs
new file mode 100644
index 0000000..aa40bb8
--- /dev/null
+++ b/pvmfw/avb/tests/utils.rs
@@ -0,0 +1,97 @@
+/*
+ * Copyright (C) 2023 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+//! Utility methods used by API tests.
+
+use anyhow::Result;
+use avb_bindgen::{
+    avb_footer_validate_and_byteswap, avb_vbmeta_image_header_to_host_byte_order, AvbFooter,
+    AvbVBMetaImageHeader,
+};
+use pvmfw_avb::{verify_payload, AvbSlotVerifyError};
+use std::{
+    fs,
+    mem::{size_of, transmute, MaybeUninit},
+};
+
+const MICRODROID_KERNEL_IMG_PATH: &str = "microdroid_kernel";
+const INITRD_NORMAL_IMG_PATH: &str = "microdroid_initrd_normal.img";
+const INITRD_DEBUG_IMG_PATH: &str = "microdroid_initrd_debuggable.img";
+const PUBLIC_KEY_RSA4096_PATH: &str = "data/testkey_rsa4096_pub.bin";
+
+pub const PUBLIC_KEY_RSA2048_PATH: &str = "data/testkey_rsa2048_pub.bin";
+
+pub fn assert_payload_verification_with_initrd_eq(
+    kernel: &[u8],
+    initrd: &[u8],
+    trusted_public_key: &[u8],
+    expected_result: Result<(), AvbSlotVerifyError>,
+) -> Result<()> {
+    assert_payload_verification_eq(kernel, Some(initrd), trusted_public_key, expected_result)
+}
+
+pub fn assert_payload_verification_eq(
+    kernel: &[u8],
+    initrd: Option<&[u8]>,
+    trusted_public_key: &[u8],
+    expected_result: Result<(), AvbSlotVerifyError>,
+) -> Result<()> {
+    assert_eq!(expected_result, verify_payload(kernel, initrd, trusted_public_key));
+    Ok(())
+}
+
+pub fn load_latest_signed_kernel() -> Result<Vec<u8>> {
+    Ok(fs::read(MICRODROID_KERNEL_IMG_PATH)?)
+}
+
+pub fn load_latest_initrd_normal() -> Result<Vec<u8>> {
+    Ok(fs::read(INITRD_NORMAL_IMG_PATH)?)
+}
+
+pub fn load_latest_initrd_debug() -> Result<Vec<u8>> {
+    Ok(fs::read(INITRD_DEBUG_IMG_PATH)?)
+}
+
+pub fn load_trusted_public_key() -> Result<Vec<u8>> {
+    Ok(fs::read(PUBLIC_KEY_RSA4096_PATH)?)
+}
+
+pub fn extract_avb_footer(kernel: &[u8]) -> Result<AvbFooter> {
+    let footer_start = kernel.len() - size_of::<AvbFooter>();
+    // SAFETY: The slice is the same size as the struct which only contains simple data types.
+    let mut footer = unsafe {
+        transmute::<[u8; size_of::<AvbFooter>()], AvbFooter>(kernel[footer_start..].try_into()?)
+    };
+    // SAFETY: The function updates the struct in-place.
+    unsafe {
+        avb_footer_validate_and_byteswap(&footer, &mut footer);
+    }
+    Ok(footer)
+}
+
+pub fn extract_vbmeta_header(kernel: &[u8], footer: &AvbFooter) -> Result<AvbVBMetaImageHeader> {
+    let vbmeta_offset: usize = footer.vbmeta_offset.try_into()?;
+    let vbmeta_size: usize = footer.vbmeta_size.try_into()?;
+    let vbmeta_src = &kernel[vbmeta_offset..(vbmeta_offset + vbmeta_size)];
+    // SAFETY: The latest kernel has a valid VBMeta header at the position specified in footer.
+    let vbmeta_header = unsafe {
+        let mut header = MaybeUninit::uninit();
+        let src = vbmeta_src.as_ptr() as *const _ as *const AvbVBMetaImageHeader;
+        avb_vbmeta_image_header_to_host_byte_order(src, header.as_mut_ptr());
+        header.assume_init()
+    };
+    Ok(vbmeta_header)
+}