Merge "Remove timestamps from genrule jars" into main
diff --git a/javalib/api/test-current.txt b/javalib/api/test-current.txt
index 0a988d8..3cd8e42 100644
--- a/javalib/api/test-current.txt
+++ b/javalib/api/test-current.txt
@@ -16,7 +16,7 @@
 
   public static final class VirtualMachineConfig.Builder {
     method @FlaggedApi("com.android.system.virtualmachine.flags.avf_v_test_apis") @NonNull public android.system.virtualmachine.VirtualMachineConfig.Builder addExtraApk(@NonNull String);
-    method @FlaggedApi("com.android.system.virtualmachine.flags.avf_v_test_apis") @NonNull public android.system.virtualmachine.VirtualMachineConfig.Builder setOs(@NonNull String);
+    method @FlaggedApi("com.android.system.virtualmachine.flags.avf_v_test_apis") @NonNull @RequiresPermission(android.system.virtualmachine.VirtualMachine.USE_CUSTOM_VIRTUAL_MACHINE_PERMISSION) public android.system.virtualmachine.VirtualMachineConfig.Builder setOs(@NonNull String);
     method @NonNull @RequiresPermission(android.system.virtualmachine.VirtualMachine.USE_CUSTOM_VIRTUAL_MACHINE_PERMISSION) public android.system.virtualmachine.VirtualMachineConfig.Builder setPayloadConfigPath(@NonNull String);
     method @FlaggedApi("com.android.system.virtualmachine.flags.avf_v_test_apis") @NonNull @RequiresPermission(android.system.virtualmachine.VirtualMachine.USE_CUSTOM_VIRTUAL_MACHINE_PERMISSION) public android.system.virtualmachine.VirtualMachineConfig.Builder setVendorDiskImage(@NonNull java.io.File);
     method @NonNull public android.system.virtualmachine.VirtualMachineConfig.Builder setVmConsoleInputSupported(boolean);
@@ -26,6 +26,7 @@
     method @FlaggedApi("com.android.system.virtualmachine.flags.avf_v_test_apis") @NonNull public java.util.List<java.lang.String> getSupportedOSList() throws android.system.virtualmachine.VirtualMachineException;
     method @FlaggedApi("com.android.system.virtualmachine.flags.avf_v_test_apis") @RequiresPermission(android.system.virtualmachine.VirtualMachine.MANAGE_VIRTUAL_MACHINE_PERMISSION) public boolean isFeatureEnabled(String) throws android.system.virtualmachine.VirtualMachineException;
     field @FlaggedApi("com.android.system.virtualmachine.flags.avf_v_test_apis") public static final String FEATURE_DICE_CHANGES = "com.android.kvm.DICE_CHANGES";
+    field @FlaggedApi("com.android.system.virtualmachine.flags.avf_v_test_apis") public static final String FEATURE_LLPVM_CHANGES = "com.android.kvm.LLPVM_CHANGES";
     field @FlaggedApi("com.android.system.virtualmachine.flags.avf_v_test_apis") public static final String FEATURE_MULTI_TENANT = "com.android.kvm.MULTI_TENANT";
     field @FlaggedApi("com.android.system.virtualmachine.flags.avf_v_test_apis") public static final String FEATURE_REMOTE_ATTESTATION = "com.android.kvm.REMOTE_ATTESTATION";
     field @FlaggedApi("com.android.system.virtualmachine.flags.avf_v_test_apis") public static final String FEATURE_VENDOR_MODULES = "com.android.kvm.VENDOR_MODULES";
diff --git a/javalib/src/android/system/virtualmachine/VirtualMachineConfig.java b/javalib/src/android/system/virtualmachine/VirtualMachineConfig.java
index 19e663f..144989e 100644
--- a/javalib/src/android/system/virtualmachine/VirtualMachineConfig.java
+++ b/javalib/src/android/system/virtualmachine/VirtualMachineConfig.java
@@ -530,6 +530,7 @@
                 && this.mEncryptedStorageBytes == other.mEncryptedStorageBytes
                 && this.mVmOutputCaptured == other.mVmOutputCaptured
                 && this.mVmConsoleInputSupported == other.mVmConsoleInputSupported
+                && (this.mVendorDiskImage == null) == (other.mVendorDiskImage == null)
                 && Objects.equals(this.mPayloadConfigPath, other.mPayloadConfigPath)
                 && Objects.equals(this.mPayloadBinaryName, other.mPayloadBinaryName)
                 && Objects.equals(this.mPackageName, other.mPackageName)
@@ -1023,6 +1024,7 @@
          */
         @TestApi
         @FlaggedApi(Flags.FLAG_AVF_V_TEST_APIS)
+        @RequiresPermission(VirtualMachine.USE_CUSTOM_VIRTUAL_MACHINE_PERMISSION)
         @NonNull
         public Builder setOs(@NonNull String os) {
             mOs = requireNonNull(os, "os must not be null");
diff --git a/javalib/src/android/system/virtualmachine/VirtualMachineManager.java b/javalib/src/android/system/virtualmachine/VirtualMachineManager.java
index f263b32..5020ff0 100644
--- a/javalib/src/android/system/virtualmachine/VirtualMachineManager.java
+++ b/javalib/src/android/system/virtualmachine/VirtualMachineManager.java
@@ -119,9 +119,10 @@
             prefix = "FEATURE_",
             value = {
                 FEATURE_DICE_CHANGES,
+                FEATURE_LLPVM_CHANGES,
                 FEATURE_MULTI_TENANT,
                 FEATURE_REMOTE_ATTESTATION,
-                FEATURE_VENDOR_MODULES
+                FEATURE_VENDOR_MODULES,
             })
     public @interface Features {}
 
@@ -164,6 +165,15 @@
             IVirtualizationService.FEATURE_VENDOR_MODULES;
 
     /**
+     * Feature to enable Secretkeeper protected secrets in Microdroid based pVMs.
+     *
+     * @hide
+     */
+    @TestApi
+    @FlaggedApi(Flags.FLAG_AVF_V_TEST_APIS)
+    public static final String FEATURE_LLPVM_CHANGES = IVirtualizationService.FEATURE_LLPVM_CHANGES;
+
+    /**
      * Returns a set of flags indicating what this implementation of virtualization is capable of.
      *
      * @see #CAPABILITY_PROTECTED_VM
diff --git a/libs/avf_features/Android.bp b/libs/avf_features/Android.bp
new file mode 100644
index 0000000..71f33db
--- /dev/null
+++ b/libs/avf_features/Android.bp
@@ -0,0 +1,26 @@
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
+rust_defaults {
+    name: "libavf_features.defaults",
+    crate_name: "avf_features",
+    defaults: ["avf_build_flags_rust"],
+    srcs: ["src/lib.rs"],
+    edition: "2021",
+    prefer_rlib: true,
+    rustlibs: [
+        "android.system.virtualizationservice-rust",
+        "libanyhow",
+        "liblog_rust",
+    ],
+}
+
+rust_library {
+    name: "libavf_features",
+    defaults: ["libavf_features.defaults"],
+    apex_available: [
+        "//apex_available:platform",
+        "com.android.virt",
+    ],
+}
diff --git a/libs/avf_features/src/lib.rs b/libs/avf_features/src/lib.rs
new file mode 100644
index 0000000..c0faab0
--- /dev/null
+++ b/libs/avf_features/src/lib.rs
@@ -0,0 +1,38 @@
+// 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.
+
+//! Provide functionality for handling AVF build-time feature flags.
+
+use android_system_virtualizationservice::aidl::android::system::virtualizationservice::{
+    IVirtualizationService::FEATURE_DICE_CHANGES, IVirtualizationService::FEATURE_LLPVM_CHANGES,
+    IVirtualizationService::FEATURE_MULTI_TENANT,
+    IVirtualizationService::FEATURE_REMOTE_ATTESTATION,
+    IVirtualizationService::FEATURE_VENDOR_MODULES,
+};
+use log::warn;
+
+/// Check if an AVF feature is enabled.
+pub fn is_feature_enabled(feature: &str) -> bool {
+    match feature {
+        FEATURE_DICE_CHANGES => cfg!(dice_changes),
+        FEATURE_LLPVM_CHANGES => cfg!(llpvm_changes),
+        FEATURE_MULTI_TENANT => cfg!(multi_tenant),
+        FEATURE_REMOTE_ATTESTATION => cfg!(remote_attestation),
+        FEATURE_VENDOR_MODULES => cfg!(vendor_modules),
+        _ => {
+            warn!("unknown feature {feature}");
+            false
+        }
+    }
+}
diff --git a/libs/libfdt/Android.bp b/libs/libfdt/Android.bp
index b5f7471..1bb5692 100644
--- a/libs/libfdt/Android.bp
+++ b/libs/libfdt/Android.bp
@@ -40,6 +40,7 @@
         "libcstr",
         "liblibfdt_bindgen",
         "libmemoffset_nostd",
+        "libstatic_assertions",
         "libzerocopy_nostd",
     ],
     whole_static_libs: [
diff --git a/libs/libfdt/src/ctypes.rs b/libs/libfdt/src/ctypes.rs
deleted file mode 100644
index a65f8e7..0000000
--- a/libs/libfdt/src/ctypes.rs
+++ /dev/null
@@ -1,61 +0,0 @@
-// 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.
-
-//! Safe zero-cost wrappers around integer values used by libfdt.
-
-use crate::result::FdtRawResult;
-use crate::{FdtError, Result};
-
-/// Wrapper guaranteed to contain a valid phandle.
-#[repr(transparent)]
-#[derive(Debug, Copy, Clone, Eq, PartialEq, Ord, PartialOrd)]
-pub struct Phandle(u32);
-
-impl Phandle {
-    /// Minimum valid value for device tree phandles.
-    pub const MIN: Self = Self(1);
-    /// Maximum valid value for device tree phandles.
-    pub const MAX: Self = Self(libfdt_bindgen::FDT_MAX_PHANDLE);
-
-    /// Creates a new Phandle
-    pub const fn new(value: u32) -> Option<Self> {
-        if Self::MIN.0 <= value && value <= Self::MAX.0 {
-            Some(Self(value))
-        } else {
-            None
-        }
-    }
-}
-
-impl From<Phandle> for u32 {
-    fn from(phandle: Phandle) -> u32 {
-        phandle.0
-    }
-}
-
-impl TryFrom<u32> for Phandle {
-    type Error = FdtError;
-
-    fn try_from(value: u32) -> Result<Self> {
-        Self::new(value).ok_or(FdtError::BadPhandle)
-    }
-}
-
-impl TryFrom<FdtRawResult> for Phandle {
-    type Error = FdtError;
-
-    fn try_from(res: FdtRawResult) -> Result<Self> {
-        Self::new(res.try_into()?).ok_or(FdtError::BadPhandle)
-    }
-}
diff --git a/libs/libfdt/src/lib.rs b/libs/libfdt/src/lib.rs
index a34ecbb..3339262 100644
--- a/libs/libfdt/src/lib.rs
+++ b/libs/libfdt/src/lib.rs
@@ -17,19 +17,19 @@
 
 #![no_std]
 
-mod ctypes;
 mod iterators;
 mod libfdt;
 mod result;
+mod safe_types;
 
-pub use ctypes::Phandle;
 pub use iterators::{
     AddressRange, CellIterator, CompatibleIterator, DescendantsIterator, MemRegIterator,
     PropertyIterator, RangesIterator, Reg, RegIterator, SubnodeIterator,
 };
 pub use result::{FdtError, Result};
+pub use safe_types::{FdtHeader, NodeOffset, Phandle, PropOffset, StringOffset};
 
-use core::ffi::{c_int, c_void, CStr};
+use core::ffi::{c_void, CStr};
 use core::ops::Range;
 use cstr::cstr;
 use libfdt::get_slice_at_ptr;
@@ -93,12 +93,12 @@
 }
 
 impl FdtPropertyStruct {
-    fn from_offset(fdt: &Fdt, offset: c_int) -> Result<&Self> {
+    fn from_offset(fdt: &Fdt, offset: PropOffset) -> Result<&Self> {
         Ok(fdt.get_property_by_offset(offset)?.as_ref())
     }
 
-    fn name_offset(&self) -> c_int {
-        u32::from_be(self.0.nameoff).try_into().unwrap()
+    fn name_offset(&self) -> StringOffset {
+        StringOffset(u32::from_be(self.0.nameoff).try_into().unwrap())
     }
 
     fn data_len(&self) -> usize {
@@ -114,12 +114,12 @@
 #[derive(Clone, Copy, Debug)]
 pub struct FdtProperty<'a> {
     fdt: &'a Fdt,
-    offset: c_int,
+    offset: PropOffset,
     property: &'a FdtPropertyStruct,
 }
 
 impl<'a> FdtProperty<'a> {
-    fn new(fdt: &'a Fdt, offset: c_int) -> Result<Self> {
+    fn new(fdt: &'a Fdt, offset: PropOffset) -> Result<Self> {
         let property = FdtPropertyStruct::from_offset(fdt, offset)?;
         Ok(Self { fdt, offset, property })
     }
@@ -147,7 +147,7 @@
 #[derive(Clone, Copy, Debug)]
 pub struct FdtNode<'a> {
     fdt: &'a Fdt,
-    offset: c_int,
+    offset: NodeOffset,
 }
 
 impl<'a> FdtNode<'a> {
@@ -355,7 +355,7 @@
 #[derive(Debug)]
 pub struct FdtNodeMut<'a> {
     fdt: &'a mut Fdt,
-    offset: c_int,
+    offset: NodeOffset,
 }
 
 impl<'a> FdtNodeMut<'a> {
@@ -492,6 +492,7 @@
             let next_node = self.delete_and_next(Some(offset))?.unwrap();
             Ok(Some((next_node, depth)))
         } else {
+            self.delete_and_next(None)?;
             Ok(None)
         }
     }
@@ -525,7 +526,7 @@
         self.delete_and_next(next_offset)
     }
 
-    fn delete_and_next(self, next_offset: Option<c_int>) -> Result<Option<Self>> {
+    fn delete_and_next(self, next_offset: Option<NodeOffset>) -> Result<Option<Self>> {
         if Some(self.offset) == next_offset {
             return Err(FdtError::Internal);
         }
@@ -668,7 +669,7 @@
     ///
     /// NOTE: This does not support individual "/memory@XXXX" banks.
     pub fn memory(&self) -> Result<MemRegIterator> {
-        let node = self.node(cstr!("/memory"))?.ok_or(FdtError::NotFound)?;
+        let node = self.root()?.subnode(cstr!("memory"))?.ok_or(FdtError::NotFound)?;
         if node.device_type()? != Some(cstr!("memory")) {
             return Err(FdtError::BadValue);
         }
@@ -682,7 +683,7 @@
 
     /// Returns the standard /chosen node.
     pub fn chosen(&self) -> Result<Option<FdtNode>> {
-        self.node(cstr!("/chosen"))
+        self.root()?.subnode(cstr!("chosen"))
     }
 
     /// Returns the standard /chosen node as mutable.
@@ -692,12 +693,12 @@
 
     /// Returns the root node of the tree.
     pub fn root(&self) -> Result<FdtNode> {
-        self.node(cstr!("/"))?.ok_or(FdtError::Internal)
+        Ok(FdtNode { fdt: self, offset: NodeOffset::ROOT })
     }
 
     /// Returns the standard /__symbols__ node.
     pub fn symbols(&self) -> Result<Option<FdtNode>> {
-        self.node(cstr!("/__symbols__"))
+        self.root()?.subnode(cstr!("__symbols__"))
     }
 
     /// Returns the standard /__symbols__ node as mutable
@@ -738,7 +739,7 @@
 
     /// Returns the mutable root node of the tree.
     pub fn root_mut(&mut self) -> Result<FdtNodeMut> {
-        self.node_mut(cstr!("/"))?.ok_or(FdtError::Internal)
+        Ok(FdtNodeMut { fdt: self, offset: NodeOffset::ROOT })
     }
 
     /// Returns a mutable tree node by its full path.
@@ -748,7 +749,11 @@
         Ok(offset.map(|offset| FdtNodeMut { fdt: self, offset }))
     }
 
-    fn next_node_skip_subnodes(&self, node: c_int, depth: usize) -> Result<Option<(c_int, usize)>> {
+    fn next_node_skip_subnodes(
+        &self,
+        node: NodeOffset,
+        depth: usize,
+    ) -> Result<Option<(NodeOffset, usize)>> {
         let mut iter = self.next_node(node, depth)?;
         while let Some((offset, next_depth)) = iter {
             if next_depth <= depth {
@@ -774,13 +779,14 @@
         self.buffer.as_ptr().cast()
     }
 
-    fn header(&self) -> &libfdt_bindgen::fdt_header {
-        let p = self.as_ptr().cast();
+    fn header(&self) -> &FdtHeader {
+        let p = self.as_ptr().cast::<libfdt_bindgen::fdt_header>();
         // SAFETY: A valid FDT (verified by constructor) must contain a valid fdt_header.
-        unsafe { &*p }
+        let header = unsafe { &*p };
+        header.as_ref()
     }
 
     fn totalsize(&self) -> usize {
-        u32::from_be(self.header().totalsize) as usize
+        self.header().totalsize.get().try_into().unwrap()
     }
 }
diff --git a/libs/libfdt/src/libfdt.rs b/libs/libfdt/src/libfdt.rs
index 1e82c9f..1af9edf 100644
--- a/libs/libfdt/src/libfdt.rs
+++ b/libs/libfdt/src/libfdt.rs
@@ -18,12 +18,12 @@
 //! user-friendly higher-level types, allowing the trait to be shared between different ones,
 //! adapted to their use-cases (e.g. alloc-based userspace or statically allocated no_std).
 
-use core::ffi::{c_int, CStr};
+use core::ffi::CStr;
 use core::mem;
 use core::ptr;
 
 use crate::result::FdtRawResult;
-use crate::{FdtError, Phandle, Result};
+use crate::{FdtError, NodeOffset, Phandle, PropOffset, Result, StringOffset};
 
 // Function names are the C function names without the `fdt_` prefix.
 
@@ -68,7 +68,7 @@
     fn as_fdt_slice(&self) -> &[u8];
 
     /// Safe wrapper around `fdt_path_offset_namelen()` (C function).
-    fn path_offset_namelen(&self, path: &[u8]) -> Result<Option<c_int>> {
+    fn path_offset_namelen(&self, path: &[u8]) -> Result<Option<NodeOffset>> {
         let fdt = self.as_fdt_slice().as_ptr().cast();
         // *_namelen functions don't include the trailing nul terminator in 'len'.
         let len = path.len().try_into().map_err(|_| FdtError::BadPath)?;
@@ -81,7 +81,7 @@
     }
 
     /// Safe wrapper around `fdt_node_offset_by_phandle()` (C function).
-    fn node_offset_by_phandle(&self, phandle: Phandle) -> Result<Option<c_int>> {
+    fn node_offset_by_phandle(&self, phandle: Phandle) -> Result<Option<NodeOffset>> {
         let fdt = self.as_fdt_slice().as_ptr().cast();
         let phandle = phandle.into();
         // SAFETY: Accesses are constrained to the DT totalsize.
@@ -91,8 +91,13 @@
     }
 
     /// Safe wrapper around `fdt_node_offset_by_compatible()` (C function).
-    fn node_offset_by_compatible(&self, prev: c_int, compatible: &CStr) -> Result<Option<c_int>> {
+    fn node_offset_by_compatible(
+        &self,
+        prev: NodeOffset,
+        compatible: &CStr,
+    ) -> Result<Option<NodeOffset>> {
         let fdt = self.as_fdt_slice().as_ptr().cast();
+        let prev = prev.into();
         let compatible = compatible.as_ptr();
         // SAFETY: Accesses (read-only) are constrained to the DT totalsize.
         let ret = unsafe { libfdt_bindgen::fdt_node_offset_by_compatible(fdt, prev, compatible) };
@@ -101,8 +106,9 @@
     }
 
     /// Safe wrapper around `fdt_next_node()` (C function).
-    fn next_node(&self, node: c_int, depth: usize) -> Result<Option<(c_int, usize)>> {
+    fn next_node(&self, node: NodeOffset, depth: usize) -> Result<Option<(NodeOffset, usize)>> {
         let fdt = self.as_fdt_slice().as_ptr().cast();
+        let node = node.into();
         let mut depth = depth.try_into().unwrap();
         // SAFETY: Accesses (read-only) are constrained to the DT totalsize.
         let ret = unsafe { libfdt_bindgen::fdt_next_node(fdt, node, &mut depth) };
@@ -119,8 +125,9 @@
     /// Safe wrapper around `fdt_parent_offset()` (C function).
     ///
     /// Note that this function returns a `Err` when called on a root.
-    fn parent_offset(&self, node: c_int) -> Result<c_int> {
+    fn parent_offset(&self, node: NodeOffset) -> Result<NodeOffset> {
         let fdt = self.as_fdt_slice().as_ptr().cast();
+        let node = node.into();
         // SAFETY: Accesses (read-only) are constrained to the DT totalsize.
         let ret = unsafe { libfdt_bindgen::fdt_parent_offset(fdt, node) };
 
@@ -131,8 +138,9 @@
     ///
     /// Note that this function returns a `Err` when called on a node at a depth shallower than
     /// the provided `depth`.
-    fn supernode_atdepth_offset(&self, node: c_int, depth: usize) -> Result<c_int> {
+    fn supernode_atdepth_offset(&self, node: NodeOffset, depth: usize) -> Result<NodeOffset> {
         let fdt = self.as_fdt_slice().as_ptr().cast();
+        let node = node.into();
         let depth = depth.try_into().unwrap();
         let nodedepth = ptr::null_mut();
         let ret =
@@ -143,8 +151,13 @@
     }
 
     /// Safe wrapper around `fdt_subnode_offset_namelen()` (C function).
-    fn subnode_offset_namelen(&self, parent: c_int, name: &[u8]) -> Result<Option<c_int>> {
+    fn subnode_offset_namelen(
+        &self,
+        parent: NodeOffset,
+        name: &[u8],
+    ) -> Result<Option<NodeOffset>> {
         let fdt = self.as_fdt_slice().as_ptr().cast();
+        let parent = parent.into();
         let namelen = name.len().try_into().unwrap();
         let name = name.as_ptr().cast();
         // SAFETY: Accesses are constrained to the DT totalsize (validated by ctor).
@@ -153,8 +166,9 @@
         FdtRawResult::from(ret).try_into()
     }
     /// Safe wrapper around `fdt_first_subnode()` (C function).
-    fn first_subnode(&self, node: c_int) -> Result<Option<c_int>> {
+    fn first_subnode(&self, node: NodeOffset) -> Result<Option<NodeOffset>> {
         let fdt = self.as_fdt_slice().as_ptr().cast();
+        let node = node.into();
         // SAFETY: Accesses (read-only) are constrained to the DT totalsize.
         let ret = unsafe { libfdt_bindgen::fdt_first_subnode(fdt, node) };
 
@@ -162,8 +176,9 @@
     }
 
     /// Safe wrapper around `fdt_next_subnode()` (C function).
-    fn next_subnode(&self, node: c_int) -> Result<Option<c_int>> {
+    fn next_subnode(&self, node: NodeOffset) -> Result<Option<NodeOffset>> {
         let fdt = self.as_fdt_slice().as_ptr().cast();
+        let node = node.into();
         // SAFETY: Accesses (read-only) are constrained to the DT totalsize.
         let ret = unsafe { libfdt_bindgen::fdt_next_subnode(fdt, node) };
 
@@ -171,8 +186,9 @@
     }
 
     /// Safe wrapper around `fdt_address_cells()` (C function).
-    fn address_cells(&self, node: c_int) -> Result<usize> {
+    fn address_cells(&self, node: NodeOffset) -> Result<usize> {
         let fdt = self.as_fdt_slice().as_ptr().cast();
+        let node = node.into();
         // SAFETY: Accesses are constrained to the DT totalsize (validated by ctor).
         let ret = unsafe { libfdt_bindgen::fdt_address_cells(fdt, node) };
 
@@ -180,8 +196,9 @@
     }
 
     /// Safe wrapper around `fdt_size_cells()` (C function).
-    fn size_cells(&self, node: c_int) -> Result<usize> {
+    fn size_cells(&self, node: NodeOffset) -> Result<usize> {
         let fdt = self.as_fdt_slice().as_ptr().cast();
+        let node = node.into();
         // SAFETY: Accesses are constrained to the DT totalsize (validated by ctor).
         let ret = unsafe { libfdt_bindgen::fdt_size_cells(fdt, node) };
 
@@ -189,8 +206,9 @@
     }
 
     /// Safe wrapper around `fdt_get_name()` (C function).
-    fn get_name(&self, node: c_int) -> Result<&[u8]> {
+    fn get_name(&self, node: NodeOffset) -> Result<&[u8]> {
         let fdt = self.as_fdt_slice().as_ptr().cast();
+        let node = node.into();
         let mut len = 0;
         // SAFETY: Accesses are constrained to the DT totalsize (validated by ctor). On success, the
         // function returns valid null terminating string and otherwise returned values are dropped.
@@ -201,8 +219,9 @@
     }
 
     /// Safe wrapper around `fdt_getprop_namelen()` (C function).
-    fn getprop_namelen(&self, node: c_int, name: &[u8]) -> Result<Option<&[u8]>> {
+    fn getprop_namelen(&self, node: NodeOffset, name: &[u8]) -> Result<Option<&[u8]>> {
         let fdt = self.as_fdt_slice().as_ptr().cast();
+        let node = node.into();
         let namelen = name.len().try_into().map_err(|_| FdtError::BadPath)?;
         let name = name.as_ptr().cast();
         let mut len = 0;
@@ -221,9 +240,10 @@
     }
 
     /// Safe wrapper around `fdt_get_property_by_offset()` (C function).
-    fn get_property_by_offset(&self, offset: c_int) -> Result<&libfdt_bindgen::fdt_property> {
+    fn get_property_by_offset(&self, offset: PropOffset) -> Result<&libfdt_bindgen::fdt_property> {
         let mut len = 0;
         let fdt = self.as_fdt_slice().as_ptr().cast();
+        let offset = offset.into();
         // SAFETY: Accesses (read-only) are constrained to the DT totalsize.
         let prop = unsafe { libfdt_bindgen::fdt_get_property_by_offset(fdt, offset, &mut len) };
 
@@ -247,8 +267,9 @@
     }
 
     /// Safe wrapper around `fdt_first_property_offset()` (C function).
-    fn first_property_offset(&self, node: c_int) -> Result<Option<c_int>> {
+    fn first_property_offset(&self, node: NodeOffset) -> Result<Option<PropOffset>> {
         let fdt = self.as_fdt_slice().as_ptr().cast();
+        let node = node.into();
         // SAFETY: Accesses (read-only) are constrained to the DT totalsize.
         let ret = unsafe { libfdt_bindgen::fdt_first_property_offset(fdt, node) };
 
@@ -256,8 +277,9 @@
     }
 
     /// Safe wrapper around `fdt_next_property_offset()` (C function).
-    fn next_property_offset(&self, prev: c_int) -> Result<Option<c_int>> {
+    fn next_property_offset(&self, prev: PropOffset) -> Result<Option<PropOffset>> {
         let fdt = self.as_fdt_slice().as_ptr().cast();
+        let prev = prev.into();
         // SAFETY: Accesses (read-only) are constrained to the DT totalsize.
         let ret = unsafe { libfdt_bindgen::fdt_next_property_offset(fdt, prev) };
 
@@ -277,8 +299,9 @@
     }
 
     /// Safe wrapper around `fdt_string()` (C function).
-    fn string(&self, offset: c_int) -> Result<&CStr> {
+    fn string(&self, offset: StringOffset) -> Result<&CStr> {
         let fdt = self.as_fdt_slice().as_ptr().cast();
+        let offset = offset.into();
         // SAFETY: Accesses (read-only) are constrained to the DT totalsize.
         let ptr = unsafe { libfdt_bindgen::fdt_string(fdt, offset) };
         let bytes =
@@ -316,8 +339,9 @@
     fn as_fdt_slice_mut(&mut self) -> &mut [u8];
 
     /// Safe wrapper around `fdt_nop_node()` (C function).
-    fn nop_node(&mut self, node: c_int) -> Result<()> {
+    fn nop_node(&mut self, node: NodeOffset) -> Result<()> {
         let fdt = self.as_fdt_slice_mut().as_mut_ptr().cast();
+        let node = node.into();
         // SAFETY: Accesses are constrained to the DT totalsize (validated by ctor).
         let ret = unsafe { libfdt_bindgen::fdt_nop_node(fdt, node) };
 
@@ -325,8 +349,9 @@
     }
 
     /// Safe wrapper around `fdt_add_subnode_namelen()` (C function).
-    fn add_subnode_namelen(&mut self, node: c_int, name: &[u8]) -> Result<c_int> {
+    fn add_subnode_namelen(&mut self, node: NodeOffset, name: &[u8]) -> Result<NodeOffset> {
         let fdt = self.as_fdt_slice_mut().as_mut_ptr().cast();
+        let node = node.into();
         let namelen = name.len().try_into().unwrap();
         let name = name.as_ptr().cast();
         // SAFETY: Accesses are constrained to the DT totalsize (validated by ctor).
@@ -336,8 +361,9 @@
     }
 
     /// Safe wrapper around `fdt_setprop()` (C function).
-    fn setprop(&mut self, node: c_int, name: &CStr, value: &[u8]) -> Result<()> {
+    fn setprop(&mut self, node: NodeOffset, name: &CStr, value: &[u8]) -> Result<()> {
         let fdt = self.as_fdt_slice_mut().as_mut_ptr().cast();
+        let node = node.into();
         let name = name.as_ptr();
         let len = value.len().try_into().map_err(|_| FdtError::BadValue)?;
         let value = value.as_ptr().cast();
@@ -349,8 +375,14 @@
     }
 
     /// Safe wrapper around `fdt_setprop_placeholder()` (C function).
-    fn setprop_placeholder(&mut self, node: c_int, name: &CStr, size: usize) -> Result<&mut [u8]> {
+    fn setprop_placeholder(
+        &mut self,
+        node: NodeOffset,
+        name: &CStr,
+        size: usize,
+    ) -> Result<&mut [u8]> {
         let fdt = self.as_fdt_slice_mut().as_mut_ptr().cast();
+        let node = node.into();
         let name = name.as_ptr();
         let len = size.try_into().unwrap();
         let mut data = ptr::null_mut();
@@ -364,8 +396,9 @@
     }
 
     /// Safe wrapper around `fdt_setprop_inplace()` (C function).
-    fn setprop_inplace(&mut self, node: c_int, name: &CStr, value: &[u8]) -> Result<()> {
+    fn setprop_inplace(&mut self, node: NodeOffset, name: &CStr, value: &[u8]) -> Result<()> {
         let fdt = self.as_fdt_slice_mut().as_mut_ptr().cast();
+        let node = node.into();
         let name = name.as_ptr();
         let len = value.len().try_into().map_err(|_| FdtError::BadValue)?;
         let value = value.as_ptr().cast();
@@ -377,8 +410,9 @@
     }
 
     /// Safe wrapper around `fdt_appendprop()` (C function).
-    fn appendprop(&mut self, node: c_int, name: &CStr, value: &[u8]) -> Result<()> {
+    fn appendprop(&mut self, node: NodeOffset, name: &CStr, value: &[u8]) -> Result<()> {
         let fdt = self.as_fdt_slice_mut().as_mut_ptr().cast();
+        let node = node.into();
         let name = name.as_ptr();
         let len = value.len().try_into().map_err(|_| FdtError::BadValue)?;
         let value = value.as_ptr().cast();
@@ -391,13 +425,15 @@
     /// Safe wrapper around `fdt_appendprop_addrrange()` (C function).
     fn appendprop_addrrange(
         &mut self,
-        parent: c_int,
-        node: c_int,
+        parent: NodeOffset,
+        node: NodeOffset,
         name: &CStr,
         addr: u64,
         size: u64,
     ) -> Result<()> {
         let fdt = self.as_fdt_slice_mut().as_mut_ptr().cast();
+        let parent = parent.into();
+        let node = node.into();
         let name = name.as_ptr();
         // SAFETY: Accesses are constrained to the DT totalsize (validated by ctor).
         let ret = unsafe {
@@ -408,8 +444,9 @@
     }
 
     /// Safe wrapper around `fdt_delprop()` (C function).
-    fn delprop(&mut self, node: c_int, name: &CStr) -> Result<()> {
+    fn delprop(&mut self, node: NodeOffset, name: &CStr) -> Result<()> {
         let fdt = self.as_fdt_slice_mut().as_mut_ptr().cast();
+        let node = node.into();
         let name = name.as_ptr();
         // SAFETY: Accesses are constrained to the DT totalsize (validated by ctor) when the
         // library locates the node's property. Removing the property may shift the offsets of
@@ -421,8 +458,9 @@
     }
 
     /// Safe wrapper around `fdt_nop_property()` (C function).
-    fn nop_property(&mut self, node: c_int, name: &CStr) -> Result<()> {
+    fn nop_property(&mut self, node: NodeOffset, name: &CStr) -> Result<()> {
         let fdt = self.as_fdt_slice_mut().as_mut_ptr().cast();
+        let node = node.into();
         let name = name.as_ptr();
         // SAFETY: Accesses are constrained to the DT totalsize (validated by ctor) when the
         // library locates the node's property.
diff --git a/libs/libfdt/src/safe_types.rs b/libs/libfdt/src/safe_types.rs
new file mode 100644
index 0000000..3848542
--- /dev/null
+++ b/libs/libfdt/src/safe_types.rs
@@ -0,0 +1,228 @@
+// 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.
+
+//! Safe zero-cost wrappers around integer values used by libfdt.
+
+use core::ffi::c_int;
+
+use crate::result::FdtRawResult;
+use crate::{FdtError, Result};
+
+use zerocopy::byteorder::big_endian;
+use zerocopy::{FromBytes, FromZeroes};
+
+macro_rules! assert_offset_eq {
+    // TODO(stable_feature(offset_of)): mem::offset_of
+    // TODO(const_feature(assert_eq)): assert_eq!()
+    ($t:ty, $u:ty, $id:ident) => {
+        static_assertions::const_assert_eq!(
+            memoffset::offset_of!($t, $id),
+            memoffset::offset_of!($u, $id),
+        );
+    };
+}
+
+/// Thin wrapper around `libfdt_bindgen::fdt_header` for transparent endianness handling.
+#[repr(C)]
+#[derive(Debug, FromZeroes, FromBytes)]
+pub struct FdtHeader {
+    /// magic word FDT_MAGIC
+    pub magic: big_endian::U32,
+    /// total size of DT block
+    pub totalsize: big_endian::U32,
+    /// offset to structure
+    pub off_dt_struct: big_endian::U32,
+    /// offset to strings
+    pub off_dt_strings: big_endian::U32,
+    /// offset to memory reserve map
+    pub off_mem_rsvmap: big_endian::U32,
+    /// format version
+    pub version: big_endian::U32,
+    /// last compatible version
+    pub last_comp_version: big_endian::U32,
+    /* version 2 fields below */
+    /// Which physical CPU id we're booting on
+    pub boot_cpuid_phys: big_endian::U32,
+    /* version 3 fields below */
+    /// size of the strings block
+    pub size_dt_strings: big_endian::U32,
+    /* version 17 fields below */
+    /// size of the structure block
+    pub size_dt_struct: big_endian::U32,
+}
+assert_offset_eq!(libfdt_bindgen::fdt_header, FdtHeader, magic);
+assert_offset_eq!(libfdt_bindgen::fdt_header, FdtHeader, totalsize);
+assert_offset_eq!(libfdt_bindgen::fdt_header, FdtHeader, off_dt_struct);
+assert_offset_eq!(libfdt_bindgen::fdt_header, FdtHeader, off_dt_strings);
+assert_offset_eq!(libfdt_bindgen::fdt_header, FdtHeader, off_mem_rsvmap);
+assert_offset_eq!(libfdt_bindgen::fdt_header, FdtHeader, version);
+assert_offset_eq!(libfdt_bindgen::fdt_header, FdtHeader, last_comp_version);
+assert_offset_eq!(libfdt_bindgen::fdt_header, FdtHeader, boot_cpuid_phys);
+assert_offset_eq!(libfdt_bindgen::fdt_header, FdtHeader, size_dt_strings);
+assert_offset_eq!(libfdt_bindgen::fdt_header, FdtHeader, size_dt_struct);
+
+impl AsRef<FdtHeader> for libfdt_bindgen::fdt_header {
+    fn as_ref(&self) -> &FdtHeader {
+        let ptr = self as *const _ as *const _;
+        // SAFETY: Types have the same layout (u32 and U32 have the same storage) and alignment.
+        unsafe { &*ptr }
+    }
+}
+
+/// Wrapper guaranteed to contain a valid phandle.
+#[repr(transparent)]
+#[derive(Debug, Copy, Clone, Eq, PartialEq, Ord, PartialOrd)]
+pub struct Phandle(u32);
+
+impl Phandle {
+    /// Minimum valid value for device tree phandles.
+    pub const MIN: Self = Self(1);
+    /// Maximum valid value for device tree phandles.
+    pub const MAX: Self = Self(libfdt_bindgen::FDT_MAX_PHANDLE);
+
+    /// Creates a new Phandle
+    pub const fn new(value: u32) -> Option<Self> {
+        if Self::MIN.0 <= value && value <= Self::MAX.0 {
+            Some(Self(value))
+        } else {
+            None
+        }
+    }
+}
+
+impl From<Phandle> for u32 {
+    fn from(phandle: Phandle) -> u32 {
+        phandle.0
+    }
+}
+
+impl TryFrom<u32> for Phandle {
+    type Error = FdtError;
+
+    fn try_from(value: u32) -> Result<Self> {
+        Self::new(value).ok_or(FdtError::BadPhandle)
+    }
+}
+
+impl TryFrom<FdtRawResult> for Phandle {
+    type Error = FdtError;
+
+    fn try_from(res: FdtRawResult) -> Result<Self> {
+        Self::new(res.try_into()?).ok_or(FdtError::BadPhandle)
+    }
+}
+
+/// Safe zero-cost wrapper around libfdt device tree node offsets.
+///
+/// This type should only be obtained from properly wrapped successful libfdt calls.
+#[repr(transparent)]
+#[derive(Debug, Copy, Clone, Eq, PartialEq, Ord, PartialOrd)]
+pub struct NodeOffset(c_int);
+
+impl NodeOffset {
+    /// Offset of the root node; 0, by definition.
+    pub const ROOT: Self = Self(0);
+}
+
+impl TryFrom<FdtRawResult> for NodeOffset {
+    type Error = FdtError;
+
+    fn try_from(res: FdtRawResult) -> Result<Self> {
+        Ok(Self(res.try_into()?))
+    }
+}
+
+impl TryFrom<FdtRawResult> for Option<NodeOffset> {
+    type Error = FdtError;
+
+    fn try_from(res: FdtRawResult) -> Result<Self> {
+        match res.try_into() {
+            Ok(n) => Ok(Some(n)),
+            Err(FdtError::NotFound) => Ok(None),
+            Err(e) => Err(e),
+        }
+    }
+}
+
+impl From<NodeOffset> for c_int {
+    fn from(offset: NodeOffset) -> Self {
+        offset.0
+    }
+}
+
+/// Safe zero-cost wrapper around libfdt device tree property offsets.
+///
+/// This type should only be obtained from properly wrapped successful libfdt calls.
+#[repr(transparent)]
+#[derive(Debug, Copy, Clone, Eq, PartialEq, Ord, PartialOrd)]
+pub struct PropOffset(c_int);
+
+impl TryFrom<FdtRawResult> for PropOffset {
+    type Error = FdtError;
+
+    fn try_from(res: FdtRawResult) -> Result<Self> {
+        Ok(Self(res.try_into()?))
+    }
+}
+
+impl TryFrom<FdtRawResult> for Option<PropOffset> {
+    type Error = FdtError;
+
+    fn try_from(res: FdtRawResult) -> Result<Self> {
+        match res.try_into() {
+            Ok(n) => Ok(Some(n)),
+            Err(FdtError::NotFound) => Ok(None),
+            Err(e) => Err(e),
+        }
+    }
+}
+
+impl From<PropOffset> for c_int {
+    fn from(offset: PropOffset) -> Self {
+        offset.0
+    }
+}
+
+/// Safe zero-cost wrapper around libfdt device tree string offsets.
+///
+/// This type should only be obtained from properly wrapped successful libfdt calls.
+#[repr(transparent)]
+#[derive(Debug, Copy, Clone, Eq, PartialEq, Ord, PartialOrd)]
+pub struct StringOffset(pub c_int); // TODO(ptosi): Move fdt_property wrapper here and remove pub.
+
+impl TryFrom<FdtRawResult> for StringOffset {
+    type Error = FdtError;
+
+    fn try_from(res: FdtRawResult) -> Result<Self> {
+        Ok(Self(res.try_into()?))
+    }
+}
+
+impl TryFrom<FdtRawResult> for Option<StringOffset> {
+    type Error = FdtError;
+
+    fn try_from(res: FdtRawResult) -> Result<Self> {
+        match res.try_into() {
+            Ok(n) => Ok(Some(n)),
+            Err(FdtError::NotFound) => Ok(None),
+            Err(e) => Err(e),
+        }
+    }
+}
+
+impl From<StringOffset> for c_int {
+    fn from(offset: StringOffset) -> Self {
+        offset.0
+    }
+}
diff --git a/libs/libfdt/tests/api_test.rs b/libs/libfdt/tests/api_test.rs
index c2ddda0..8f5b76d 100644
--- a/libs/libfdt/tests/api_test.rs
+++ b/libs/libfdt/tests/api_test.rs
@@ -438,6 +438,22 @@
 }
 
 #[test]
