Merge "[DON'T BLOCK] Test ownership migration rules" into main
diff --git a/apex/Android.bp b/apex/Android.bp
index 53fb423..ba42c88 100644
--- a/apex/Android.bp
+++ b/apex/Android.bp
@@ -33,7 +33,26 @@
     },
 }
 
-apex_defaults {
+soong_config_module_type {
+    name: "avf_flag_aware_apex_defaults",
+    module_type: "apex_defaults",
+    config_namespace: "ANDROID",
+    bool_variables: [
+        "release_avf_enable_device_assignment",
+        "release_avf_enable_llpvm_changes",
+        "release_avf_enable_remote_attestation",
+        "release_avf_enable_vendor_modules",
+    ],
+    properties: [
+        "androidManifest",
+        "arch",
+        "prebuilts",
+        "systemserverclasspath_fragments",
+        "vintf_fragments",
+    ],
+}
+
+avf_flag_aware_apex_defaults {
     name: "com.android.virt_common",
     // TODO(jiyong): make it updatable
     updatable: false,
@@ -66,22 +85,13 @@
         "libsso",
         "libutils",
     ],
-}
-
-soong_config_module_type {
-    name: "avf_flag_aware_apex_defaults",
-    module_type: "apex_defaults",
-    config_namespace: "ANDROID",
-    bool_variables: [
-        "release_avf_enable_device_assignment",
-        "release_avf_enable_remote_attestation",
-        "release_avf_enable_vendor_modules",
-    ],
-    properties: [
-        "arch",
-        "prebuilts",
-        "vintf_fragments",
-    ],
+    soong_config_variables: {
+        release_avf_enable_llpvm_changes: {
+            systemserverclasspath_fragments: [
+                "com.android.virt-systemserver-fragment",
+            ],
+        },
+    },
 }
 
 avf_flag_aware_apex_defaults {
@@ -144,6 +154,9 @@
                 },
             },
         },
+        release_avf_enable_llpvm_changes: {
+            androidManifest: "AndroidManifest.xml",
+        },
         release_avf_enable_vendor_modules: {
             prebuilts: [
                 "microdroid_gki-android14-6.1_initrd_debuggable",
@@ -323,3 +336,29 @@
         ],
     },
 }
+
+soong_config_module_type {
+    name: "avf_flag_aware_systemserverclasspath_fragment",
+    module_type: "systemserverclasspath_fragment",
+    config_namespace: "ANDROID",
+    bool_variables: [
+        "release_avf_enable_llpvm_changes",
+    ],
+    properties: [
+        "enabled",
+    ],
+}
+
+avf_flag_aware_systemserverclasspath_fragment {
+    name: "com.android.virt-systemserver-fragment",
+    contents: [
+        "service-virtualization",
+    ],
+    apex_available: ["com.android.virt"],
+    enabled: false,
+    soong_config_variables: {
+        release_avf_enable_llpvm_changes: {
+            enabled: true,
+        },
+    },
+}
diff --git a/apex/AndroidManifest.xml b/apex/AndroidManifest.xml
new file mode 100644
index 0000000..be52f42
--- /dev/null
+++ b/apex/AndroidManifest.xml
@@ -0,0 +1,26 @@
+<?xml version="1.0" encoding="utf-8"?>
+<!--
+ * Copyright 2024 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.
+ -->
+
+<manifest xmlns:android="http://schemas.android.com/apk/res/android"
+          package="com.android.virt">
+    <!-- APEX does not have classes.dex -->
+    <application android:hasCode="false">
+        <apex-system-service
+            android:name="com.android.system.virtualmachine.VirtualizationSystemService"
+        />
+    </application>
+</manifest>
diff --git a/apex/product_packages.mk b/apex/product_packages.mk
index 4c03836..a318817 100644
--- a/apex/product_packages.mk
+++ b/apex/product_packages.mk
@@ -44,3 +44,15 @@
     $(error RELEASE_AVF_ENABLE_VENDOR_MODULES must also be enabled)
   endif
 endif
