Merge "Don't start composd if VMs are not supported"
diff --git a/libs/dice/Android.bp b/libs/dice/Android.bp
deleted file mode 100644
index 31a39b2..0000000
--- a/libs/dice/Android.bp
+++ /dev/null
@@ -1,19 +0,0 @@
-package {
-    default_applicable_licenses: ["Android-Apache-2.0"],
-}
-
-rust_library_rlib {
-    name: "libdice_nostd",
-    crate_name: "dice",
-    srcs: ["src/lib.rs"],
-    edition: "2021",
-    no_stdlibs: true,
-    prefer_rlib: true,
-    stdlibs: ["libcore.rust_sysroot"],
-    rustlibs: [
-        "libdiced_open_dice_nostd",
-        "libopen_dice_cbor_bindgen_nostd",
-        "libopen_dice_bcc_bindgen_nostd",
-    ],
-    apex_available: ["com.android.virt"],
-}
diff --git a/libs/dice/src/bcc.rs b/libs/dice/src/bcc.rs
deleted file mode 100644
index a7ef882..0000000
--- a/libs/dice/src/bcc.rs
+++ /dev/null
@@ -1,112 +0,0 @@
-/*
- * Copyright 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.
- */
-
-//! Wrapper around dice/android/bcc.h.
-
-use core::mem;
-use core::ptr;
-
-use open_dice_bcc_bindgen::BccHandoverMainFlow;
-use open_dice_bcc_bindgen::BccHandoverParse;
-
-use crate::check_result;
-use crate::Cdi;
-use crate::DiceError;
-use crate::InputValues;
-use crate::Result;
-
-/// Boot Chain Certificate handover format combining the BCC and CDIs in a single CBOR object.
-#[derive(Clone, Debug)]
-pub struct Handover<'a> {
-    buffer: &'a [u8],
-    /// Attestation CDI.
-    pub cdi_attest: &'a Cdi,
-    /// Sealing CDI.
-    pub cdi_seal: &'a Cdi,
-    /// Boot Chain Certificate (optional).
-    pub bcc: Option<&'a [u8]>,
-}
-
-impl<'a> Handover<'a> {
-    /// Validates and extracts the fields of a BCC handover buffer.
-    pub fn new(buffer: &'a [u8]) -> Result<Self> {
-        let mut cdi_attest: *const u8 = ptr::null();
-        let mut cdi_seal: *const u8 = ptr::null();
-        let mut bcc: *const u8 = ptr::null();
-        let mut bcc_size: usize = 0;
-
-        // SAFETY - The buffer is only read and never stored and the returned pointers should all
-        // point within the address range of the buffer or be NULL.
-        check_result(unsafe {
-            BccHandoverParse(
-                buffer.as_ptr(),
-                buffer.len(),
-                &mut cdi_attest as *mut *const u8,
-                &mut cdi_seal as *mut *const u8,
-                &mut bcc as *mut *const u8,
-                &mut bcc_size as *mut usize,
-            )
-        })?;
-
-        let cdi_attest = {
-            let i = index_from_ptr(buffer, cdi_attest).ok_or(DiceError::PlatformError)?;
-            let s = buffer.get(i..(i + mem::size_of::<Cdi>())).ok_or(DiceError::PlatformError)?;
-            s.try_into().map_err(|_| DiceError::PlatformError)?
-        };
-        let cdi_seal = {
-            let i = index_from_ptr(buffer, cdi_seal).ok_or(DiceError::PlatformError)?;
-            let s = buffer.get(i..(i + mem::size_of::<Cdi>())).ok_or(DiceError::PlatformError)?;
-            s.try_into().map_err(|_| DiceError::PlatformError)?
-        };
-        let bcc = if bcc.is_null() {
-            None
-        } else {
-            let i = index_from_ptr(buffer, bcc).ok_or(DiceError::PlatformError)?;
-            Some(buffer.get(i..(i + bcc_size)).ok_or(DiceError::PlatformError)?)
-        };
-
-        Ok(Self { buffer, cdi_attest, cdi_seal, bcc })
-    }
-
-    /// Executes the main BCC handover flow.
-    pub fn main_flow(&self, input_values: &InputValues, buffer: &mut [u8]) -> Result<usize> {
-        let context = ptr::null_mut();
-        let mut size: usize = 0;
-        // SAFETY - The function only reads `self.buffer`, writes to `buffer` within its bounds,
-        // reads `input_values` as a constant input and doesn't store any pointer.
-        check_result(unsafe {
-            BccHandoverMainFlow(
-                context,
-                self.buffer.as_ptr(),
-                self.buffer.len(),
-                input_values.as_ptr(),
-                buffer.len(),
-                buffer.as_mut_ptr(),
-                &mut size as *mut usize,
-            )
-        })?;
-
-        Ok(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)
-    } else {
-        None
-    }
-}
diff --git a/libs/dice/src/lib.rs b/libs/dice/src/lib.rs
deleted file mode 100644
index 6870eeb..0000000
--- a/libs/dice/src/lib.rs
+++ /dev/null
@@ -1,26 +0,0 @@
-/*
- * Copyright 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.
- */
-
-//! Bare metal wrapper around libopen_dice.
-
-#![no_std]
-
-pub use diced_open_dice::{
-    bcc_format_config_descriptor, check_result, Cdi, Config, DiceError, DiceMode, Hash,
-    InputValues, Result, CDI_SIZE, HASH_SIZE, HIDDEN_SIZE,
-};
-
-pub mod bcc;
diff --git a/microdroid_manager/src/dice.rs b/microdroid_manager/src/dice.rs
index 9a2648f..fd22198 100644
--- a/microdroid_manager/src/dice.rs
+++ b/microdroid_manager/src/dice.rs
@@ -14,10 +14,11 @@
 
 //! Logic for handling the DICE values and boot operations.
 