+fn node_mut_delete_and_next_node_with_last_node() {
+    let mut data = fs::read(TEST_TREE_WITH_EMPTY_MEMORY_RANGE_PATH).unwrap();
+    let fdt = Fdt::from_mut_slice(&mut data).unwrap();
+
+    let mut iter = fdt.root_mut().unwrap().next_node(0).unwrap();
+    while let Some((node, depth)) = iter {
+        iter = node.delete_and_next_node(depth).unwrap();
+    }
+
+    let root = fdt.root().unwrap();
+    let all_descendants: Vec<_> =
+        root.descendants().map(|(node, depth)| (node.name(), depth)).collect();
+    assert!(all_descendants.is_empty(), "{all_descendants:?}");
+}
+
+#[test]
 #[ignore] // Borrow checker test. Compilation success is sufficient.
 fn node_name_lifetime() {
     let data = fs::read(TEST_TREE_PHANDLE_PATH).unwrap();
diff --git a/pvmfw/src/fdt.rs b/pvmfw/src/fdt.rs
index 311f467..146d012 100644
--- a/pvmfw/src/fdt.rs
+++ b/pvmfw/src/fdt.rs
@@ -59,6 +59,8 @@
     InvalidCpuCount(usize),
     /// Invalid VCpufreq Range.
     InvalidVcpufreq(u64, u64),
+    /// Forbidden /avf/untrusted property.
+    ForbiddenUntrustedProp(&'static CStr),
 }
 
 impl fmt::Display for FdtValidationError {
@@ -68,6 +70,9 @@
             Self::InvalidVcpufreq(addr, size) => {
                 write!(f, "Invalid vcpufreq region: ({addr:#x}, {size:#x})")
             }
+            Self::ForbiddenUntrustedProp(name) => {
+                write!(f, "Forbidden /avf/untrusted property '{name:?}'")
+            }
         }
     }
 }