+
+ifdef RELEASE_AVF_ENABLE_LLPVM_CHANGES
+  ifndef RELEASE_AVF_ENABLE_DICE_CHANGES
+    $(error RELEASE_AVF_ENABLE_DICE_CHANGES must also be enabled)
+  endif
+endif
+
+ifdef RELEASE_AVF_ENABLE_REMOTE_ATTESTATION
+  ifndef RELEASE_AVF_ENABLE_DICE_CHANGES
+    $(error RELEASE_AVF_ENABLE_DICE_CHANGES must also be enabled)
+  endif
+endif
diff --git a/javalib/service/Android.bp b/javalib/service/Android.bp
new file mode 100644
index 0000000..9c1fa01
--- /dev/null
+++ b/javalib/service/Android.bp
@@ -0,0 +1,30 @@
+// Copyright (C) 2024 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.
+
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
+java_library {
+    name: "service-virtualization",
+    srcs: [
+        "src/**/*.java",
+    ],
+    defaults: [
+        "framework-system-server-module-defaults",
+    ],
+    sdk_version: "system_server_current",
+    apex_available: ["com.android.virt"],
+    installable: true,
+}
diff --git a/javalib/service/src/com/android/system/virtualmachine/VirtualizationSystemService.java b/javalib/service/src/com/android/system/virtualmachine/VirtualizationSystemService.java
new file mode 100644
index 0000000..2905acd
--- /dev/null
+++ b/javalib/service/src/com/android/system/virtualmachine/VirtualizationSystemService.java
@@ -0,0 +1,31 @@
+/*
+ * Copyright (C) 2024 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.
+ */
+
+package com.android.system.virtualmachine;
+
+import android.content.Context;
+import com.android.server.SystemService;
+
+/** TODO */
+public class VirtualizationSystemService extends SystemService {
+
+    public VirtualizationSystemService(Context context) {
+        super(context);
+    }
+
+    @Override
+    public void onStart() {}
+}
diff --git a/pvmfw/avb/Android.bp b/pvmfw/avb/Android.bp
index c5ebe73..3bb8354 100644
--- a/pvmfw/avb/Android.bp
+++ b/pvmfw/avb/Android.bp
@@ -10,7 +10,6 @@
     srcs: ["src/lib.rs"],
     prefer_rlib: true,
     rustlibs: [
-        "libavb_bindgen_nostd",
         "libavb_rs_nostd",
         "libtinyvec_nostd",
     ],