-use anyhow::{bail, Context, Error, Result};
+use anyhow::{anyhow, bail, Context, Error, Result};
 use byteorder::{NativeEndian, ReadBytesExt};
 use diced_open_dice::{
-    retry_bcc_main_flow, Cdi, Config, DiceMode, Hash, Hidden, InputValues, OwnedDiceArtifacts,
+    bcc_handover_parse, retry_bcc_main_flow, BccHandover, Cdi, Config, DiceMode, Hash, Hidden,
+    InputValues, OwnedDiceArtifacts,
 };
 use keystore2_crypto::ZVec;
 use libc::{c_void, mmap, munmap, MAP_FAILED, MAP_PRIVATE, PROT_READ};
@@ -47,9 +48,7 @@
         driver_path: PathBuf,
         mmap_addr: *mut c_void,
         mmap_size: usize,
-        cdi_attest: &'a Cdi,
-        cdi_seal: &'a Cdi,
-        bcc: &'a [u8],
+        bcc_handover: BccHandover<'a>,
     },
     Fake(OwnedDiceArtifacts),
 }
@@ -86,27 +85,13 @@
         // accessible and not referenced from anywhere else.
         let mmap_buf =
             unsafe { slice::from_raw_parts((mmap_addr as *const u8).as_ref().unwrap(), mmap_size) };
-        // Very inflexible parsing / validation of the BccHandover data. Assumes deterministically
-        // encoded CBOR.
-        //
-        // BccHandover = {
-        //   1 : bstr .size 32,     ; CDI_Attest
-        //   2 : bstr .size 32,     ; CDI_Seal
-        //   3 : Bcc,               ; Certificate chain
-        // }
-        if mmap_buf[0..4] != [0xa3, 0x01, 0x58, 0x20]
-            || mmap_buf[36..39] != [0x02, 0x58, 0x20]
-            || mmap_buf[71] != 0x03
-        {
-            bail!("BccHandover format mismatch");
-        }
+        let bcc_handover =
+            bcc_handover_parse(mmap_buf).map_err(|_| anyhow!("Failed to parse Bcc Handover"))?;
         Ok(Self::Real {
             driver_path: driver_path.to_path_buf(),
             mmap_addr,
             mmap_size,
-            cdi_attest: mmap_buf[4..36].try_into().unwrap(),
-            cdi_seal: mmap_buf[39..71].try_into().unwrap(),
-            bcc: &mmap_buf[72..],
+            bcc_handover,
         })
     }
 