@@ -420,6 +425,24 @@
     Ok(())
 }
 
+/// Reads the /avf/untrusted DT node, which the host can use to pass properties (no subnodes) to
+/// the guest that don't require being validated by pvmfw.
+fn parse_untrusted_props(fdt: &Fdt) -> libfdt::Result<BTreeMap<CString, Vec<u8>>> {
+    let mut props = BTreeMap::new();
+    if let Some(node) = fdt.node(cstr!("/avf/untrusted"))? {
+        for property in node.properties()? {
+            let name = property.name()?;
+            let value = property.value()?;
+            props.insert(CString::from(name), value.to_vec());
+        }
+        if node.subnodes()?.next().is_some() {
+            warn!("Discarding unexpected /avf/untrusted subnodes.");
+        }
+    }
+
+    Ok(props)
+}
+
 /// Read candidate properties' names from DT which could be overlaid
 fn parse_vm_ref_dt(fdt: &Fdt) -> libfdt::Result<BTreeMap<CString, Vec<u8>>> {
     let mut property_map = BTreeMap::new();
@@ -436,6 +459,19 @@
     Ok(property_map)
 }
 
+fn validate_untrusted_props(props: &BTreeMap<CString, Vec<u8>>) -> Result<(), FdtValidationError> {
+    const FORBIDDEN_PROPS: &[&CStr] =
+        &[cstr!("compatible"), cstr!("linux,phandle"), cstr!("phandle")];
+
+    for name in FORBIDDEN_PROPS {
+        if props.contains_key(*name) {
+            return Err(FdtValidationError::ForbiddenUntrustedProp(name));
+        }
+    }
+
+    Ok(())
+}
+
 /// Overlay VM reference DT into VM DT based on the props_info. Property is overlaid in vm_dt only
 /// when it exists both in vm_ref_dt and props_info. If the values mismatch, it returns error.
 fn validate_vm_ref_dt(
@@ -837,6 +873,23 @@
     node.setprop_inplace(cstr!("interrupts"), value.as_bytes())
 }
 
