Merge changes Ia9bb1597,I4f912afb

* changes:
  Compos test compilation is only for dogfooders and is critical
  Revert "Remove the daily job"
diff --git a/TEST_MAPPING b/TEST_MAPPING
index 4c9907f..8376c1f 100644
--- a/TEST_MAPPING
+++ b/TEST_MAPPING
@@ -44,6 +44,9 @@
       "path": "packages/modules/Virtualization/libs/apkverify"
     },
     {
+      "path": "packages/modules/Virtualization/libs/devicemapper"
+    },
+    {
       "path": "packages/modules/Virtualization/libs/vbmeta"
     },
     {
diff --git a/libs/devicemapper/Android.bp b/libs/devicemapper/Android.bp
index 088b320..783fa79 100644
--- a/libs/devicemapper/Android.bp
+++ b/libs/devicemapper/Android.bp
@@ -36,5 +36,5 @@
         "libscopeguard",
         "libtempfile",
     ],
-    data: ["tests/data/*"],
+    data: ["testdata/*"],
 }
diff --git a/libs/devicemapper/src/crypt.rs b/libs/devicemapper/src/crypt.rs
new file mode 100644
index 0000000..9b715a5
--- /dev/null
+++ b/libs/devicemapper/src/crypt.rs
@@ -0,0 +1,153 @@
+/*
+ * Copyright (C) 2022 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.
+ */
+
+/// `crypt` module implements the "crypt" target in the device mapper framework. Specifically,
+/// it provides `DmCryptTargetBuilder` struct which is used to construct a `DmCryptTarget` struct
+/// which is then given to `DeviceMapper` to create a mapper device.
+use crate::util::*;
+use crate::DmTargetSpec;
+
+use anyhow::{bail, Context, Result};
+use data_model::DataInit;
+use std::io::Write;
+use std::mem::size_of;
+use std::path::Path;
+
+const SECTOR_SIZE: u64 = 512;
+
+// The UAPI for the crypt target is at:
+// Documentation/admin-guide/device-mapper/dm-crypt.rst
+
+/// Supported ciphers
+pub enum CipherType {
+    // TODO(b/253394457) Include ciphers with authenticated modes as well
+    AES256XTS,
+}
+
+pub struct DmCryptTarget(Box<[u8]>);
+
+impl DmCryptTarget {
+    /// Flatten into slice
+    pub fn as_slice(&self) -> &[u8] {
+        self.0.as_ref()
+    }
+}
+
+pub struct DmCryptTargetBuilder<'a> {
+    cipher: CipherType,
+    key: Option<&'a [u8]>,
+    iv_offset: u64,
+    device_path: Option<&'a Path>,
+    offset: u64,
+    device_size: u64,
+    // TODO(b/238179332) Extend this to include opt_params, in particular 'integrity'
+}
+
+impl<'a> Default for DmCryptTargetBuilder<'a> {
+    fn default() -> Self {
+        DmCryptTargetBuilder {
+            cipher: CipherType::AES256XTS,
+            key: None,
+            iv_offset: 0,
+            device_path: None,
+            offset: 0,
+            device_size: 0,
+        }
+    }
+}
+
+impl<'a> DmCryptTargetBuilder<'a> {
+    /// Sets the device that will be used as the data device (i.e. providing actual data).
+    pub fn data_device(&mut self, p: &'a Path, size: u64) -> &mut Self {
+        self.device_path = Some(p);
+        self.device_size = size;
+        self
+    }
+
+    /// Sets the encryption cipher.
+    pub fn cipher(&mut self, cipher: CipherType) -> &mut Self {
+        self.cipher = cipher;
+        self
+    }
+
+    /// Sets the key used for encryption. Input is byte array.
+    pub fn key(&mut self, key: &'a [u8]) -> &mut Self {
+        self.key = Some(key);
+        self
+    }
+
+    /// The IV offset is a sector count that is added to the sector number before creating the IV.
+    pub fn iv_offset(&mut self, iv_offset: u64) -> &mut Self {
+        self.iv_offset = iv_offset;
+        self
+    }
+
+    /// Starting sector within the device where the encrypted data begins
+    pub fn offset(&mut self, offset: u64) -> &mut Self {
+        self.offset = offset;
+        self
+    }
+
+    /// Constructs a `DmCryptTarget`.
+    pub fn build(&self) -> Result<DmCryptTarget> {
+        // The `DmCryptTarget` struct actually is a flattened data consisting of a header and
+        // body. The format of the header is `dm_target_spec` as defined in
+        // include/uapi/linux/dm-ioctl.h.
+        let device_path = self
+            .device_path
+            .context("data device is not set")?
+            .to_str()
+            .context("data device path is not encoded in utf8")?;
+
+        let key =
+            if let Some(key) = self.key { hexstring_from(key) } else { bail!("key is not set") };
+
+        // Step2: serialize the information according to the spec, which is ...
+        // DmTargetSpec{...}
+        // <cipher> <key> <iv_offset> <device path> \
+        // <offset> [<#opt_params> <opt_params>]
+        let mut body = String::new();
+        use std::fmt::Write;
+        write!(&mut body, "{} ", get_kernel_crypto_name(&self.cipher))?;
+        write!(&mut body, "{} ", key)?;
+        write!(&mut body, "{} ", self.iv_offset)?;
+        write!(&mut body, "{} ", device_path)?;
+        write!(&mut body, "{} ", self.offset)?;
+        write!(&mut body, "\0")?; // null terminator
+
+        let size = size_of::<DmTargetSpec>() + body.len();
+        let aligned_size = (size + 7) & !7; // align to 8 byte boundaries
+        let padding = aligned_size - size;
+
+        let mut header = DmTargetSpec::new("crypt")?;
+        header.sector_start = 0;
+        header.length = self.device_size / SECTOR_SIZE; // number of 512-byte sectors
+        header.next = aligned_size as u32;
+
+        let mut buf = Vec::with_capacity(aligned_size);
+        buf.write_all(header.as_slice())?;
+        buf.write_all(body.as_bytes())?;
+        buf.write_all(vec![0; padding].as_slice())?;
+
+        Ok(DmCryptTarget(buf.into_boxed_slice()))
+    }
+}
+
+fn get_kernel_crypto_name(cipher: &CipherType) -> &str {
+    match cipher {
+        CipherType::AES256XTS => "aes-xts-plain64",
+    }
+}
diff --git a/libs/devicemapper/src/lib.rs b/libs/devicemapper/src/lib.rs
index 938ca0f..b9fb5c3 100644
--- a/libs/devicemapper/src/lib.rs
+++ b/libs/devicemapper/src/lib.rs
@@ -38,6 +38,8 @@
 use std::os::unix::io::AsRawFd;
 use std::path::{Path, PathBuf};
 