@@ -115,7 +100,7 @@
         // directly, so we have the chance to rotate the key if needed. A salt isn't needed as the
         // input key material is already cryptographically strong.
         let cdi_seal = match self {
-            Self::Real { cdi_seal, .. } => cdi_seal,
+            Self::Real { bcc_handover, .. } => bcc_handover.cdi_seal,
             Self::Fake(fake) => &fake.cdi_values.cdi_seal,
         };
         let salt = &[];
@@ -138,7 +123,11 @@
             hidden,
         );
         let (cdi_attest, cdi_seal, bcc) = match &self {
-            Self::Real { cdi_attest, cdi_seal, bcc, .. } => (*cdi_attest, *cdi_seal, *bcc),
+            Self::Real { bcc_handover, .. } => (
+                bcc_handover.cdi_attest,
+                bcc_handover.cdi_seal,
+                bcc_handover.bcc.ok_or_else(|| anyhow!("bcc is none"))?,
+            ),
             Self::Fake(fake) => {
                 (&fake.cdi_values.cdi_attest, &fake.cdi_values.cdi_seal, fake.bcc.as_slice())
             }
diff --git a/pvmfw/Android.bp b/pvmfw/Android.bp
index 9cb997b..7561800 100644
--- a/pvmfw/Android.bp
+++ b/pvmfw/Android.bp
@@ -14,7 +14,6 @@
     rustlibs: [
         "libaarch64_paging",
         "libbuddy_system_allocator",
-        "libdice_nostd", // TODO(b/267575445): Remove this library once the migration is done.
         "libdiced_open_dice_nostd",
         "libfdtpci",
         "liblibfdt",
diff --git a/pvmfw/src/dice.rs b/pvmfw/src/dice.rs
index 9c5f59a..14f522f 100644
--- a/pvmfw/src/dice.rs
+++ b/pvmfw/src/dice.rs
@@ -20,10 +20,9 @@
 use core::mem::size_of;
 use core::slice;
 
-use dice::Config;
-use dice::DiceMode;
-use dice::InputValues;
-use diced_open_dice::{bcc_format_config_descriptor, hash, HIDDEN_SIZE};
+use diced_open_dice::{
+    bcc_format_config_descriptor, hash, Config, DiceMode, Hash, InputValues, HIDDEN_SIZE,
+};
 use pvmfw_avb::{DebugLevel, Digest, VerifiedBootData};
 
 fn to_dice_mode(debug_level: DebugLevel) -> DiceMode {
@@ -33,7 +32,7 @@
     }
 }
 
-fn to_dice_hash(verified_boot_data: &VerifiedBootData) -> dice::Result<dice::Hash> {
+fn to_dice_hash(verified_boot_data: &VerifiedBootData) -> diced_open_dice::Result<Hash> {
     let mut digests = [0u8; size_of::<Digest>() * 2];
     digests[..size_of::<Digest>()].copy_from_slice(&verified_boot_data.kernel_digest);
     if let Some(initrd_digest) = verified_boot_data.initrd_digest {
@@ -43,13 +42,13 @@
 }
 
 pub struct PartialInputs {
-    code_hash: dice::Hash,
-    auth_hash: dice::Hash,
+    code_hash: Hash,
+    auth_hash: Hash,
     mode: DiceMode,
 }
 
 impl PartialInputs {
-    pub fn new(data: &VerifiedBootData) -> dice::Result<Self> {
+    pub fn new(data: &VerifiedBootData) -> diced_open_dice::Result<Self> {
         let code_hash = to_dice_hash(data)?;
         let auth_hash = hash(data.public_key)?;
         let mode = to_dice_mode(data.debug_level);
@@ -57,7 +56,10 @@
         Ok(Self { code_hash, auth_hash, mode })
     }
 
-    pub fn into_input_values(self, salt: &[u8; HIDDEN_SIZE]) -> dice::Result<InputValues> {
+    pub fn into_input_values(
+        self,
+        salt: &[u8; HIDDEN_SIZE],
+    ) -> diced_open_dice::Result<InputValues> {
         let component_name = CStr::from_bytes_with_nul(b"vm_entry\0").unwrap();
         let mut config_descriptor_buffer = [0; 128];
         let config_descriptor_size = bcc_format_config_descriptor(
diff --git a/pvmfw/src/entry.rs b/pvmfw/src/entry.rs
index 530449c..ddde50a 100644
--- a/pvmfw/src/entry.rs
+++ b/pvmfw/src/entry.rs
@@ -25,7 +25,6 @@
 use core::arch::asm;
 use core::num::NonZeroUsize;
 use core::slice;
-use dice::bcc::Handover;
 use log::debug;
 use log::error;
 use log::info;
@@ -243,10 +242,6 @@
     })?;
 
     let bcc_slice = appended.get_bcc_mut();
-    let bcc = Handover::new(bcc_slice).map_err(|e| {
-        error!("Invalid BCC Handover: {e:?}");
-        RebootReason::InvalidBcc
-    })?;
 
     debug!("Activating dynamic page table...");
     // SAFETY - page_table duplicates the static mappings for everything that the Rust code is
@@ -258,7 +253,7 @@
     let slices = MemorySlices::new(fdt, payload, payload_size, &mut memory)?;
 
     // This wrapper allows main() to be blissfully ignorant of platform details.
-    crate::main(slices.fdt, slices.kernel, slices.ramdisk, &bcc, &mut memory)?;
+    crate::main(slices.fdt, slices.kernel, slices.ramdisk, bcc_slice, &mut memory)?;
 
     helpers::flushed_zeroize(bcc_slice);
     helpers::flush(slices.fdt.as_slice());
diff --git a/pvmfw/src/main.rs b/pvmfw/src/main.rs
index f7774e4..ba26114 100644
--- a/pvmfw/src/main.rs
+++ b/pvmfw/src/main.rs
@@ -46,7 +46,7 @@
     memory::MemoryTracker,
     virtio::pci::{self, find_virtio_devices},
 };
-use ::dice::bcc;
+use diced_open_dice::{bcc_handover_main_flow, bcc_handover_parse, HIDDEN_SIZE};
 use fdtpci::{PciError, PciInfo};
 use libfdt::Fdt;
 use log::{debug, error, info, trace};
@@ -59,7 +59,7 @@
     fdt: &mut Fdt,
     signed_kernel: &[u8],
     ramdisk: Option<&[u8]>,
-    bcc: &bcc::Handover,
+    current_bcc_handover: &[u8],
     memory: &mut MemoryTracker,
 ) -> Result<(), RebootReason> {
     info!("pVM firmware");
@@ -71,7 +71,11 @@
     } else {
         debug!("Ramdisk: None");
     }
-    trace!("BCC: {bcc:x?}");
+    let bcc_handover = bcc_handover_parse(current_bcc_handover).map_err(|e| {
+        error!("Invalid BCC Handover: {e:?}");
+        RebootReason::InvalidBcc
+    })?;
+    trace!("BCC: {bcc_handover:x?}");
 
     // Set up PCI bus for VirtIO devices.
     let pci_info = PciInfo::from_fdt(fdt).map_err(handle_pci_error)?;
@@ -95,12 +99,12 @@
         error!("Failed to compute partial DICE inputs: {e:?}");
         RebootReason::InternalError
     })?;
-    let salt = [0; ::dice::HIDDEN_SIZE]; // TODO(b/249723852): Get from instance.img and/or TRNG.
+    let salt = [0; HIDDEN_SIZE]; // TODO(b/249723852): Get from instance.img and/or TRNG.
     let dice_inputs = dice_inputs.into_input_values(&salt).map_err(|e| {
         error!("Failed to generate DICE inputs: {e:?}");
         RebootReason::InternalError
     })?;
-    let _ = bcc.main_flow(&dice_inputs, next_bcc).map_err(|e| {
+    let _ = bcc_handover_main_flow(current_bcc_handover, &dice_inputs, next_bcc).map_err(|e| {
         error!("Failed to derive next-stage DICE secrets: {e:?}");
         RebootReason::SecretDerivationError
     })?;