+fn patch_untrusted_props(fdt: &mut Fdt, props: &BTreeMap<CString, Vec<u8>>) -> libfdt::Result<()> {
+    let avf_node = if let Some(node) = fdt.node_mut(cstr!("/avf"))? {
+        node
+    } else {
+        fdt.root_mut()?.add_subnode(cstr!("avf"))?
+    };
+
+    // The node shouldn't already be present; if it is, return the error.
+    let mut node = avf_node.add_subnode(cstr!("untrusted"))?;
+
+    for (name, value) in props {
+        node.setprop(name, value)?;
+    }
+
+    Ok(())
+}
+
 #[derive(Debug)]
 struct VcpufreqInfo {
     addr: u64,
@@ -864,6 +917,7 @@
     serial_info: SerialInfo,
     pub swiotlb_info: SwiotlbInfo,
     device_assignment: Option<DeviceAssignmentInfo>,
+    untrusted_props: BTreeMap<CString, Vec<u8>>,
     vm_ref_dt_props_info: BTreeMap<CString, Vec<u8>>,
     vcpufreq_info: Option<VcpufreqInfo>,
 }
@@ -1023,6 +1077,15 @@
         None => None,
     };
 
+    let untrusted_props = parse_untrusted_props(fdt).map_err(|e| {
+        error!("Failed to read untrusted properties: {e}");
+        RebootReason::InvalidFdt
+    })?;
+    validate_untrusted_props(&untrusted_props).map_err(|e| {
+        error!("Failed to validate untrusted properties: {e}");
+        RebootReason::InvalidFdt
+    })?;
+
     let vm_ref_dt_props_info = parse_vm_ref_dt(fdt).map_err(|e| {
         error!("Failed to read names of properties under /avf from DT: {e}");
         RebootReason::InvalidFdt
@@ -1039,6 +1102,7 @@
         serial_info,
         swiotlb_info,
         device_assignment,
+        untrusted_props,
         vm_ref_dt_props_info,
         vcpufreq_info,
     })
