Merge "Fix Microdroid boot time tests reporting NaN"
diff --git a/TEST_MAPPING b/TEST_MAPPING
index 14452a3..ea3ab74 100644
--- a/TEST_MAPPING
+++ b/TEST_MAPPING
@@ -34,7 +34,9 @@
     },
     {
       "name": "ComposBenchmarkApp"
-    },
+    }
+  ],
+  "avf-postsubmit-userdebug": [
     {
       "name": "AVFHostTestCases"
     }
diff --git a/encryptedstore/src/main.rs b/encryptedstore/src/main.rs
index 2f54534..96c80db 100644
--- a/encryptedstore/src/main.rs
+++ b/encryptedstore/src/main.rs
@@ -46,6 +46,7 @@
     let blkdevice = Path::new(matches.get_one::<String>("blkdevice").unwrap());
     let key = matches.get_one::<String>("key").unwrap();
     let mountpoint = Path::new(matches.get_one::<String>("mountpoint").unwrap());
+    // Note this error context is used in MicrodroidTests.
     encryptedstore_init(blkdevice, key, mountpoint).context(format!(
         "Unable to initialize encryptedstore on {:?} & mount at {:?}",
         blkdevice, mountpoint
diff --git a/libs/dice/src/bcc.rs b/libs/dice/src/bcc.rs
index b333781..a7ef882 100644
--- a/libs/dice/src/bcc.rs
+++ b/libs/dice/src/bcc.rs
@@ -16,17 +16,11 @@
 
 //! Wrapper around dice/android/bcc.h.
 
-use core::ffi::CStr;
 use core::mem;
 use core::ptr;
 
-use open_dice_bcc_bindgen::BccConfigValues;
-use open_dice_bcc_bindgen::BccFormatConfigDescriptor;
 use open_dice_bcc_bindgen::BccHandoverMainFlow;
 use open_dice_bcc_bindgen::BccHandoverParse;
-use open_dice_bcc_bindgen::BCC_INPUT_COMPONENT_NAME;
-use open_dice_bcc_bindgen::BCC_INPUT_COMPONENT_VERSION;
-use open_dice_bcc_bindgen::BCC_INPUT_RESETTABLE;
 
 use crate::check_result;
 use crate::Cdi;
@@ -109,57 +103,6 @@
     }
 }
 
-/// Formats a configuration descriptor following the BCC's specification.
-///
-/// ```
-/// BccConfigDescriptor = {
-///   ? -70002 : tstr,     ; Component name
-///   ? -70003 : int,      ; Component version
-///   ? -70004 : null,     ; Resettable
-/// }
-/// ```
-pub fn format_config_descriptor(
-    buffer: &mut [u8],
-    name: Option<&CStr>,
-    version: Option<u64>,
-    resettable: bool,
-) -> Result<usize> {
-    let mut inputs = 0;
-
-    if name.is_some() {
-        inputs |= BCC_INPUT_COMPONENT_NAME;
-    }
-
-    if version.is_some() {
-        inputs |= BCC_INPUT_COMPONENT_VERSION;
-    }
-
-    if resettable {
-        inputs |= BCC_INPUT_RESETTABLE;
-    }
-
-    let values = BccConfigValues {
-        inputs,
-        component_name: name.map_or(ptr::null(), |p| p.as_ptr()),
-        component_version: version.unwrap_or(0),
-    };
-
-    let mut buffer_size = 0;
-
-    // SAFETY - The function writes to the buffer, within the given bounds, and only reads the
-    // input values. It writes its result to buffer_size.
-    check_result(unsafe {
-        BccFormatConfigDescriptor(
-            &values as *const _,
-            buffer.len(),
-            buffer.as_mut_ptr(),
-            &mut buffer_size as *mut _,
-        )
-    })?;
-
-    Ok(buffer_size)
-}
-
 fn index_from_ptr(slice: &[u8], pointer: *const u8) -> Option<usize> {
     if slice.as_ptr_range().contains(&pointer) {
         (pointer as usize).checked_sub(slice.as_ptr() as usize)
diff --git a/libs/dice/src/lib.rs b/libs/dice/src/lib.rs
index 4a45ab4..6870eeb 100644
--- a/libs/dice/src/lib.rs
+++ b/libs/dice/src/lib.rs
@@ -19,23 +19,8 @@
 #![no_std]
 
 pub use diced_open_dice::{
-    check_result, Cdi, Config, DiceError, Hash, InputValues, Result, CDI_SIZE, HASH_SIZE,
-    HIDDEN_SIZE,
+    bcc_format_config_descriptor, check_result, Cdi, Config, DiceError, DiceMode, Hash,
+    InputValues, Result, CDI_SIZE, HASH_SIZE, HIDDEN_SIZE,
 };
-pub use open_dice_cbor_bindgen::DiceMode;
-
-use open_dice_cbor_bindgen::DiceHash;
 
 pub mod bcc;
-
-fn ctx() -> *mut core::ffi::c_void {
-    core::ptr::null_mut()
-}
-
-/// Hash the provided input using DICE's default hash function.
-pub fn hash(bytes: &[u8]) -> Result<Hash> {
-    let mut output: Hash = [0; HASH_SIZE];
-    // SAFETY - DiceHash takes a sized input buffer and writes to a constant-sized output buffer.
-    check_result(unsafe { DiceHash(ctx(), bytes.as_ptr(), bytes.len(), output.as_mut_ptr()) })?;
-    Ok(output)
-}
diff --git a/pvmfw/Android.bp b/pvmfw/Android.bp
index 21f84a5..0d6a9a4 100644
--- a/pvmfw/Android.bp
+++ b/pvmfw/Android.bp
@@ -14,7 +14,8 @@
     rustlibs: [
         "libaarch64_paging",
         "libbuddy_system_allocator",
-        "libdice_nostd",
+        "libdice_nostd", // TODO(b/267575445): Remove this library once the migration is done.
+        "libdiced_open_dice_nostd",
         "libfdtpci",
         "liblibfdt",
         "liblog_rust_nostd",
diff --git a/pvmfw/src/dice.rs b/pvmfw/src/dice.rs
index 42cc802..f6a1f3d 100644
--- a/pvmfw/src/dice.rs
+++ b/pvmfw/src/dice.rs
@@ -16,13 +16,11 @@
 
 use core::ffi::CStr;
 use core::mem::size_of;
-use dice::bcc::format_config_descriptor;
 use dice::bcc::Handover;
-use dice::hash;
 use dice::Config;
 use dice::DiceMode;
 use dice::InputValues;
-use dice::HIDDEN_SIZE;
+use diced_open_dice::{bcc_format_config_descriptor, hash, HIDDEN_SIZE};
 use pvmfw_avb::{DebugLevel, Digest, VerifiedBootData};
 
 fn to_dice_mode(debug_level: DebugLevel) -> DiceMode {
@@ -53,11 +51,11 @@
     let mode = to_dice_mode(verified_boot_data.debug_level);
     let component_name = CStr::from_bytes_with_nul(b"vm_entry\0").unwrap();
     let mut config_descriptor_buffer = [0; 128];
-    let config_descriptor_size = format_config_descriptor(
-        &mut config_descriptor_buffer,
+    let config_descriptor_size = bcc_format_config_descriptor(
         Some(component_name),
         None,  // component_version
         false, // resettable
+        &mut config_descriptor_buffer,
     )?;
     let config = &config_descriptor_buffer[..config_descriptor_size];
 
diff --git a/tests/helper/src/java/com/android/microdroid/test/common/DeviceProperties.java b/tests/helper/src/java/com/android/microdroid/test/common/DeviceProperties.java
index 94f7e99..ba82c38 100644
--- a/tests/helper/src/java/com/android/microdroid/test/common/DeviceProperties.java
+++ b/tests/helper/src/java/com/android/microdroid/test/common/DeviceProperties.java
@@ -26,9 +26,11 @@
     }
 
     private static final String KEY_VENDOR_DEVICE = "ro.product.vendor.device";
+    private static final String KEY_BUILD_TYPE = "ro.build.type";
     private static final String KEY_METRICS_TAG = "debug.hypervisor.metrics_tag";
 
     private static final String CUTTLEFISH_DEVICE_PREFIX = "vsoc_";
+    private static final String USER_BUILD_TYPE = "user";
 
     private final PropertyGetter mPropertyGetter;
 
@@ -49,6 +51,13 @@
         return vendorDeviceName != null && vendorDeviceName.startsWith(CUTTLEFISH_DEVICE_PREFIX);
     }
 
+    /**
+     * @return whether the device is user build.
+     */
+    public boolean isUserBuild() {
+        return USER_BUILD_TYPE.equals(getProperty(KEY_BUILD_TYPE));
+    }
+
     public String getMetricsTag() {
         return getProperty(KEY_METRICS_TAG);
     }
diff --git a/tests/hostside/helper/java/com/android/microdroid/test/host/MicrodroidHostTestCaseBase.java b/tests/hostside/helper/java/com/android/microdroid/test/host/MicrodroidHostTestCaseBase.java
index 8d328bc..1766835 100644
--- a/tests/hostside/helper/java/com/android/microdroid/test/host/MicrodroidHostTestCaseBase.java
+++ b/tests/hostside/helper/java/com/android/microdroid/test/host/MicrodroidHostTestCaseBase.java
@@ -110,6 +110,10 @@
         }
     }
 
+    public boolean isUserBuild() {
+        return DeviceProperties.create(getDevice()::getProperty).isUserBuild();
+    }
+
     protected boolean isCuttlefish() {
         return DeviceProperties.create(getDevice()::getProperty).isCuttlefish();
     }
diff --git a/tests/hostside/java/com/android/microdroid/test/MicrodroidHostTests.java b/tests/hostside/java/com/android/microdroid/test/MicrodroidHostTests.java
index c87ed80..a890770 100644
--- a/tests/hostside/java/com/android/microdroid/test/MicrodroidHostTests.java
+++ b/tests/hostside/java/com/android/microdroid/test/MicrodroidHostTests.java
@@ -587,6 +587,7 @@
     @Ignore("b/243630590: Temporal workaround until lab devices has flashed new DPM")
     public void testTombstonesAreGeneratedUponKernelCrash() throws Exception {
         assumeFalse("Cuttlefish is not supported", isCuttlefish());
+        assumeFalse("Skipping test because ramdump is disabled on user build", isUserBuild());
         assertThat(
                         isTombstoneGenerated(
                                 "assets/vm_config_crash.json",
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 9cafd68..984b10b 100644
--- a/tests/testapk/src/java/com/android/microdroid/test/MicrodroidTests.java
+++ b/tests/testapk/src/java/com/android/microdroid/test/MicrodroidTests.java
@@ -1303,6 +1303,65 @@
 
     @Test
     @CddTest(requirements = {"9.17/C-1-1", "9.17/C-2-1"})
+    public void encryptedStorageIsInaccessibleToDifferentVm() throws Exception {
+        assumeSupportedKernel();
+
+        VirtualMachineConfig config =
+                newVmConfigBuilder()
+                        .setPayloadBinaryName("MicrodroidTestNativeLib.so")
+                        .setMemoryBytes(minMemoryRequired())
+                        .setEncryptedStorageBytes(4_000_000)
+                        .setDebugLevel(DEBUG_LEVEL_FULL)
+                        .setVmOutputCaptured(true)
+                        .build();
+
+        VirtualMachine vm = forceCreateNewVirtualMachine("test_vm", config);
+
+        TestResults testResults =
+                runVmTestService(
+                        vm,
+                        (ts, tr) -> {
+                            ts.writeToFile(
+                                    /* content= */ EXAMPLE_STRING,
+                                    /* path= */ "/mnt/encryptedstore/test_file");
+                        });
+        assertThat(testResults.mException).isNull();
+
+        // Start a different vm (this changes the vm identity)
+        VirtualMachine diff_test_vm = forceCreateNewVirtualMachine("diff_test_vm", config);
+
+        // Replace the backing storage image to the original one
+        File storageImgOrig = getVmFile("test_vm", "storage.img");
+        File storageImgNew = getVmFile("diff_test_vm", "storage.img");
+        Files.copy(storageImgOrig.toPath(), storageImgNew.toPath(), REPLACE_EXISTING);
+        assertFileContentsAreEqualInTwoVms("storage.img", "test_vm", "diff_test_vm");
+
+        CompletableFuture<Boolean> onPayloadReadyExecuted = new CompletableFuture<>();
+        CompletableFuture<Boolean> onStoppedExecuted = new CompletableFuture<>();
+        VmEventListener listener =
+                new VmEventListener() {
+                    @Override
+                    public void onPayloadReady(VirtualMachine vm) {
+                        onPayloadReadyExecuted.complete(true);
+                        super.onPayloadReady(vm);
+                    }
+
+                    @Override
+                    public void onStopped(VirtualMachine vm, int reason) {
+                        onStoppedExecuted.complete(true);
+                        super.onStopped(vm, reason);
+                    }
+                };
+        listener.runToFinish(TAG, diff_test_vm);
+
+        // Assert that payload never started & logs contains encryptedstore initialization error
+        assertThat(onStoppedExecuted.getNow(false)).isTrue();
+        assertThat(onPayloadReadyExecuted.getNow(false)).isFalse();
+        assertThat(listener.getConsoleOutput()).contains("Unable to initialize encryptedstore");
+    }
+
+    @Test
+    @CddTest(requirements = {"9.17/C-1-1", "9.17/C-2-1"})
     public void microdroidLauncherHasEmptyCapabilities() throws Exception {
         assumeSupportedKernel();
 
diff --git a/vmbase/example/Android.bp b/vmbase/example/Android.bp
index 94eb21a..26be51b 100644
--- a/vmbase/example/Android.bp
+++ b/vmbase/example/Android.bp
@@ -11,7 +11,7 @@
     rustlibs: [
         "libaarch64_paging",
         "libbuddy_system_allocator",
-        "libdice_nostd",
+        "libdiced_open_dice_nostd",
         "libfdtpci",
         "liblibfdt",
         "liblog_rust_nostd",
diff --git a/vmbase/example/src/main.rs b/vmbase/example/src/main.rs
index ec28a11..3b0e9db 100644
--- a/vmbase/example/src/main.rs
+++ b/vmbase/example/src/main.rs
@@ -225,7 +225,7 @@
 
 fn check_dice() {
     info!("Testing DICE integration...");
-    let hash = dice::hash("hello world".as_bytes()).expect("DiceHash failed");
+    let hash = diced_open_dice::hash("hello world".as_bytes()).expect("DiceHash failed");
     assert_eq!(
         hash,
         [