+/// Exposes DmCryptTarget & related builder
+pub mod crypt;
 /// Expose util functions
 pub mod util;
 /// Exposes the DmVerityTarget & related builder
@@ -46,9 +48,10 @@
 pub mod loopdevice;
 
 mod sys;
+use crypt::DmCryptTarget;
 use sys::*;
 use util::*;
-use verity::*;
+use verity::DmVerityTarget;
 
 nix::ioctl_readwrite!(_dm_dev_create, DM_IOCTL, Cmd::DM_DEV_CREATE, DmIoctl);
 nix::ioctl_readwrite!(_dm_dev_suspend, DM_IOCTL, Cmd::DM_DEV_SUSPEND, DmIoctl);
@@ -151,27 +154,55 @@
         Ok(DeviceMapper(f))
     }
 
-    /// Creates a device mapper device and configure it according to the `target` specification.
+    /// Creates a (crypt) device and configure it according to the `target` specification.
+    /// The path to the generated device is "/dev/mapper/<name>".
+    pub fn create_crypt_device(&self, name: &str, target: &DmCryptTarget) -> Result<PathBuf> {
+        self.create_device(name, target.as_slice(), uuid("crypto".as_bytes())?, true)
+    }
+
+    /// Creates a (verity) device and configure it according to the `target` specification.
     /// The path to the generated device is "/dev/mapper/<name>".
     pub fn create_verity_device(&self, name: &str, target: &DmVerityTarget) -> Result<PathBuf> {
+        self.create_device(name, target.as_slice(), uuid("apkver".as_bytes())?, false)
+    }
+
+    /// Removes a mapper device.
+    pub fn delete_device_deferred(&self, name: &str) -> Result<()> {
+        let mut data = DmIoctl::new(name)?;
+        data.flags |= Flag::DM_DEFERRED_REMOVE;
+        dm_dev_remove(self, &mut data)
+            .context(format!("failed to remove device with name {}", &name))?;
+        Ok(())
+    }
+
+    fn create_device(
+        &self,
+        name: &str,
+        target: &[u8],
+        uid: String,
+        writable: bool,
+    ) -> Result<PathBuf> {
         // Step 1: create an empty device
         let mut data = DmIoctl::new(name)?;
-        data.set_uuid(&uuid("apkver".as_bytes())?)?;
+        data.set_uuid(&uid)?;
         dm_dev_create(self, &mut data)
             .context(format!("failed to create an empty device with name {}", &name))?;
 
         // Step 2: load table onto the device
-        let payload_size = size_of::<DmIoctl>() + target.as_slice().len();
+        let payload_size = size_of::<DmIoctl>() + target.len();
 
         let mut data = DmIoctl::new(name)?;
         data.data_size = payload_size as u32;
         data.data_start = size_of::<DmIoctl>() as u32;
         data.target_count = 1;
-        data.flags |= Flag::DM_READONLY_FLAG;
+
+        if !writable {
+            data.flags |= Flag::DM_READONLY_FLAG;
+        }
 
         let mut payload = Vec::with_capacity(payload_size);
         payload.extend_from_slice(data.as_slice());
-        payload.extend_from_slice(target.as_slice());
+        payload.extend_from_slice(target);
         dm_table_load(self, payload.as_mut_ptr() as *mut DmIoctl)
             .context("failed to load table")?;
 
@@ -185,15 +216,6 @@
         wait_for_path(&path)?;
         Ok(path)
     }