@@ -1097,6 +1161,10 @@
             RebootReason::InvalidFdt
         })?;
     }
+    patch_untrusted_props(fdt, &info.untrusted_props).map_err(|e| {
+        error!("Failed to patch untrusted properties: {e}");
+        RebootReason::InvalidFdt
+    })?;
 
     Ok(())
 }
diff --git a/rialto/src/main.rs b/rialto/src/main.rs
index ad9b776..48b69b3 100644
--- a/rialto/src/main.rs
+++ b/rialto/src/main.rs
@@ -177,7 +177,9 @@
 
     let mut vsock_stream = VsockStream::new(socket_device, host_addr())?;
     while let ServiceVmRequest::Process(req) = vsock_stream.read_request()? {
+        info!("Received request: {}", req.name());
         let response = process_request(req, bcc_handover.as_ref());
+        info!("Sending response: {}", response.name());
         vsock_stream.write_response(&response)?;
         vsock_stream.flush()?;
     }
diff --git a/service_vm/comm/src/message.rs b/service_vm/comm/src/message.rs
index 80a9608..9f83b78 100644
--- a/service_vm/comm/src/message.rs
+++ b/service_vm/comm/src/message.rs
@@ -56,6 +56,18 @@
     RequestClientVmAttestation(ClientVmAttestationParams),
 }
 
+impl Request {
+    /// Returns the name of the request.
+    pub fn name(&self) -> &'static str {
+        match self {
+            Self::Reverse(_) => "Reverse",
+            Self::GenerateEcdsaP256KeyPair => "GenerateEcdsaP256KeyPair",
+            Self::GenerateCertificateRequest(_) => "GenerateCertificateRequest",
+            Self::RequestClientVmAttestation(_) => "RequestClientVmAttestation",
+        }
+    }
+}
+
 /// Represents the params passed to `Request::RequestClientVmAttestation`.
 #[derive(Clone, Debug, Serialize, Deserialize)]
 pub struct ClientVmAttestationParams {
@@ -98,6 +110,19 @@
     Err(RequestProcessingError),
 }
 