diff --git a/pvmfw/avb/src/descriptor.rs b/pvmfw/avb/src/descriptor.rs
deleted file mode 100644
index a3db0e5..0000000
--- a/pvmfw/avb/src/descriptor.rs
+++ /dev/null
@@ -1,23 +0,0 @@
-// 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.
-
-//! Structs and functions relating to the descriptors.
-
-mod collection;
-mod common;
-mod hash;
-mod property;
-
-pub(crate) use collection::Descriptors;
-pub use hash::Digest;
diff --git a/pvmfw/avb/src/descriptor/collection.rs b/pvmfw/avb/src/descriptor/collection.rs
deleted file mode 100644
index 6784758..0000000
--- a/pvmfw/avb/src/descriptor/collection.rs
+++ /dev/null
@@ -1,190 +0,0 @@
-// 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.
-
-//! Structs and functions relating to the descriptor collection.
-
-use super::common::get_valid_descriptor;
-use super::hash::HashDescriptor;
-use super::property::PropertyDescriptor;
-use crate::partition::PartitionName;
-use crate::utils::{to_usize, usize_checked_add};
-use crate::PvmfwVerifyError;
-use avb::{IoError, IoResult, SlotVerifyError, SlotVerifyNoDataResult, VbmetaData};
-use avb_bindgen::{
-    avb_descriptor_foreach, avb_descriptor_validate_and_byteswap, AvbDescriptor, AvbDescriptorTag,
-};
-use core::{ffi::c_void, mem::size_of, slice};
-use tinyvec::ArrayVec;
-
-/// `Descriptors` can have at most one `HashDescriptor` per known partition and at most one
-/// `PropertyDescriptor`.
-#[derive(Default)]
-pub(crate) struct Descriptors<'a> {
-    hash_descriptors: ArrayVec<[HashDescriptor<'a>; PartitionName::NUM_OF_KNOWN_PARTITIONS]>,
-    prop_descriptor: Option<PropertyDescriptor<'a>>,
-}
-
-impl<'a> Descriptors<'a> {
-    /// Builds `Descriptors` from `VbmetaData`.
-    /// Returns an error if the given `VbmetaData` contains non-hash descriptor, hash
-    /// descriptor of unknown `PartitionName` or duplicated hash descriptors.
-    pub(crate) fn from_vbmeta(vbmeta: &'a VbmetaData) -> Result<Self, PvmfwVerifyError> {
-        let mut res: IoResult<Self> = Ok(Self::default());
-        // SAFETY: It is safe as `vbmeta.data()` contains a valid VBMeta structure.
-        let output = unsafe {
-            avb_descriptor_foreach(
-                vbmeta.data().as_ptr(),
-                vbmeta.data().len(),
-                Some(check_and_save_descriptor),
-                &mut res as *mut _ as *mut c_void,
-            )
-        };
-        if output == res.is_ok() {
-            res.map_err(PvmfwVerifyError::InvalidDescriptors)
-        } else {
-            Err(SlotVerifyError::InvalidMetadata.into())
-        }
-    }
-
-    pub(crate) fn num_hash_descriptor(&self) -> usize {
-        self.hash_descriptors.len()
-    }
-
-    /// Finds the `HashDescriptor` for the given `PartitionName`.
-    /// Throws an error if no corresponding descriptor found.
-    pub(crate) fn find_hash_descriptor(
-        &self,
-        partition_name: PartitionName,
-    ) -> SlotVerifyNoDataResult<&HashDescriptor> {
-        self.hash_descriptors
-            .iter()
-            .find(|d| d.partition_name == partition_name)
-            .ok_or(SlotVerifyError::InvalidMetadata)
-    }
-
-    pub(crate) fn has_property_descriptor(&self) -> bool {
-        self.prop_descriptor.is_some()
-    }
-
-    pub(crate) fn find_property_value(&self, key: &[u8]) -> Option<&[u8]> {
-        self.prop_descriptor.as_ref().filter(|desc| desc.key == key).map(|desc| desc.value)
-    }
-
-    fn push(&mut self, descriptor: Descriptor<'a>) -> IoResult<()> {
-        match descriptor {
-            Descriptor::Hash(d) => self.push_hash_descriptor(d),
-            Descriptor::Property(d) => self.push_property_descriptor(d),
-        }
-    }
-
-    fn push_hash_descriptor(&mut self, descriptor: HashDescriptor<'a>) -> IoResult<()> {
-        if self.hash_descriptors.iter().any(|d| d.partition_name == descriptor.partition_name) {
-            return Err(IoError::Io);
-        }
-        self.hash_descriptors.push(descriptor);
-        Ok(())
-    }
-
-    fn push_property_descriptor(&mut self, descriptor: PropertyDescriptor<'a>) -> IoResult<()> {
-        if self.prop_descriptor.is_some() {
-            return Err(IoError::Io);
-        }
-        self.prop_descriptor.replace(descriptor);
-        Ok(())
-    }
-}
-
-/// # Safety
-///
-/// Behavior is undefined if any of the following conditions are violated:
-/// * The `descriptor` pointer must be non-null and points to a valid `AvbDescriptor` struct.
-/// * The `user_data` pointer must be non-null, points to a valid `IoResult<Descriptors>`
-///  struct and is initialized.
-unsafe extern "C" fn check_and_save_descriptor(
-    descriptor: *const AvbDescriptor,
-    user_data: *mut c_void,
-) -> bool {
-    // SAFETY: It is safe because the caller ensures that `user_data` points to a valid struct and
-    // is initialized.
-    let Some(res) = (unsafe { (user_data as *mut IoResult<Descriptors>).as_mut() }) else {
-        return false;
-    };
-    let Ok(descriptors) = res else {
-        return false;
-    };
-    // SAFETY: It is safe because the caller ensures that the `descriptor` pointer is non-null
-    // and valid.
-    unsafe { try_check_and_save_descriptor(descriptor, descriptors) }.map_or_else(
-        |e| {
-            *res = Err(e);
-            false
-        },
-        |_| true,
-    )
-}
-
-/// # Safety
-///
-/// Behavior is undefined if any of the following conditions are violated:
-/// * The `descriptor` pointer must be non-null and points to a valid `AvbDescriptor` struct.
-unsafe fn try_check_and_save_descriptor(
-    descriptor: *const AvbDescriptor,
-    descriptors: &mut Descriptors,
-) -> IoResult<()> {
-    // SAFETY: It is safe because the caller ensures that `descriptor` is a non-null pointer
-    // pointing to a valid struct.
-    let descriptor = unsafe { Descriptor::from_descriptor_ptr(descriptor)? };
-    descriptors.push(descriptor)
-}
-
-enum Descriptor<'a> {
-    Hash(HashDescriptor<'a>),
-    Property(PropertyDescriptor<'a>),
-}
-
-impl<'a> Descriptor<'a> {
-    /// # Safety
-    ///
-    /// Behavior is undefined if any of the following conditions are violated:
-    /// * The `descriptor` pointer must be non-null and point to a valid `AvbDescriptor`.
-    unsafe fn from_descriptor_ptr(descriptor: *const AvbDescriptor) -> IoResult<Self> {
-        let avb_descriptor =
-        // SAFETY: It is safe as the raw pointer `descriptor` is non-null and points to
-        // a valid `AvbDescriptor`.
-            unsafe { get_valid_descriptor(descriptor, avb_descriptor_validate_and_byteswap)? };
-        let len = usize_checked_add(
-            size_of::<AvbDescriptor>(),
-            to_usize(avb_descriptor.num_bytes_following)?,
-        )?;
-        // SAFETY: It is safe because the caller ensures that `descriptor` is a non-null pointer
-        // pointing to a valid struct.
-        let data = unsafe { slice::from_raw_parts(descriptor as *const u8, len) };
-        match avb_descriptor.tag.try_into() {
-            Ok(AvbDescriptorTag::AVB_DESCRIPTOR_TAG_HASH) => {
-                // SAFETY: It is safe because the caller ensures that `descriptor` is a non-null
-                // pointer pointing to a valid struct.
-                let descriptor = unsafe { HashDescriptor::from_descriptor_ptr(descriptor, data)? };
-                Ok(Self::Hash(descriptor))
-            }
-            Ok(AvbDescriptorTag::AVB_DESCRIPTOR_TAG_PROPERTY) => {
-                let descriptor =
-                // SAFETY: It is safe because the caller ensures that `descriptor` is a non-null
-                // pointer pointing to a valid struct.
-                    unsafe { PropertyDescriptor::from_descriptor_ptr(descriptor, data)? };
-                Ok(Self::Property(descriptor))
-            }
-            _ => Err(IoError::NoSuchValue),
-        }
-    }
-}
diff --git a/pvmfw/avb/src/descriptor/common.rs b/pvmfw/avb/src/descriptor/common.rs
deleted file mode 100644
index 6063a7c..0000000
--- a/pvmfw/avb/src/descriptor/common.rs
+++ /dev/null
@@ -1,40 +0,0 @@
-// 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.
-
-//! Structs and functions used by all the descriptors.
-
-use crate::utils::is_not_null;
-use avb::{IoError, IoResult};
-use core::mem::MaybeUninit;
-
-/// # Safety
-///
-/// Behavior is undefined if any of the following conditions are violated:
-/// * The `descriptor_ptr` pointer must be non-null and point to a valid `AvbDescriptor`.
-pub(super) unsafe fn get_valid_descriptor<T>(
-    descriptor_ptr: *const T,
-    descriptor_validate_and_byteswap: unsafe extern "C" fn(src: *const T, dest: *mut T) -> bool,
-) -> IoResult<T> {
-    is_not_null(descriptor_ptr)?;
-    // SAFETY: It is safe because the caller ensures that `descriptor_ptr` is a non-null pointer
-    // pointing to a valid struct.
-    let descriptor = unsafe {
-        let mut desc = MaybeUninit::uninit();
-        if !descriptor_validate_and_byteswap(descriptor_ptr, desc.as_mut_ptr()) {
-            return Err(IoError::Io);
-        }
-        desc.assume_init()
-    };
-    Ok(descriptor)
-}
diff --git a/pvmfw/avb/src/descriptor/hash.rs b/pvmfw/avb/src/descriptor/hash.rs
deleted file mode 100644
index 35db66d..0000000
--- a/pvmfw/avb/src/descriptor/hash.rs
+++ /dev/null
@@ -1,101 +0,0 @@
-// 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.
-
-//! Structs and functions relating to the hash descriptor.
-
-use super::common::get_valid_descriptor;
-use crate::partition::PartitionName;
-use crate::utils::{to_usize, usize_checked_add};
-use avb::{IoError, IoResult};
-use avb_bindgen::{
-    avb_hash_descriptor_validate_and_byteswap, AvbDescriptor, AvbHashDescriptor,
-    AVB_SHA256_DIGEST_SIZE,
-};
-use core::{mem::size_of, ops::Range};
-
-/// Digest type for kernel and initrd.
-pub type Digest = [u8; AVB_SHA256_DIGEST_SIZE as usize];
-
-pub(crate) struct HashDescriptor<'a> {
-    pub(crate) partition_name: PartitionName,
-    pub(crate) digest: &'a Digest,
-}
-
-impl<'a> Default for HashDescriptor<'a> {
-    fn default() -> Self {
-        Self { partition_name: Default::default(), digest: &Self::EMPTY_DIGEST }
-    }
-}
-
-impl<'a> HashDescriptor<'a> {
-    const EMPTY_DIGEST: Digest = [0u8; AVB_SHA256_DIGEST_SIZE as usize];
-
-    /// # Safety
-    ///
-    /// Behavior is undefined if any of the following conditions are violated:
-    /// * The `descriptor` pointer must be non-null and point to a valid `AvbDescriptor`.
-    pub(super) unsafe fn from_descriptor_ptr(
-        descriptor: *const AvbDescriptor,
-        data: &'a [u8],
-    ) -> IoResult<Self> {
-        // SAFETY: It is safe as the raw pointer `descriptor` is non-null and points to
-        // a valid `AvbDescriptor`.
-        let h = unsafe { HashDescriptorHeader::from_descriptor_ptr(descriptor)? };
-        let partition_name = data
-            .get(h.partition_name_range()?)
-            .ok_or(IoError::RangeOutsidePartition)?
-            .try_into()?;
-        let digest = data
-            .get(h.digest_range()?)
-            .ok_or(IoError::RangeOutsidePartition)?
-            .try_into()
-            .map_err(|_| IoError::InvalidValueSize)?;
-        Ok(Self { partition_name, digest })
-    }
-}
-
-struct HashDescriptorHeader(AvbHashDescriptor);
-
-impl HashDescriptorHeader {
-    /// # Safety
-    ///
-    /// Behavior is undefined if any of the following conditions are violated:
-    /// * The `descriptor` pointer must be non-null and point to a valid `AvbDescriptor`.
-    unsafe fn from_descriptor_ptr(descriptor: *const AvbDescriptor) -> IoResult<Self> {
-        // SAFETY: It is safe as the raw pointer `descriptor` is non-null and points to
-        // a valid `AvbDescriptor`.
-        unsafe {
-            get_valid_descriptor(
-                descriptor as *const AvbHashDescriptor,
-                avb_hash_descriptor_validate_and_byteswap,
-            )
-            .map(Self)
-        }
-    }
-
-    fn partition_name_end(&self) -> IoResult<usize> {
-        usize_checked_add(size_of::<AvbHashDescriptor>(), to_usize(self.0.partition_name_len)?)
-    }
-
-    fn partition_name_range(&self) -> IoResult<Range<usize>> {
-        let start = size_of::<AvbHashDescriptor>();
-        Ok(start..(self.partition_name_end()?))
-    }
-
-    fn digest_range(&self) -> IoResult<Range<usize>> {
-        let start = usize_checked_add(self.partition_name_end()?, to_usize(self.0.salt_len)?)?;
-        let end = usize_checked_add(start, to_usize(self.0.digest_len)?)?;
-        Ok(start..end)
-    }
-}
diff --git a/pvmfw/avb/src/descriptor/property.rs b/pvmfw/avb/src/descriptor/property.rs
deleted file mode 100644
index 8145d64..0000000
--- a/pvmfw/avb/src/descriptor/property.rs
+++ /dev/null
@@ -1,92 +0,0 @@
-// 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.
-
-//! Structs and functions relating to the property descriptor.
-
-use super::common::get_valid_descriptor;
-use crate::utils::{to_usize, usize_checked_add};
-use avb::{IoError, IoResult};
-use avb_bindgen::{
-    avb_property_descriptor_validate_and_byteswap, AvbDescriptor, AvbPropertyDescriptor,
-};
-use core::mem::size_of;
-
-pub(super) struct PropertyDescriptor<'a> {
-    pub(super) key: &'a [u8],
-    pub(super) value: &'a [u8],
-}
-
-impl<'a> PropertyDescriptor<'a> {
-    /// # Safety
-    ///
-    /// Behavior is undefined if any of the following conditions are violated:
-    /// * The `descriptor` pointer must be non-null and point to a valid `AvbDescriptor`.
-    pub(super) unsafe fn from_descriptor_ptr(
-        descriptor: *const AvbDescriptor,
-        data: &'a [u8],
-    ) -> IoResult<Self> {
-        // SAFETY: It is safe as the raw pointer `descriptor` is non-null and points to
-        // a valid `AvbDescriptor`.
-        let h = unsafe { PropertyDescriptorHeader::from_descriptor_ptr(descriptor)? };
-        let key = Self::get_valid_slice(data, h.key_start(), h.key_end()?)?;
-        let value = Self::get_valid_slice(data, h.value_start()?, h.value_end()?)?;
-        Ok(Self { key, value })
-    }
-
-    fn get_valid_slice(data: &[u8], start: usize, end: usize) -> IoResult<&[u8]> {
-        const NUL_BYTE: u8 = b'\0';
-
-        match data.get(end) {
-            Some(&NUL_BYTE) => data.get(start..end).ok_or(IoError::RangeOutsidePartition),
-            _ => Err(IoError::NoSuchValue),
-        }
-    }
-}
-
-struct PropertyDescriptorHeader(AvbPropertyDescriptor);
-
-impl PropertyDescriptorHeader {
-    /// # Safety
-    ///
-    /// Behavior is undefined if any of the following conditions are violated:
-    /// * The `descriptor` pointer must be non-null and point to a valid `AvbDescriptor`.
-    unsafe fn from_descriptor_ptr(descriptor: *const AvbDescriptor) -> IoResult<Self> {
-        // SAFETY: It is safe as the raw pointer `descriptor` is non-null and points to
-        // a valid `AvbDescriptor`.
-        unsafe {
-            get_valid_descriptor(
-                descriptor as *const AvbPropertyDescriptor,
-                avb_property_descriptor_validate_and_byteswap,
-            )
-            .map(Self)
-        }
-    }
-
-    fn key_start(&self) -> usize {
-        size_of::<AvbPropertyDescriptor>()
-    }
-
-    fn key_end(&self) -> IoResult<usize> {
-        usize_checked_add(self.key_start(), to_usize(self.0.key_num_bytes)?)
-    }
-
-    fn value_start(&self) -> IoResult<usize> {
-        // There is a NUL byte between key and value.
-        usize_checked_add(self.key_end()?, 1)
-    }
-
-    fn value_end(&self) -> IoResult<usize> {
-        usize_checked_add(self.value_start()?, to_usize(self.0.value_num_bytes)?)
-    }
-}
diff --git a/pvmfw/avb/src/error.rs b/pvmfw/avb/src/error.rs
index 4e3f27e..2e1950a 100644
--- a/pvmfw/avb/src/error.rs
+++ b/pvmfw/avb/src/error.rs
@@ -15,7 +15,7 @@
 //! This module contains the error thrown by the payload verification API
 //! and other errors used in the library.
 