-
-    /// Removes a mapper device
-    pub fn delete_device_deferred(&self, name: &str) -> Result<()> {
-        let mut data = DmIoctl::new(name)?;
-        data.flags |= Flag::DM_DEFERRED_REMOVE;
-        dm_dev_remove(self, &mut data)
-            .context(format!("failed to remove device with name {}", &name))?;
-        Ok(())
-    }
 }
 
 /// Used to derive a UUID that uniquely identifies a device mapper device when creating it.
@@ -208,3 +230,113 @@
     let uuid = Uuid::new_v1(ts, node_id)?;
     Ok(String::from(uuid.to_hyphenated().encode_lower(&mut Uuid::encode_buffer())))
 }
+
+#[cfg(test)]
+mod tests {
+    use super::*;
+    use crypt::DmCryptTargetBuilder;
+    use std::fs::{read, File, OpenOptions};
+    use std::io::Write;
+
+    const KEY: &[u8; 32] = b"thirtytwobyteslongreallylongword";
+    const DIFFERENT_KEY: &[u8; 32] = b"drowgnolyllaergnolsetybowtytriht";
+
+    // Create a file in given temp directory with given size
+    fn prepare_tmpfile(test_dir: &Path, filename: &str, sz: u64) -> PathBuf {
+        let filepath = test_dir.join(filename);
+        let f = File::create(&filepath).unwrap();
+        f.set_len(sz).unwrap();
+        filepath
+    }
+
+    fn write_to_dev(path: &Path, data: &[u8]) {
+        let mut f = OpenOptions::new().read(true).write(true).open(&path).unwrap();
+        f.write_all(data).unwrap();
+    }
+
+    fn delete_device(dm: &DeviceMapper, name: &str) -> Result<()> {
+        dm.delete_device_deferred(name)?;
+        wait_for_path_disappears(Path::new(MAPPER_DEV_ROOT).join(&name))?;
+        Ok(())
+    }
+
+    #[test]
+    fn mapping_again_keeps_data() {
+        // This test creates 2 different crypt devices using same key backed by same data_device
+        // -> Write data on dev1 -> Check the data is visible & same on dev2
+        let dm = DeviceMapper::new().unwrap();
+        let inputimg = include_bytes!("../testdata/rand8k");
+        let sz = inputimg.len() as u64;
+
+        let test_dir = tempfile::TempDir::new().unwrap();
+        let backing_file = prepare_tmpfile(test_dir.path(), "storage", sz);
+        let data_device = loopdevice::attach(
+            backing_file,
+            0,
+            sz,
+            /*direct_io*/ true,
+            /*writable*/ true,
+        )
+        .unwrap();
+        scopeguard::defer! {
+            loopdevice::detach(&data_device).unwrap();
+            _ = delete_device(&dm, "crypt1");
+            _ = delete_device(&dm, "crypt2");
+        }
+
+        let target =
+            DmCryptTargetBuilder::default().data_device(&data_device, sz).key(KEY).build().unwrap();
+
+        let mut crypt_device = dm.create_crypt_device("crypt1", &target).unwrap();
+        write_to_dev(&crypt_device, inputimg);
+
+        // Recreate another device using same target spec & check if the content is the same
+        crypt_device = dm.create_crypt_device("crypt2", &target).unwrap();
+
+        let crypt = read(crypt_device).unwrap();
+        assert_eq!(inputimg.len(), crypt.len()); // fail early if the size doesn't match
+        assert_eq!(inputimg, crypt.as_slice());
+    }
+
+    #[test]
+    fn data_inaccessible_with_diff_key() {
+        // This test creates 2 different crypt devices using different keys backed
+        // by same data_device -> Write data on dev1 -> Check the data is visible but not the same on dev2
+        let dm = DeviceMapper::new().unwrap();
+        let inputimg = include_bytes!("../testdata/rand8k");
+        let sz = inputimg.len() as u64;
+
+        let test_dir = tempfile::TempDir::new().unwrap();
+        let backing_file = prepare_tmpfile(test_dir.path(), "storage", sz);
+        let data_device = loopdevice::attach(
+            backing_file,
+            0,
+            sz,
+            /*direct_io*/ true,
+            /*writable*/ true,
+        )
+        .unwrap();
+        scopeguard::defer! {
+            loopdevice::detach(&data_device).unwrap();
+            _ = delete_device(&dm, "crypt3");
+            _ = delete_device(&dm, "crypt4");
+        }
+
+        let target =
+            DmCryptTargetBuilder::default().data_device(&data_device, sz).key(KEY).build().unwrap();
+        let target2 = DmCryptTargetBuilder::default()
+            .data_device(&data_device, sz)
+            .key(DIFFERENT_KEY)
+            .build()
+            .unwrap();
+
+        let mut crypt_device = dm.create_crypt_device("crypt3", &target).unwrap();
+
+        write_to_dev(&crypt_device, inputimg);
+
+        // Recreate the crypt device again diff key & check if the content is changed
+        crypt_device = dm.create_crypt_device("crypt4", &target2).unwrap();
+        let crypt = read(crypt_device).unwrap();
+        assert_ne!(inputimg, crypt.as_slice());
+    }
+}
diff --git a/libs/devicemapper/src/util.rs b/libs/devicemapper/src/util.rs
index 913f827..e8df424 100644
--- a/libs/devicemapper/src/util.rs
+++ b/libs/devicemapper/src/util.rs
@@ -37,6 +37,21 @@
     Ok(())
 }
 