+impl Response {
+    /// Returns the name of the response.
+    pub fn name(&self) -> &'static str {
+        match self {
+            Self::Reverse(_) => "Reverse",
+            Self::GenerateEcdsaP256KeyPair(_) => "GenerateEcdsaP256KeyPair",
+            Self::GenerateCertificateRequest(_) => "GenerateCertificateRequest",
+            Self::RequestClientVmAttestation(_) => "RequestClientVmAttestation",
+            Self::Err(_) => "Err",
+        }
+    }
+}
+
 /// Errors related to request processing.
 #[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
 pub enum RequestProcessingError {
diff --git a/tests/benchmark/src/java/com/android/microdroid/benchmark/MicrodroidBenchmarks.java b/tests/benchmark/src/java/com/android/microdroid/benchmark/MicrodroidBenchmarks.java
index 2d52732..77cae32 100644
--- a/tests/benchmark/src/java/com/android/microdroid/benchmark/MicrodroidBenchmarks.java
+++ b/tests/benchmark/src/java/com/android/microdroid/benchmark/MicrodroidBenchmarks.java
@@ -415,8 +415,9 @@
                 long guestRss = 0;
                 long guestPss = 0;
                 boolean hasGuestMaps = false;
-                for (ProcessUtil.SMapEntry entry :
-                        ProcessUtil.getProcessSmaps(vmPid, shellExecutor)) {
+                List<ProcessUtil.SMapEntry> smaps =
+                        ProcessUtil.getProcessSmaps(vmPid, shellExecutor);
+                for (ProcessUtil.SMapEntry entry : smaps) {
                     long rss = entry.metrics.get("Rss");
                     long pss = entry.metrics.get("Pss");
                     if (entry.name.contains("crosvm_guest")) {
@@ -429,8 +430,12 @@
                     }
                 }
                 if (!hasGuestMaps) {
+                    StringBuilder sb = new StringBuilder();
+                    for (ProcessUtil.SMapEntry entry : smaps) {
+                        sb.append(entry.toString());
+                    }
                     throw new IllegalStateException(
-                            "found no crosvm_guest smap entry in crosvm process");
+                            "found no crosvm_guest smap entry in crosvm process: " + sb);
                 }
                 mHostRss = hostRss;
                 mHostPss = hostPss;
diff --git a/tests/helper/src/java/com/android/microdroid/test/common/ProcessUtil.java b/tests/helper/src/java/com/android/microdroid/test/common/ProcessUtil.java
index c72d91e..e058674 100644
--- a/tests/helper/src/java/com/android/microdroid/test/common/ProcessUtil.java
+++ b/tests/helper/src/java/com/android/microdroid/test/common/ProcessUtil.java
@@ -33,13 +33,24 @@
     public static class SMapEntry {
         public String name;
         public Map<String, Long> metrics;
+
+        @Override
+        public String toString() {
+            StringBuilder sb = new StringBuilder();
+            sb.append("name: " + name + "\n");
+            metrics.forEach(
+                    (k, v) -> {
+                        sb.append("  " + k + ": " + v + "\n");
+                    });
+            return sb.toString();
+        }
     }
 
     /** Gets metrics key and values mapping of specified process id */
     public static List<SMapEntry> getProcessSmaps(int pid, Function<String, String> shellExecutor)
             throws IOException {
         String path = "/proc/" + pid + "/smaps";
-        return parseMemoryInfo(shellExecutor.apply("cat " + path + " || true"));
+        return parseMemoryInfo(shellExecutor.apply("cat " + path));
     }
 
     /** Gets metrics key and values mapping of specified process id */
diff --git a/tests/helper/src/java/com/android/microdroid/test/device/MicrodroidDeviceTestBase.java b/tests/helper/src/java/com/android/microdroid/test/device/MicrodroidDeviceTestBase.java
index 8e11218..2c72561 100644
--- a/tests/helper/src/java/com/android/microdroid/test/device/MicrodroidDeviceTestBase.java
+++ b/tests/helper/src/java/com/android/microdroid/test/device/MicrodroidDeviceTestBase.java
@@ -62,6 +62,7 @@
     private static final String TAG = "MicrodroidDeviceTestBase";
     private final String MAX_PERFORMANCE_TASK_PROFILE = "CPUSET_SP_TOP_APP";
 
+    protected static final String KERNEL_VERSION = SystemProperties.get("ro.kernel.version");
     protected static final Set<String> SUPPORTED_GKI_VERSIONS =
             Collections.unmodifiableSet(new HashSet(Arrays.asList("android14-6.1")));
 
@@ -110,7 +111,7 @@
         }
     }
 
-    private Context mCtx;
+    private final Context mCtx = ApplicationProvider.getApplicationContext();
     private boolean mProtectedVm;
     private String mGki;
 
@@ -165,10 +166,7 @@
     }
 
     public void prepareTestSetup(boolean protectedVm, String gki) {
-        mCtx = ApplicationProvider.getApplicationContext();
-        assume().withMessage("Device doesn't support AVF")
-                .that(mCtx.getPackageManager().hasSystemFeature(FEATURE_VIRTUALIZATION_FRAMEWORK))
-                .isTrue();
+        assumeFeatureVirtualizationFramework();
 
         mProtectedVm = protectedVm;
         mGki = gki;
@@ -194,6 +192,18 @@
         }
     }
 
+    protected void assumeFeatureVirtualizationFramework() {
+        assume().withMessage("Device doesn't support AVF")
+                .that(mCtx.getPackageManager().hasSystemFeature(FEATURE_VIRTUALIZATION_FRAMEWORK))
+                .isTrue();
+    }
+
+    protected void assumeSupportedDevice() {
+        assume().withMessage("Skip on 5.4 kernel. b/218303240")
+                .that(KERNEL_VERSION)
+                .isNotEqualTo("5.4");
+    }
+
     public abstract static class VmEventListener implements VirtualMachineCallback {
         private ExecutorService mExecutorService = Executors.newSingleThreadExecutor();
         private OptionalLong mVcpuStartedNanoTime = OptionalLong.empty();
diff --git a/tests/hostside/Android.bp b/tests/hostside/Android.bp
index e3d9cbe..13a9925 100644
--- a/tests/hostside/Android.bp
+++ b/tests/hostside/Android.bp
@@ -37,6 +37,8 @@
         "lpunpack",
         "sign_virt_apex",
         "simg2img",
+        "dtdiff",
+        "dtc", // for dtdiff
     ],
     // java_test_host doesn't have data_native_libs but jni_libs can be used to put
     // native modules under ./lib directory.
@@ -51,5 +53,6 @@
         "liblp",
         "libsparse",
         "libz",
+        "libfdt", // for dtc
     ],
 }
diff --git a/tests/hostside/java/com/android/microdroid/test/MicrodroidHostTests.java b/tests/hostside/java/com/android/microdroid/test/MicrodroidHostTests.java
index 2cd4577..4503cd3 100644
--- a/tests/hostside/java/com/android/microdroid/test/MicrodroidHostTests.java
+++ b/tests/hostside/java/com/android/microdroid/test/MicrodroidHostTests.java
@@ -47,6 +47,7 @@
 import com.android.tradefed.device.TestDevice;
 import com.android.tradefed.testtype.DeviceJUnit4ClassRunner.TestMetrics;
 import com.android.tradefed.util.CommandResult;
+import com.android.tradefed.util.CommandStatus;
 import com.android.tradefed.util.FileUtil;
 import com.android.tradefed.util.RunUtil;
 import com.android.tradefed.util.xml.AbstractXmlParser;
@@ -985,23 +986,71 @@
 
     @Test
     public void testDeviceAssignment() throws Exception {
-        assumeProtectedVm();
+        // Check for preconditions
         assumeVfioPlatformSupported();
 
         List<String> devices = getAssignableDevices();
         assumeFalse("no assignable devices", devices.isEmpty());
 
+        String vmFdtPath = "/sys/firmware/fdt";
+        File testDir = FileUtil.createTempDir("device_assignment_test");
+        File baseFdtFile = new File(testDir, "base_fdt.dtb");
+        File fdtFile = new File(testDir, "fdt.dtb");
+
+        // Generates baseline DT
+        launchWithDeviceAssignment(/* device= */ null);
+        assertThat(mMicrodroidDevice.pullFile(vmFdtPath, baseFdtFile)).isTrue();
+        getAndroidDevice().shutdownMicrodroid(mMicrodroidDevice);
+
+        // Prepares to run dtdiff. It requires dtc.
+        File dtdiff = findTestFile("dtdiff");
+        RunUtil runner = new RunUtil();
+        String separator = System.getProperty("path.separator");
+        String path = dtdiff.getParent() + separator + System.getenv("PATH");
+        runner.setEnvVariable("PATH", path);
+
+        // Try assign devices one by one
+        for (String device : devices) {
+            assertThat(device).isNotNull();
+            launchWithDeviceAssignment(device);
+            assertThat(mMicrodroidDevice.pullFile(vmFdtPath, fdtFile)).isTrue();
+            getAndroidDevice().shutdownMicrodroid(mMicrodroidDevice);
+
+            CommandResult result =
+                    runner.runTimedCmd(
+                            500,
+                            dtdiff.getAbsolutePath(),
+                            baseFdtFile.getPath(),
+                            fdtFile.getPath());
+
+            assertWithMessage(
+                            "VM's device tree hasn't changed when assigning "
+                                    + device
+                                    + ", result="
+                                    + result)
+                    .that(result.getStatus())
+                    .isNotEqualTo(CommandStatus.SUCCESS);
+        }
+
+        mMicrodroidDevice = null;
+    }
+
+    private void launchWithDeviceAssignment(String device) throws Exception {
         final String configPath = "assets/" + mOs + "/vm_config.json";
-        mMicrodroidDevice =
+
+        MicrodroidBuilder builder =
                 MicrodroidBuilder.fromDevicePath(getPathForPackage(PACKAGE_NAME), configPath)
                         .debugLevel("full")
                         .memoryMib(minMemorySize())
                         .cpuTopology("match_host")
-                        .protectedVm(true)
-                        .addAssignableDevice(devices.get(0))
-                        .build(getAndroidDevice());
+                        .protectedVm(mProtectedVm);
+        if (device != null) {
+            builder.addAssignableDevice(device);
+        }
+        mMicrodroidDevice = builder.build(getAndroidDevice());
 
-        mMicrodroidDevice.waitForBootComplete(BOOT_COMPLETE_TIMEOUT);
+        assertThat(mMicrodroidDevice.waitForBootComplete(BOOT_COMPLETE_TIMEOUT)).isTrue();
+        assertThat(mMicrodroidDevice.enableAdbRoot()).isTrue();
     }
 
     @Test
@@ -1035,6 +1084,13 @@
         }
 
         mOs = (mGki != null) ? "microdroid_gki-" + mGki : "microdroid";