-use avb::{IoError, SlotVerifyError};
+use avb::{DescriptorError, SlotVerifyError};
 use core::fmt;
 
 /// Wrapper around `SlotVerifyError` to add custom pvmfw errors.
@@ -25,7 +25,7 @@
     /// Passthrough `SlotVerifyError` with no `SlotVerifyData`.
     AvbError(SlotVerifyError<'static>),
     /// VBMeta has invalid descriptors.
-    InvalidDescriptors(IoError),
+    InvalidDescriptors(DescriptorError),
     /// Unknown vbmeta property.
     UnknownVbmetaProperty,
 }
@@ -37,6 +37,12 @@
     }
 }
 
+impl From<DescriptorError> for PvmfwVerifyError {
+    fn from(error: DescriptorError) -> Self {
+        Self::InvalidDescriptors(error)
+    }
+}
+
 impl fmt::Display for PvmfwVerifyError {
     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
         match self {
diff --git a/pvmfw/avb/src/lib.rs b/pvmfw/avb/src/lib.rs
index 9c3fe11..fd68652 100644
--- a/pvmfw/avb/src/lib.rs
+++ b/pvmfw/avb/src/lib.rs
@@ -18,13 +18,10 @@
 
 extern crate alloc;
 
-mod descriptor;
 mod error;
 mod ops;
 mod partition;
-mod utils;
 mod verify;
 
-pub use descriptor::Digest;
 pub use error::PvmfwVerifyError;
-pub use verify::{verify_payload, Capability, DebugLevel, VerifiedBootData};
+pub use verify::{verify_payload, Capability, DebugLevel, Digest, VerifiedBootData};
diff --git a/pvmfw/avb/src/partition.rs b/pvmfw/avb/src/partition.rs
index c05a0ac..02a78c6 100644
--- a/pvmfw/avb/src/partition.rs
+++ b/pvmfw/avb/src/partition.rs
@@ -27,8 +27,6 @@
 }
 
 impl PartitionName {
-    pub(crate) const NUM_OF_KNOWN_PARTITIONS: usize = 3;
-
     const KERNEL_PARTITION_NAME: &'static [u8] = b"boot\0";
     const INITRD_NORMAL_PARTITION_NAME: &'static [u8] = b"initrd_normal\0";
     const INITRD_DEBUG_PARTITION_NAME: &'static [u8] = b"initrd_debug\0";
diff --git a/pvmfw/avb/src/utils.rs b/pvmfw/avb/src/utils.rs
deleted file mode 100644
index b4f099b..0000000
--- a/pvmfw/avb/src/utils.rs
+++ /dev/null
@@ -1,33 +0,0 @@
-// 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 avb::{IoError, IoResult};
-
-pub(crate) fn is_not_null<T>(ptr: *const T) -> IoResult<()> {
-    if ptr.is_null() {
-        Err(IoError::NoSuchValue)
-    } else {
-        Ok(())
-    }
-}
-
-pub(crate) fn to_usize<T: TryInto<usize>>(num: T) -> IoResult<usize> {
-    num.try_into().map_err(|_| IoError::InvalidValueSize)
-}
-
-pub(crate) fn usize_checked_add(x: usize, y: usize) -> IoResult<usize> {
-    x.checked_add(y).ok_or(IoError::InvalidValueSize)
-}
diff --git a/pvmfw/avb/src/verify.rs b/pvmfw/avb/src/verify.rs
index a85dbbb..2ebe9a1 100644
--- a/pvmfw/avb/src/verify.rs
+++ b/pvmfw/avb/src/verify.rs
@@ -14,17 +14,22 @@
 
 //! This module handles the pvmfw payload verification.
 
-use crate::descriptor::{Descriptors, Digest};
 use crate::ops::{Ops, Payload};
 use crate::partition::PartitionName;
 use crate::PvmfwVerifyError;
 use alloc::vec;
 use alloc::vec::Vec;
-use avb::{PartitionData, SlotVerifyError, SlotVerifyNoDataResult, VbmetaData};
+use avb::{
+    Descriptor, DescriptorError, DescriptorResult, HashDescriptor, PartitionData,
+    PropertyDescriptor, SlotVerifyError, SlotVerifyNoDataResult, VbmetaData,
+};
 
 // We use this for the rollback_index field if SlotVerifyData has empty rollback_indexes
 const DEFAULT_ROLLBACK_INDEX: u64 = 0;
 
+/// SHA256 digest type for kernel and initrd.
+pub type Digest = [u8; 32];
+
 /// Verified data returned when the payload verification succeeds.
 #[derive(Debug, PartialEq, Eq)]
 pub struct VerifiedBootData<'a> {
@@ -68,15 +73,21 @@
 }
 
 impl Capability {
-    const KEY: &'static [u8] = b"com.android.virt.cap";
+    const KEY: &'static str = "com.android.virt.cap";
     const REMOTE_ATTEST: &'static [u8] = b"remote_attest";
     const SECRETKEEPER_PROTECTION: &'static [u8] = b"secretkeeper_protection";
     const SEPARATOR: u8 = b'|';
 
-    fn get_capabilities(property_value: &[u8]) -> Result<Vec<Self>, PvmfwVerifyError> {
+    /// Returns the capabilities indicated in `descriptor`, or error if the descriptor has
+    /// unexpected contents.
+    fn get_capabilities(descriptor: &PropertyDescriptor) -> Result<Vec<Self>, PvmfwVerifyError> {
+        if descriptor.key != Self::KEY {
+            return Err(PvmfwVerifyError::UnknownVbmetaProperty);
+        }
+
         let mut res = Vec::new();
 
-        for v in property_value.split(|b| *b == Self::SEPARATOR) {
+        for v in descriptor.value.split(|b| *b == Self::SEPARATOR) {
             let cap = match v {
                 Self::REMOTE_ATTEST => Self::RemoteAttest,
                 Self::SECRETKEEPER_PROTECTION => Self::SecretkeeperProtection,
@@ -106,16 +117,6 @@
     }
 }
 
-fn verify_vbmeta_has_only_one_hash_descriptor(
-    descriptors: &Descriptors,
-) -> SlotVerifyNoDataResult<()> {
-    if descriptors.num_hash_descriptor() == 1 {
-        Ok(())
-    } else {
-        Err(SlotVerifyError::InvalidMetadata)
-    }
-}
-
 fn verify_loaded_partition_has_expected_length(
     loaded_partitions: &[PartitionData],
     partition_name: PartitionName,
@@ -142,15 +143,91 @@
 /// Verifies that the vbmeta contains at most one property descriptor and it indicates the
 /// vm type is service VM.
 fn verify_property_and_get_capabilities(
-    descriptors: &Descriptors,
+    descriptors: &[Descriptor],
 ) -> Result<Vec<Capability>, PvmfwVerifyError> {
-    if !descriptors.has_property_descriptor() {
-        return Ok(vec![]);
+    let mut iter = descriptors.iter().filter_map(|d| match d {
+        Descriptor::Property(p) => Some(p),
+        _ => None,
+    });
+
+    let descriptor = match iter.next() {
+        // No property descriptors -> no capabilities.
+        None => return Ok(vec![]),
+        Some(d) => d,
+    };
+
+    // Multiple property descriptors -> error.
+    if iter.next().is_some() {
+        return Err(DescriptorError::InvalidContents.into());
     }
-    descriptors
-        .find_property_value(Capability::KEY)
-        .ok_or(PvmfwVerifyError::UnknownVbmetaProperty)
-        .and_then(Capability::get_capabilities)
+
+    Capability::get_capabilities(descriptor)
+}
+
+/// Hash descriptors extracted from a vbmeta image.
+///
+/// We always have a kernel hash descriptor and may have initrd normal or debug descriptors.
+struct HashDescriptors<'a> {
+    kernel: &'a HashDescriptor<'a>,
+    initrd_normal: Option<&'a HashDescriptor<'a>>,
+    initrd_debug: Option<&'a HashDescriptor<'a>>,
+}
+
+impl<'a> HashDescriptors<'a> {
+    /// Extracts the hash descriptors from all vbmeta descriptors. Any unexpected hash descriptor
+    /// is an error.
+    fn get(descriptors: &'a [Descriptor<'a>]) -> DescriptorResult<Self> {
+        let mut kernel = None;
+        let mut initrd_normal = None;
+        let mut initrd_debug = None;
+
+        for descriptor in descriptors.iter().filter_map(|d| match d {
+            Descriptor::Hash(h) => Some(h),
+            _ => None,
+        }) {
+            let target = match descriptor
+                .partition_name
+                .as_bytes()
+                .try_into()
+                .map_err(|_| DescriptorError::InvalidContents)?
+            {
+                PartitionName::Kernel => &mut kernel,
+                PartitionName::InitrdNormal => &mut initrd_normal,
+                PartitionName::InitrdDebug => &mut initrd_debug,
+            };
+
+            if target.is_some() {
+                // Duplicates of the same partition name is an error.
+                return Err(DescriptorError::InvalidContents);
+            }
+            target.replace(descriptor);
+        }
+
+        // Kernel is required, the others are optional.
+        Ok(Self {
+            kernel: kernel.ok_or(DescriptorError::InvalidContents)?,
+            initrd_normal,
+            initrd_debug,
+        })
+    }
+
+    /// Returns an error if either initrd descriptor exists.
+    fn verify_no_initrd(&self) -> Result<(), PvmfwVerifyError> {
+        match self.initrd_normal.or(self.initrd_debug) {
+            Some(_) => Err(SlotVerifyError::InvalidMetadata.into()),
+            None => Ok(()),
+        }
+    }
+}
+
+/// Returns a copy of the SHA256 digest in `descriptor`, or error if the sizes don't match.
+fn copy_digest(descriptor: &HashDescriptor) -> SlotVerifyNoDataResult<Digest> {
+    let mut digest = Digest::default();
+    if descriptor.digest.len() != digest.len() {
+        return Err(SlotVerifyError::InvalidMetadata);
+    }
+    digest.clone_from_slice(descriptor.digest);
+    Ok(digest)
 }
 
 /// Verifies the given initrd partition, and checks that the resulting contents looks like expected.
@@ -186,15 +263,15 @@
     verify_only_one_vbmeta_exists(vbmeta_images)?;
     let vbmeta_image = &vbmeta_images[0];
     verify_vbmeta_is_from_kernel_partition(vbmeta_image)?;
-    let descriptors = Descriptors::from_vbmeta(vbmeta_image)?;
+    let descriptors = vbmeta_image.descriptors()?;
+    let hash_descriptors = HashDescriptors::get(&descriptors)?;
     let capabilities = verify_property_and_get_capabilities(&descriptors)?;
-    let kernel_descriptor = descriptors.find_hash_descriptor(PartitionName::Kernel)?;
 
     if initrd.is_none() {
-        verify_vbmeta_has_only_one_hash_descriptor(&descriptors)?;
+        hash_descriptors.verify_no_initrd()?;
         return Ok(VerifiedBootData {
             debug_level: DebugLevel::None,
-            kernel_digest: *kernel_descriptor.digest,
+            kernel_digest: copy_digest(hash_descriptors.kernel)?,
             initrd_digest: None,
             public_key: trusted_public_key,
             capabilities,
@@ -204,19 +281,19 @@
 
     let initrd = initrd.unwrap();
     let mut initrd_ops = Ops::new(&payload);
-    let (debug_level, initrd_partition_name) =
+    let (debug_level, initrd_descriptor) =
         if verify_initrd(&mut initrd_ops, PartitionName::InitrdNormal, initrd).is_ok() {
-            (DebugLevel::None, PartitionName::InitrdNormal)
+            (DebugLevel::None, hash_descriptors.initrd_normal)
         } else if verify_initrd(&mut initrd_ops, PartitionName::InitrdDebug, initrd).is_ok() {
-            (DebugLevel::Full, PartitionName::InitrdDebug)
+            (DebugLevel::Full, hash_descriptors.initrd_debug)
         } else {
             return Err(SlotVerifyError::Verification(None).into());
         };
-    let initrd_descriptor = descriptors.find_hash_descriptor(initrd_partition_name)?;
+    let initrd_descriptor = initrd_descriptor.ok_or(DescriptorError::InvalidContents)?;
     Ok(VerifiedBootData {
         debug_level,
-        kernel_digest: *kernel_descriptor.digest,
-        initrd_digest: Some(*initrd_descriptor.digest),
+        kernel_digest: copy_digest(hash_descriptors.kernel)?,
+        initrd_digest: Some(copy_digest(initrd_descriptor)?),
         public_key: trusted_public_key,
         capabilities,
         rollback_index,
diff --git a/pvmfw/avb/tests/api_test.rs b/pvmfw/avb/tests/api_test.rs
index 6dc5a0a..c6f26ac 100644
--- a/pvmfw/avb/tests/api_test.rs
+++ b/pvmfw/avb/tests/api_test.rs
@@ -17,7 +17,7 @@
 mod utils;
 
 use anyhow::{anyhow, Result};
-use avb::{IoError, SlotVerifyError};
+use avb::{DescriptorError, SlotVerifyError};
 use avb_bindgen::{AvbFooter, AvbVBMetaImageHeader};
 use pvmfw_avb::{verify_payload, Capability, DebugLevel, PvmfwVerifyError, VerifiedBootData};
 use std::{fs, mem::size_of, ptr};
@@ -88,7 +88,7 @@
         &fs::read(TEST_IMG_WITH_NON_INITRD_HASHDESC_PATH)?,
         /* initrd= */ None,
         &load_trusted_public_key()?,
-        PvmfwVerifyError::InvalidDescriptors(IoError::NoSuchPartition),
+        PvmfwVerifyError::InvalidDescriptors(DescriptorError::InvalidContents),
     )
 }
 
@@ -98,7 +98,7 @@
         &fs::read(TEST_IMG_WITH_INITRD_AND_NON_INITRD_DESC_PATH)?,
         &load_latest_initrd_normal()?,
         &load_trusted_public_key()?,
-        PvmfwVerifyError::InvalidDescriptors(IoError::NoSuchPartition),
+        PvmfwVerifyError::InvalidDescriptors(DescriptorError::InvalidContents),
     )
 }
 
@@ -142,7 +142,7 @@
         &fs::read(TEST_IMG_WITH_MULTIPLE_PROPS_PATH)?,
         /* initrd= */ None,
         &load_trusted_public_key()?,
-        PvmfwVerifyError::InvalidDescriptors(IoError::Io),
+        PvmfwVerifyError::InvalidDescriptors(DescriptorError::InvalidContents),
     )
 }
 
diff --git a/pvmfw/src/fdt.rs b/pvmfw/src/fdt.rs
index 2ea4599..770fdf0 100644
--- a/pvmfw/src/fdt.rs
+++ b/pvmfw/src/fdt.rs
@@ -581,14 +581,9 @@
     range1.addr = addr - size;
     range1.size = Some(size);
 
-    let range0 = range0.to_cells();
-    let range1 = range1.to_cells();
-    let value = [
-        range0.0,          // addr
-        range0.1.unwrap(), //size
-        range1.0,          // addr
-        range1.1.unwrap(), //size
-    ];
+    let (addr0, size0) = range0.to_cells();
+    let (addr1, size1) = range1.to_cells();
+    let value = [addr0, size0.unwrap(), addr1, size1.unwrap()];
 
     let mut node =
         fdt.root_mut()?.next_compatible(cstr!("arm,gic-v3"))?.ok_or(FdtError::NotFound)?;