+/// Wait for the path to disappear
+#[cfg(test)]
+pub fn wait_for_path_disappears<P: AsRef<Path>>(path: P) -> Result<()> {
+    const TIMEOUT: Duration = Duration::from_secs(1);
+    const INTERVAL: Duration = Duration::from_millis(10);
+    let begin = Instant::now();
+    while !path.as_ref().exists() {
+        if begin.elapsed() > TIMEOUT {
+            bail!("{:?} not disappearing. TIMEOUT.", path.as_ref());
+        }
+        thread::sleep(INTERVAL);
+    }
+    Ok(())
+}
+
 /// Returns hexadecimal reprentation of a given byte array.
 pub fn hexstring_from(s: &[u8]) -> String {
     s.iter().map(|byte| format!("{:02x}", byte)).reduce(|i, j| i + &j).unwrap_or_default()
diff --git a/libs/devicemapper/testdata/rand8k b/libs/devicemapper/testdata/rand8k
new file mode 100644
index 0000000..4172e33
--- /dev/null
+++ b/libs/devicemapper/testdata/rand8k
Binary files differ
diff --git a/tests/benchmark_hostside/java/android/avf/test/AVFHostTestCase.java b/tests/benchmark_hostside/java/android/avf/test/AVFHostTestCase.java
index 17f773e..5e57b32 100644
--- a/tests/benchmark_hostside/java/android/avf/test/AVFHostTestCase.java
+++ b/tests/benchmark_hostside/java/android/avf/test/AVFHostTestCase.java
@@ -19,6 +19,7 @@
 import static com.android.tradefed.testtype.DeviceJUnit4ClassRunner.TestMetrics;
 
 import static com.google.common.truth.Truth.assertWithMessage;
+import static com.google.common.truth.TruthJUnit.assume;
 
 import static org.junit.Assert.assertNotNull;
 import static org.junit.Assume.assumeFalse;
@@ -73,9 +74,9 @@
     private static final int BOOT_COMPLETE_TIMEOUT_MS = 10 * 60 * 1000;
     private static final double NANOS_IN_SEC = 1_000_000_000.0;
     private static final int ROUND_COUNT = 5;
+    private static final int ROUND_IGNORE_STARTUP_TIME = 3;
     private static final String APK_NAME = "MicrodroidTestApp.apk";
     private static final String PACKAGE_NAME = "com.android.microdroid.test";
-    private static final String SETTINGS_PACKAGE_NAME = "com.android.settings";
     private static final int NUM_VCPUS = 3;
 
     private MetricsProcessor mMetricsProcessor;
@@ -122,14 +123,32 @@
     }
 
     @Test