+
+        new CommandRunner(getDevice())
+                .tryRun(
+                        "pm",
+                        "grant",
+                        SHELL_PACKAGE_NAME,
+                        "android.permission.USE_CUSTOM_VIRTUAL_MACHINE");
     }
 
     @After
@@ -1049,21 +1105,13 @@
                 mTestLogs, getDevice(), LOG_PATH, "vm.log-" + mTestName.getMethodName());
 
         getDevice().uninstallPackage(PACKAGE_NAME);
-
-        // testCustomVirtualMachinePermission revokes this permission. Grant it again as cleanup
-        new CommandRunner(getDevice())
-                .tryRun(
-                        "pm",
-                        "grant",
-                        SHELL_PACKAGE_NAME,
-                        "android.permission.USE_CUSTOM_VIRTUAL_MACHINE");
     }
 
-    private void assumeProtectedVm() throws Exception {
+    private void assumeProtectedVm() {
         assumeTrue("This test is only for protected VM.", mProtectedVm);
     }
 
-    private void assumeNonProtectedVm() throws Exception {
+    private void assumeNonProtectedVm() {
         assumeFalse("This test is only for non-protected VM.", mProtectedVm);
     }
 
diff --git a/tests/testapk/src/java/com/android/microdroid/test/MicrodroidCapabilitiesTest.java b/tests/testapk/src/java/com/android/microdroid/test/MicrodroidCapabilitiesTest.java
new file mode 100644
index 0000000..a0826c9
--- /dev/null
+++ b/tests/testapk/src/java/com/android/microdroid/test/MicrodroidCapabilitiesTest.java
@@ -0,0 +1,58 @@
+/*
+ * 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.
+ */
+package com.android.microdroid.test;
+
+import static com.google.common.truth.Truth.assertWithMessage;
+
+import android.system.virtualmachine.VirtualMachineManager;
+
+import com.android.compatibility.common.util.CddTest;
+import com.android.microdroid.test.device.MicrodroidDeviceTestBase;
+
+import org.junit.Test;
+import org.junit.runner.RunWith;
+import org.junit.runners.JUnit4;
+
+/**
+ * Test the advertised AVF capabilities include the ability to start some type of VM.
+ *
+ * <p>Tests in MicrodroidTests run on either protected or non-protected VMs, provided they are
+ * supported. If neither is they are all skipped. So we need a separate test (that doesn't call
+ * {@link #prepareTestSetup}) to make sure that at least one of these is available.
+ */
+@RunWith(JUnit4.class)
+public class MicrodroidCapabilitiesTest extends MicrodroidDeviceTestBase {
+    @Test
+    @CddTest(requirements = {"9.17/C-1-1", "9.17/C-2-1"})
+    public void supportForProtectedOrNonProtectedVms() {
+        assumeSupportedDevice();
+
+        // (There's a test for devices that don't expose the system feature over in
+        // NoMicrodroidTest.)
+        assumeFeatureVirtualizationFramework();
+
+        int capabilities = getVirtualMachineManager().getCapabilities();
+        int vmCapabilities =
+                capabilities
+                        & (VirtualMachineManager.CAPABILITY_PROTECTED_VM
+                                | VirtualMachineManager.CAPABILITY_NON_PROTECTED_VM);
+        assertWithMessage(
+                        "A device that has FEATURE_VIRTUALIZATION_FRAMEWORK must support at least"
+                                + " one of protected or non-protected VMs")
+                .that(vmCapabilities)
+                .isNotEqualTo(0);
+    }
+}
diff --git a/tests/testapk/src/java/com/android/microdroid/test/MicrodroidTests.java b/tests/testapk/src/java/com/android/microdroid/test/MicrodroidTests.java
index 0687a7b..0132b0d 100644
--- a/tests/testapk/src/java/com/android/microdroid/test/MicrodroidTests.java
+++ b/tests/testapk/src/java/com/android/microdroid/test/MicrodroidTests.java
@@ -118,8 +118,6 @@
 
     @Rule public Timeout globalTimeout = Timeout.seconds(300);
 
-    private static final String KERNEL_VERSION = SystemProperties.get("ro.kernel.version");
-
     @Parameterized.Parameters(name = "protectedVm={0},gki={1}")
     public static Collection<Object[]> params() {
         List<Object[]> ret = new ArrayList<>();
@@ -142,13 +140,17 @@
     @Before
     public void setup() {
         prepareTestSetup(mProtectedVm, mGki);
-        // USE_CUSTOM_VIRTUAL_MACHINE permission has protection level signature|development, meaning
-        // that it will be automatically granted when test apk is installed. We have some tests
-        // checking the behavior when caller doesn't have this permission (e.g.
-        // createVmWithConfigRequiresPermission). Proactively revoke the permission so that such
-        // tests can pass when ran by itself, e.g.:
-        // atest com.android.microdroid.test.MicrodroidTests#createVmWithConfigRequiresPermission
-        revokePermission(VirtualMachine.USE_CUSTOM_VIRTUAL_MACHINE_PERMISSION);
+        if (mGki != null) {
+            // Using a non-default VM always needs the custom permission.
+            grantPermission(VirtualMachine.USE_CUSTOM_VIRTUAL_MACHINE_PERMISSION);
+        } else {
+            // USE_CUSTOM_VIRTUAL_MACHINE permission has protection level signature|development,
+            // meaning that it will be automatically granted when test apk is installed.
+            // But most callers shouldn't need this permission, so by default we run tests with it
+            // revoked.
+            // Tests that rely on the state of the permission should explicitly grant or revoke it.
+            revokePermission(VirtualMachine.USE_CUSTOM_VIRTUAL_MACHINE_PERMISSION);
+        }
     }
 
     @After
@@ -590,6 +592,9 @@
                 .isFalse();
         assertConfigCompatible(baseline, newBaselineBuilder().setPayloadBinaryName("different"))
                 .isFalse();
+        assertConfigCompatible(
+                        baseline, newBaselineBuilder().setVendorDiskImage(new File("/foo/bar")))
+                .isFalse();
         int capabilities = getVirtualMachineManager().getCapabilities();
         if ((capabilities & CAPABILITY_PROTECTED_VM) != 0
                 && (capabilities & CAPABILITY_NON_PROTECTED_VM) != 0) {
@@ -639,6 +644,7 @@
         VirtualMachineConfig.Builder otherOsBuilder =
                 newBaselineBuilder().setOs("microdroid_gki-android14-6.1");
         assertConfigCompatible(microdroidOsConfig, otherOsBuilder).isFalse();
+
     }
 
     private VirtualMachineConfig.Builder newBaselineBuilder() {
@@ -778,6 +784,7 @@
     })
     public void createVmWithConfigRequiresPermission() throws Exception {
         assumeSupportedDevice();
+        revokePermission(VirtualMachine.USE_CUSTOM_VIRTUAL_MACHINE_PERMISSION);
 
         VirtualMachineConfig config =
                 newVmConfigBuilderWithPayloadConfig("assets/" + os() + "/vm_config.json")
@@ -2136,6 +2143,7 @@
         assumeFalse(
                 "boot with vendor partition is failing in HWASAN enabled Microdroid.", isHwasan());
         assumeFeatureEnabled(VirtualMachineManager.FEATURE_VENDOR_MODULES);
+        revokePermission(VirtualMachine.USE_CUSTOM_VIRTUAL_MACHINE_PERMISSION);
 
         File vendorDiskImage =
                 new File("/data/local/tmp/cts/microdroid/test_microdroid_vendor_image.img");
@@ -2312,10 +2320,4 @@
         return 0;
     }
 
-    private void assumeSupportedDevice() {
-        assume()
-                .withMessage("Skip on 5.4 kernel. b/218303240")
-                .that(KERNEL_VERSION)
-                .isNotEqualTo("5.4");
-    }
 }
diff --git a/virtualizationmanager/Android.bp b/virtualizationmanager/Android.bp
index 48b5cd1..bb6ccb7 100644
--- a/virtualizationmanager/Android.bp
+++ b/virtualizationmanager/Android.bp
@@ -32,9 +32,11 @@
         "libandroid_logger",
         "libanyhow",
         "libapkverify",
+        "libavf_features",
         "libavflog",
         "libbase_rust",
         "libbinder_rs",
+        "libcfg_if",
         "libclap",
         "libcstr",
         "libcommand_fds",
diff --git a/virtualizationmanager/src/aidl.rs b/virtualizationmanager/src/aidl.rs
index a2194cc..88700ec 100644
--- a/virtualizationmanager/src/aidl.rs
+++ b/virtualizationmanager/src/aidl.rs
@@ -35,10 +35,6 @@
     IVirtualMachine::{BnVirtualMachine, IVirtualMachine},
     IVirtualMachineCallback::IVirtualMachineCallback,
     IVirtualizationService::IVirtualizationService,
-    IVirtualizationService::FEATURE_MULTI_TENANT,
-    IVirtualizationService::FEATURE_VENDOR_MODULES,
-    IVirtualizationService::FEATURE_DICE_CHANGES,
-    IVirtualizationService::FEATURE_REMOTE_ATTESTATION,
     MemoryTrimLevel::MemoryTrimLevel,
     Partition::Partition,
     PartitionType::PartitionType,
@@ -306,19 +302,7 @@
     /// Returns whether given feature is enabled
     fn isFeatureEnabled(&self, feature: &str) -> binder::Result<bool> {
         check_manage_access()?;
-
-        // This approach is quite cumbersome, but will do the work for the short term.
-        // TODO(b/298012279): make this scalable.
-        match feature {
-            FEATURE_DICE_CHANGES => Ok(cfg!(dice_changes)),
-            FEATURE_MULTI_TENANT => Ok(cfg!(multi_tenant)),
-            FEATURE_REMOTE_ATTESTATION => Ok(cfg!(remote_attestation)),
-            FEATURE_VENDOR_MODULES => Ok(cfg!(vendor_modules)),
-            _ => {
-                warn!("unknown feature {feature}");
-                Ok(false)
-            }
-        }
+        Ok(avf_features::is_feature_enabled(feature))
     }
 
     fn enableTestAttestation(&self) -> binder::Result<()> {
@@ -603,10 +587,14 @@
             } else {
                 // Additional custom features not included in CustomConfig:
                 // - specifying a config file;
-                // - specifying extra APKs.
+                // - specifying extra APKs;
+                // - specifying an OS other than Microdroid.
                 match &config.payload {
                     Payload::ConfigPath(_) => true,
-                    Payload::PayloadConfig(payload_config) => !payload_config.extraApks.is_empty(),
+                    Payload::PayloadConfig(payload_config) => {
+                        !payload_config.extraApks.is_empty()
+                            || payload_config.osName != MICRODROID_OS_NAME
+                    }
                 }
             }
         }
diff --git a/virtualizationmanager/src/crosvm.rs b/virtualizationmanager/src/crosvm.rs
index 2c23441..3380df3 100644
--- a/virtualizationmanager/src/crosvm.rs
+++ b/virtualizationmanager/src/crosvm.rs
@@ -450,20 +450,20 @@
                 let mut vm_metric = self.vm_metric.lock().unwrap();
 
                 // Get CPU Information
-                if let Ok(guest_time) = get_guest_time(pid) {
-                    vm_metric.cpu_guest_time = Some(guest_time);
-                } else {
-                    error!("Failed to parse /proc/[pid]/stat");
+                match get_guest_time(pid) {
+                    Ok(guest_time) => vm_metric.cpu_guest_time = Some(guest_time),
+                    Err(e) => error!("Failed to get guest CPU time: {e:?}"),
                 }
 
                 // Get Memory Information
-                if let Ok(rss) = get_rss(pid) {
-                    vm_metric.rss = match &vm_metric.rss {
-                        Some(x) => Some(Rss::extract_max(x, &rss)),
-                        None => Some(rss),
+                match get_rss(pid) {
+                    Ok(rss) => {
+                        vm_metric.rss = match &vm_metric.rss {
+                            Some(x) => Some(Rss::extract_max(x, &rss)),
+                            None => Some(rss),
+                        }
                     }
-                } else {
-                    error!("Failed to parse /proc/[pid]/smaps");
+                    Err(e) => error!("Failed to get guest RSS: {}", e),
                 }
             }
 
@@ -812,7 +812,11 @@
     if config.host_cpu_topology {
         if cfg!(virt_cpufreq) {
             command.arg("--host-cpu-topology");
-            command.arg("--virt-cpufreq");
+            cfg_if::cfg_if! {
+                if #[cfg(any(target_arch = "aarch64"))] {
+                    command.arg("--virt-cpufreq");
+                }
+            }
         } else if let Some(cpus) = get_num_cpus() {
             command.arg("--cpus").arg(cpus.to_string());
         } else {
diff --git a/virtualizationservice/aidl/android/system/virtualizationservice/IVirtualizationService.aidl b/virtualizationservice/aidl/android/system/virtualizationservice/IVirtualizationService.aidl
index 7962bc3..f7bbf55 100644
--- a/virtualizationservice/aidl/android/system/virtualizationservice/IVirtualizationService.aidl
+++ b/virtualizationservice/aidl/android/system/virtualizationservice/IVirtualizationService.aidl
@@ -23,6 +23,7 @@
 
 interface IVirtualizationService {
     const String FEATURE_DICE_CHANGES = "com.android.kvm.DICE_CHANGES";
+    const String FEATURE_LLPVM_CHANGES = "com.android.kvm.LLPVM_CHANGES";
     const String FEATURE_MULTI_TENANT = "com.android.kvm.MULTI_TENANT";
     const String FEATURE_REMOTE_ATTESTATION = "com.android.kvm.REMOTE_ATTESTATION";
     const String FEATURE_VENDOR_MODULES = "com.android.kvm.VENDOR_MODULES";
diff --git a/virtualizationservice/src/aidl.rs b/virtualizationservice/src/aidl.rs
index d0c5d4a..c7ae5f0 100644
--- a/virtualizationservice/src/aidl.rs
+++ b/virtualizationservice/src/aidl.rs
@@ -14,38 +14,31 @@
 
 //! Implementation of the AIDL interface of the VirtualizationService.
 
-use crate::{get_calling_pid, get_calling_uid, REMOTELY_PROVISIONED_COMPONENT_SERVICE_NAME};
 use crate::atom::{forward_vm_booted_atom, forward_vm_creation_atom, forward_vm_exited_atom};
-use crate::rkpvm::{request_attestation, generate_ecdsa_p256_key_pair};
 use crate::remote_provisioning;
+use crate::rkpvm::{generate_ecdsa_p256_key_pair, request_attestation};
+use crate::{get_calling_pid, get_calling_uid, REMOTELY_PROVISIONED_COMPONENT_SERVICE_NAME};
 use android_os_permissions_aidl::aidl::android::os::IPermissionController;
-use android_system_virtualizationcommon::aidl::android::system::virtualizationcommon::Certificate::Certificate;
-use android_system_virtualizationservice::{
-    aidl::android::system::virtualizationservice::AssignableDevice::AssignableDevice,
-    aidl::android::system::virtualizationservice::VirtualMachineDebugInfo::VirtualMachineDebugInfo,
-    binder::ParcelFileDescriptor,
-};
-use android_system_virtualizationservice_internal::aidl::android::system::virtualizationservice_internal::{
-    AtomVmBooted::AtomVmBooted,
-    AtomVmCreationRequested::AtomVmCreationRequested,
-    AtomVmExited::AtomVmExited,
-    IBoundDevice::IBoundDevice,
-    IGlobalVmContext::{BnGlobalVmContext, IGlobalVmContext},
-    IVirtualizationServiceInternal::IVirtualizationServiceInternal,
-    IVfioHandler::{BpVfioHandler, IVfioHandler},
-    IVfioHandler::VfioDev::VfioDev,
-};
-use android_system_virtualmachineservice::aidl::android::system::virtualmachineservice::IVirtualMachineService::VM_TOMBSTONES_SERVICE_PORT;
+use android_system_virtualizationcommon::aidl::android::system::virtualizationcommon;
+use android_system_virtualizationservice::aidl::android::system::virtualizationservice;
+use android_system_virtualizationservice_internal as android_vs_internal;
+use android_system_virtualmachineservice::aidl::android::system::virtualmachineservice;
+use android_vs_internal::aidl::android::system::virtualizationservice_internal;
 use anyhow::{anyhow, ensure, Context, Result};
 use avflog::LogResult;
-use binder::{self, wait_for_interface, BinderFeatures, ExceptionCode, Interface, LazyServiceGuard, Status, Strong, IntoBinderResult};
-use service_vm_comm::Response;
+use binder::{
+    self, wait_for_interface, BinderFeatures, ExceptionCode, Interface, IntoBinderResult,
+    LazyServiceGuard, ParcelFileDescriptor, Status, Strong,
+};
 use lazy_static::lazy_static;
 use libc::VMADDR_CID_HOST;
 use log::{error, info, warn};
+use nix::unistd::{chown, Uid};
+use openssl::x509::X509;
 use rkpd_client::get_rkpd_attestation_key;
 use rustutils::system_properties;
 use serde::Deserialize;
+use service_vm_comm::Response;
 use std::collections::{HashMap, HashSet};
 use std::fs::{self, create_dir, remove_dir_all, remove_file, set_permissions, File, Permissions};
 use std::io::{Read, Write};
@@ -54,9 +47,22 @@
 use std::path::{Path, PathBuf};
 use std::sync::{Arc, Mutex, Weak};
 use tombstoned_client::{DebuggerdDumpType, TombstonedConnection};
+use virtualizationcommon::Certificate::Certificate;
+use virtualizationservice::{
+    AssignableDevice::AssignableDevice, VirtualMachineDebugInfo::VirtualMachineDebugInfo,
+};
+use virtualizationservice_internal::{
+    AtomVmBooted::AtomVmBooted,
+    AtomVmCreationRequested::AtomVmCreationRequested,
+    AtomVmExited::AtomVmExited,
+    IBoundDevice::IBoundDevice,
+    IGlobalVmContext::{BnGlobalVmContext, IGlobalVmContext},
+    IVfioHandler::VfioDev::VfioDev,
+    IVfioHandler::{BpVfioHandler, IVfioHandler},
+    IVirtualizationServiceInternal::IVirtualizationServiceInternal,
+};
+use virtualmachineservice::IVirtualMachineService::VM_TOMBSTONES_SERVICE_PORT;
 use vsock::{VsockListener, VsockStream};
-use nix::unistd::{chown, Uid};
-use openssl::x509::X509;
 
 /// The unique ID of a VM used (together with a port number) for vsock communication.
 pub type Cid = u32;
diff --git a/vm/Android.bp b/vm/Android.bp
index 04aff5e..c1d9b6b 100644
--- a/vm/Android.bp
+++ b/vm/Android.bp
@@ -12,6 +12,7 @@
     rustlibs: [
         "android.system.virtualizationservice-rust",
         "libanyhow",
+        "libavf_features",
         "libbinder_rs",
         "libclap",
         "libenv_logger",
diff --git a/vm/src/main.rs b/vm/src/main.rs
index de9291c..ea8c682 100644
--- a/vm/src/main.rs
+++ b/vm/src/main.rs
@@ -232,6 +232,8 @@
 
 #[derive(Parser)]
 enum Opt {
+    /// Check if the feature is enabled on device.
+    CheckFeatureEnabled { feature: String },
     /// Run a virtual machine with a config in APK
     RunApp {
         #[command(flatten)]
@@ -304,6 +306,13 @@
     virtmgr.connect().context("Failed to connect to VirtualizationService")
 }
 
+fn command_check_feature_enabled(feature: &str) {
+    println!(
+        "Feature {feature} is {}",
+        if avf_features::is_feature_enabled(feature) { "enabled" } else { "disabled" }
+    );
+}
+
 fn main() -> Result<(), Error> {
     env_logger::init();
     let opt = Opt::parse();
@@ -312,6 +321,10 @@
     ProcessState::start_thread_pool();
 
     match opt {
+        Opt::CheckFeatureEnabled { feature } => {
+            command_check_feature_enabled(&feature);
+            Ok(())
+        }
         Opt::RunApp { config } => command_run_app(config),
         Opt::RunMicrodroid { config } => command_run_microdroid(config),
         Opt::Run { config } => command_run(config),