-    public void testAppStartupTime() throws Exception {
+    public void testCameraAppStartupTime() throws Exception {
+        String[] launchIntentPackages = {
+            "com.android.camera2",
+            "com.google.android.GoogleCamera/com.android.camera.CameraLauncher"
+        };
+        String launchIntentPackage = findSupportedPackage(launchIntentPackages);
+        assume().withMessage("No supported camera package").that(launchIntentPackage).isNotNull();
+        appStartupHelper(launchIntentPackage);
+    }
+
+    @Test
+    public void testSettingsAppStartupTime() throws Exception {
+        String[] launchIntentPackages = {
+            "com.android.settings"
+        };
+        String launchIntentPackage = findSupportedPackage(launchIntentPackages);
+        assume().withMessage("No supported settings package").that(launchIntentPackage).isNotNull();
+        appStartupHelper(launchIntentPackage);
+    }
+
+    private void appStartupHelper(String launchIntentPackage) throws Exception {
         assumeTrue("Skip on non-protected VMs", isProtectedVmSupported());
 
         StartupTimeMetricCollection mCollection =
-                new StartupTimeMetricCollection(SETTINGS_PACKAGE_NAME, ROUND_COUNT);
-        for (int round = 0; round < ROUND_COUNT; ++round) {
-            getAppStartupTime(mCollection);
-        }
+                new StartupTimeMetricCollection(getPackageName(launchIntentPackage), ROUND_COUNT);
+        getAppStartupTime(launchIntentPackage, mCollection);
 
         reportMetric(mCollection.mAppBeforeVmRunTotalTime,
                 "app_startup/" + mCollection.getPkgName() + "/total_time/before_vm",
@@ -151,13 +170,38 @@
                 "ms");
     }
 
+    private String getPackageName(String launchIntentPackage) {
+        String appPkg = launchIntentPackage;
+
+        // Does the appPkgName contain the intent ?
+        if (launchIntentPackage != null && launchIntentPackage.contains("/")) {
+            appPkg = launchIntentPackage.split("/")[0];
+        }
+        return appPkg;
+    }
+
+    private String findSupportedPackage(String[] pkgNameList) throws Exception {
+        CommandRunner android = new CommandRunner(getDevice());
+
+        for (String pkgName : pkgNameList) {
+            String appPkg = getPackageName(pkgName);
+            String hasPackage = android.run("pm list package | grep -w " + appPkg + " 1> /dev/null"
+                    + "; echo $?");
+            assertNotNull(hasPackage);
+
+            if (hasPackage.equals("0")) {
+                return pkgName;
+            }
+        }
+        return null;
+    }
+
     private void microdroidWaitForBootComplete() {
         runOnMicrodroidForResult("watch -e \"getprop dev.bootcomplete | grep '^0$'\"");
     }
 
-    private AmStartupTimeCmdParser getColdRunStartupTimes(String pkgName)
+    private AmStartupTimeCmdParser getColdRunStartupTimes(CommandRunner android, String pkgName)
             throws DeviceNotAvailableException, InterruptedException {
-        CommandRunner android = new CommandRunner(getDevice());
         unlockScreen(android);
         // Ensure we are killing the app to get the cold app startup time
         android.run("am force-stop " + pkgName);
@@ -170,20 +214,27 @@
 
     // Returns an array of two elements containing the delta between the initial app startup time
     // and the time measured after running the VM.
-    private void getAppStartupTime(StartupTimeMetricCollection metricColector)
+    private void getAppStartupTime(String pkgName, StartupTimeMetricCollection metricColector)
             throws Exception {
         final String configPath = "assets/vm_config.json";
         final String cid;
         final int vm_mem_mb;
 
-        // Reboot the device to run the test without stage2 fragmentation
+        // 1. Reboot the device to run the test without stage2 fragmentation
         getDevice().rebootUntilOnline();
         waitForBootCompleted();
 
-        // Run the app before the VM run and collect app startup time statistics
+        // 2. Start the app and ignore first runs to warm up caches
         CommandRunner android = new CommandRunner(getDevice());
-        AmStartupTimeCmdParser beforeVmStartApp = getColdRunStartupTimes(SETTINGS_PACKAGE_NAME);
-        metricColector.addStartupTimeMetricBeforeVmRun(beforeVmStartApp);
+        for (int i = 0; i < ROUND_IGNORE_STARTUP_TIME; i++) {
+            getColdRunStartupTimes(android, pkgName);
+        }
+
+        // 3. Run the app before the VM run and collect app startup time statistics
+        for (int i = 0; i < ROUND_COUNT; i++) {
+            AmStartupTimeCmdParser beforeVmStartApp = getColdRunStartupTimes(android, pkgName);
+            metricColector.addStartupTimeMetricBeforeVmRun(beforeVmStartApp);
+        }
 
         // Clear up any test dir
         android.tryRun("rm", "-rf", MicrodroidHostTestCaseBase.TEST_ROOT);
@@ -216,12 +267,19 @@
         } catch (Exception ex) {
         }
 
-        AmStartupTimeCmdParser duringVmStartApp = getColdRunStartupTimes(SETTINGS_PACKAGE_NAME);
-        metricColector.addStartupTimeMetricDuringVmRun(duringVmStartApp);
+        // Run the app during the VM run and collect cold startup time.
+        for (int i = 0; i < ROUND_COUNT; i++) {
+            AmStartupTimeCmdParser duringVmStartApp = getColdRunStartupTimes(android, pkgName);
+            metricColector.addStartupTimeMetricDuringVmRun(duringVmStartApp);
+        }
+
         shutdownMicrodroid(getDevice(), cid);
 
-        AmStartupTimeCmdParser afterVmStartApp = getColdRunStartupTimes(SETTINGS_PACKAGE_NAME);
-        metricColector.addStartupTimerMetricAfterVmRun(afterVmStartApp);
+        // Run the app after the VM run and collect cold startup time.
+        for (int i = 0; i < ROUND_COUNT; i++) {
+            AmStartupTimeCmdParser afterVmStartApp = getColdRunStartupTimes(android, pkgName);
+            metricColector.addStartupTimerMetricAfterVmRun(afterVmStartApp);
+        }
     }
 
     static class AmStartupTimeCmdParser {
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 36379af..1a1dbeb 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
@@ -130,14 +130,17 @@
     private static String runOnHostWithTimeout(long timeoutMillis, String... cmd) {
         assertThat(timeoutMillis).isAtLeast(0);
         CommandResult result = RunUtil.getDefault().runTimedCmd(timeoutMillis, cmd);
-        assertThat(result).isSuccess();
+        assertWithMessage("Host command `" + join(cmd) + "` did not succeed")
+                .about(command_results())
+                .that(result)
+                .isSuccess();
         return result.getStdout().trim();
     }
 
     // Run a shell command on Microdroid
     public static String runOnMicrodroid(String... cmd) {
         CommandResult result = runOnMicrodroidForResult(cmd);
-        assertWithMessage("microdroid shell cmd `" + join(cmd) + "`")
+        assertWithMessage("Microdroid command `" + join(cmd) + "` did not succeed")
                 .about(command_results())
                 .that(result)
                 .isSuccess();
@@ -197,7 +200,11 @@
 
     // Asserts the command will fail on Microdroid.
     public static void assertFailedOnMicrodroid(String... cmd) {
-        assertThat(runOnMicrodroidForResult(cmd)).isFailed();
+        CommandResult result = runOnMicrodroidForResult(cmd);
+        assertWithMessage("Microdroid command `" + join(cmd) + "` did not fail expectedly")
+                .about(command_results())
+                .that(result)
+                .isFailed();
     }
 
     private static String join(String... strs) {
diff --git a/tests/testapk/Android.bp b/tests/testapk/Android.bp
index 2439142..42abbbf 100644
--- a/tests/testapk/Android.bp
+++ b/tests/testapk/Android.bp
@@ -34,14 +34,15 @@
 cc_library_shared {
     name: "MicrodroidTestNativeLib",
     srcs: ["src/native/testbinary.cpp"],
+    stl: "libc++_static",
     shared_libs: [
-        "libbase",
         "libbinder_ndk",
         "MicrodroidTestNativeLibSub",
         "libvm_payload",
     ],
     static_libs: [
         "com.android.microdroid.testservice-ndk",
+        "libbase",
         "libfsverity_digests_proto_cc",
         "liblog",
         "libprotobuf-cpp-lite-ndk",
@@ -52,9 +53,11 @@
     name: "MicrodroidTestNativeCrashLib",
     header_libs: ["vm_payload_headers"],
     srcs: ["src/native/crashbinary.cpp"],
+    stl: "libc++_static",
 }
 
 cc_library_shared {
     name: "MicrodroidTestNativeLibSub",
     srcs: ["src/native/testlib.cpp"],
+    stl: "libc++_static",
 }