diff --git a/.cargo/config b/.cargo/config.toml similarity index 86% rename from .cargo/config rename to .cargo/config.toml index 073d01a90b..e70dcfa7ad 100644 --- a/.cargo/config +++ b/.cargo/config.toml @@ -1,3 +1,5 @@ +# Licensed under the Apache-2.0 license + [target.riscv32imc-unknown-none-elf] rustflags = [ "-C", "target-feature=+relax", diff --git a/Cargo.lock b/Cargo.lock index 3d0a5c0588..7423b49a55 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -375,7 +375,6 @@ dependencies = [ "caliptra-lms-types", "caliptra-registers", "caliptra-test", - "caliptra_common", "cfg-if 1.0.0", "dpe", "openssl", @@ -1266,9 +1265,12 @@ dependencies = [ [[package]] name = "deranged" -version = "0.3.7" +version = "0.3.11" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7684a49fb1af197853ef7b2ee694bc1f5b4179556f1e5710e1760c5db6f5e929" +checksum = "b42b6fa04a440b495c8b04d0e71b707c585f83cb9cb28cf8cd0d976c315e31b4" +dependencies = [ + "powerfmt", +] [[package]] name = "derive_arbitrary" @@ -1835,6 +1837,12 @@ dependencies = [ "num-traits", ] +[[package]] +name = "num-conv" +version = "0.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "51d515d32fb182ee37cda2ccdcb92950d6a3c2893aa280e540671c2cd0f3b1d9" + [[package]] name = "num-integer" version = "0.1.45" @@ -2010,6 +2018,12 @@ dependencies = [ "ufmt", ] +[[package]] +name = "powerfmt" +version = "0.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "439ee305def115ba05938db6eb1644ff94165c5ab5e9420d1c1bcedbba909391" + [[package]] name = "ppv-lite86" version = "0.2.17" @@ -2413,12 +2427,14 @@ dependencies = [ [[package]] name = "time" -version = "0.3.29" +version = "0.3.37" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "426f806f4089c493dcac0d24c29c01e2c38baf8e30f1b716ee37e83d200b18fe" +checksum = "35e7868883861bd0e56d9ac6efcaaca0d6d5d82a2a7ec8209ff492c07cf37b21" dependencies = [ "deranged", "itoa", + "num-conv", + "powerfmt", "serde", "time-core", "time-macros", @@ -2432,10 +2448,11 @@ checksum = "ef927ca75afb808a4d64dd374f00a2adf8d0fcff8e7b184af886c3c87ec4a3f3" [[package]] name = "time-macros" -version = "0.2.15" +version = "0.2.19" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "4ad70d68dba9e1f8aceda7aa6711965dfec1cac869f311a51bd08b3a2ccbce20" +checksum = "2834e6017e3e5e4b9834939793b282bc03b37a3336245fa820e35e233e2a85de" dependencies = [ + "num-conv", "time-core", ] diff --git a/api/src/soc_mgr.rs b/api/src/soc_mgr.rs index 38a77ae2b8..2c617fd26e 100644 --- a/api/src/soc_mgr.rs +++ b/api/src/soc_mgr.rs @@ -315,11 +315,12 @@ pub trait SocManager { .as_mut_bytes() .split_at_mut(mem::size_of::()); - let mut header = MailboxReqHeader::mut_from_bytes(header_bytes as &mut [u8]).unwrap(); + let header = MailboxReqHeader::mut_from_bytes(header_bytes as &mut [u8]).unwrap(); header.chksum = calc_checksum(R::ID.into(), payload_bytes); - let Some(data) = SocManager::mailbox_exec(self, R::ID.into(), req.as_bytes(), resp_bytes)? else { - return Err(CaliptraApiError::MailboxNoResponseData); + let Some(data) = SocManager::mailbox_exec(self, R::ID.into(), req.as_bytes(), resp_bytes)? + else { + return Err(CaliptraApiError::MailboxNoResponseData); }; if data.len() < R::Resp::MIN_SIZE || data.len() > mem::size_of::() { diff --git a/builder/src/lib.rs b/builder/src/lib.rs index 7b06133515..729df38f77 100644 --- a/builder/src/lib.rs +++ b/builder/src/lib.rs @@ -388,7 +388,7 @@ pub fn elf2rom(elf_bytes: &[u8]) -> io::Result> { let elf = elf::ElfBytes::::minimal_parse(elf_bytes).map_err(other_err)?; let Some(segments) = elf.segments() else { - return Err(other_err("ELF file has no segments")) + return Err(other_err("ELF file has no segments")); }; for segment in segments { if segment.p_type != elf::abi::PT_LOAD { @@ -398,15 +398,21 @@ pub fn elf2rom(elf_bytes: &[u8]) -> io::Result> { let mem_offset = segment.p_paddr as usize; let len = segment.p_filesz as usize; let Some(src_bytes) = elf_bytes.get(file_offset..file_offset + len) else { - return Err(other_err(format!("segment at 0x{:x} out of file bounds", segment.p_offset))); + return Err(other_err(format!( + "segment at 0x{:x} out of file bounds", + segment.p_offset + ))); }; if len == 0 { continue; } let Some(dest_bytes) = result.get_mut(mem_offset..mem_offset + len) else { - return Err(other_err(format!( + return Err(other_err(format!( "segment at 0x{mem_offset:04x}..0x{:04x} exceeds the ROM region \ - of 0x0000..0x{:04x}", mem_offset + len, result.len()))); + of 0x0000..0x{:04x}", + mem_offset + len, + result.len() + ))); }; dest_bytes.copy_from_slice(src_bytes); } @@ -434,7 +440,7 @@ pub fn elf2rom(elf_bytes: &[u8]) -> io::Result> { pub fn elf_size(elf_bytes: &[u8]) -> io::Result { let elf = elf::ElfBytes::::minimal_parse(elf_bytes).map_err(other_err)?; let Some(segments) = elf.segments() else { - return Err(other_err("ELF file has no segments")) + return Err(other_err("ELF file has no segments")); }; let mut min_addr = u64::MAX; let mut max_addr = u64::MIN; @@ -445,11 +451,7 @@ pub fn elf_size(elf_bytes: &[u8]) -> io::Result { min_addr = min_addr.min(segment.p_paddr); max_addr = max_addr.max(segment.p_paddr + segment.p_filesz); } - Ok(if max_addr >= min_addr { - max_addr - min_addr - } else { - 0 - }) + Ok(max_addr.saturating_sub(min_addr)) } #[derive(Clone)] diff --git a/cfi/lib/src/cfi_counter.rs b/cfi/lib/src/cfi_counter.rs index 42b5bc64e5..bfc3ed26af 100644 --- a/cfi/lib/src/cfi_counter.rs +++ b/cfi/lib/src/cfi_counter.rs @@ -64,7 +64,8 @@ impl Default for CfiInt { } fn prng() -> &'static Xoshiro128 { - unsafe { &CFI_STATE.prng } + let cfi_state = &raw const CFI_STATE; + unsafe { &(*cfi_state).prng } } /// CFI counter @@ -177,8 +178,8 @@ impl CfiCounter { pub fn read() -> CfiInt { unsafe { CfiInt::from_raw( - core::ptr::read_volatile(&CFI_STATE.val as *const u32), - core::ptr::read_volatile(&CFI_STATE.mask as *const u32), + core::ptr::read_volatile(&raw const CFI_STATE.val), + core::ptr::read_volatile(&raw const CFI_STATE.mask), ) } } @@ -186,8 +187,8 @@ impl CfiCounter { /// Write counter value fn write(val: CfiInt) { unsafe { - core::ptr::write_volatile(&mut CFI_STATE.val as *mut u32, val.val); - core::ptr::write_volatile(&mut CFI_STATE.mask as *mut u32, val.masked_val); + core::ptr::write_volatile(&raw mut CFI_STATE.val, val.val); + core::ptr::write_volatile(&raw mut CFI_STATE.mask, val.masked_val); } } } diff --git a/ci-tools/size-history/src/git.rs b/ci-tools/size-history/src/git.rs index b543c88a7a..ec96f93bfc 100644 --- a/ci-tools/size-history/src/git.rs +++ b/ci-tools/size-history/src/git.rs @@ -29,7 +29,7 @@ impl CommitInfo { let mut title = expect_line_with_prefix(" ", lines.next())?.to_string(); 'inner: loop { let Some(line) = lines.next() else { - result.push(CommitInfo{ + result.push(CommitInfo { id: commit_id.into(), author: author.into(), title, diff --git a/ci-tools/size-history/src/main.rs b/ci-tools/size-history/src/main.rs index 6109e8ad17..242a947723 100644 --- a/ci-tools/size-history/src/main.rs +++ b/ci-tools/size-history/src/main.rs @@ -67,8 +67,12 @@ fn real_main() -> io::Result<()> { if !worktree.is_log_linear()? { println!("git history is not linear; attempting to squash PR"); - let (Ok(pull_request_title), Ok(base_ref)) = (env::var("PR_TITLE"), env::var("PR_BASE_COMMIT")) else { - return Err(other_err("non-linear history not supported outside of a PR")); + let (Ok(pull_request_title), Ok(base_ref)) = + (env::var("PR_TITLE"), env::var("PR_BASE_COMMIT")) + else { + return Err(other_err( + "non-linear history not supported outside of a PR", + )); }; let mut rebase_onto: String = base_ref; for merge_parents in worktree.merge_log()? { diff --git a/common/src/keyids.rs b/common/src/keyids.rs index 1689f550d7..f61f7ff85d 100644 --- a/common/src/keyids.rs +++ b/common/src/keyids.rs @@ -31,7 +31,7 @@ pub const KEY_ID_ROM_FMC_CDI: KeyId = KeyId::KeyId6; pub const KEY_ID_FMC_ECDSA_PRIV_KEY: KeyId = KeyId::KeyId7; #[cfg(feature = "rom")] pub const KEY_ID_FMC_MLDSA_KEYPAIR_SEED: KeyId = KeyId::KeyId8; -#[cfg(any(feature = "rom"))] +#[cfg(feature = "rom")] pub const KEY_ID_FW_KEY_LADDER: KeyId = KeyId::KeyId2; #[cfg(feature = "fmc")] pub const KEY_ID_RT_CDI: KeyId = KeyId::KeyId4; diff --git a/common/src/lib.rs b/common/src/lib.rs index 11c3c4467e..9dcc768103 100644 --- a/common/src/lib.rs +++ b/common/src/lib.rs @@ -39,7 +39,7 @@ pub use fuse::{FuseLogEntry, FuseLogEntryId}; pub use pcr::{PcrLogEntry, PcrLogEntryId, RT_FW_CURRENT_PCR, RT_FW_JOURNEY_PCR}; pub const FMC_ORG: u32 = 0x40000000; -pub const FMC_SIZE: u32 = 21 * 1024; +pub const FMC_SIZE: u32 = 22 * 1024; pub const RUNTIME_ORG: u32 = FMC_ORG + FMC_SIZE; pub const RUNTIME_SIZE: u32 = 128 * 1024; diff --git a/common/src/verifier.rs b/common/src/verifier.rs index 3fdd23db1c..64447011e6 100644 --- a/common/src/verifier.rs +++ b/common/src/verifier.rs @@ -32,7 +32,7 @@ pub struct FirmwareImageVerificationEnv<'a, 'b> { pub image: &'b [u8], } -impl<'a, 'b> ImageVerificationEnv for &mut FirmwareImageVerificationEnv<'a, 'b> { +impl ImageVerificationEnv for &mut FirmwareImageVerificationEnv<'_, '_> { /// Calculate 384 digest using SHA2 Engine fn sha384_digest(&mut self, offset: u32, len: u32) -> CaliptraResult { let err = CaliptraError::IMAGE_VERIFIER_ERR_DIGEST_OUT_OF_BOUNDS; diff --git a/common/src/x509.rs b/common/src/x509.rs index 5ce910a7d7..c031b649da 100644 --- a/common/src/x509.rs +++ b/common/src/x509.rs @@ -13,7 +13,6 @@ Abstract: --*/ use caliptra_drivers::*; use core::mem::size_of; -use core::usize; use zerocopy::IntoBytes; use crate::crypto::PubKey; diff --git a/coverage/src/lib.rs b/coverage/src/lib.rs index 13065fcd0e..5edd20c0a1 100644 --- a/coverage/src/lib.rs +++ b/coverage/src/lib.rs @@ -65,7 +65,7 @@ pub fn dump_emu_coverage_to_file( bitmap: &BitVec, ) -> std::io::Result<()> { let mut filename = format!("CovData{}", hex::encode(rand::random::<[u8; 16]>())); - filename.push_str(&'-'.to_string()); + filename.push('-'); filename.push_str(&tag.to_string()); filename.push_str(".bitvec"); @@ -110,7 +110,7 @@ pub fn get_bitvec_paths(dir: &str) -> Result, Box) -> anyhow::Result> { let instruction = u16::from_le_bytes([instruction[0], instruction[1]]); match instruction & 0b11 { - 0 | 1 | 2 => { + 0..=2 => { index += 2; } _ => { @@ -263,7 +263,7 @@ pub mod calculator { fn test_parse_trace_file() { // Create a temporary trace file for testing let temp_trace_file = "temp_trace.txt"; - let trace_data = vec![ + let trace_data = [ "SoC write4 *0x300300bc <- 0x0", "SoC write4 *0x30030110 <- 0x2625a00", "SoC write4 *0x30030114 <- 0x0", @@ -312,5 +312,5 @@ fn test_coverage_map_creation_data_files() { let paths = get_bitvec_paths("/tmp").unwrap(); let cv = CoverageMap::new(paths); - assert!(cv.map.get(&tag).is_some()); + assert!(cv.map.contains_key(&tag)); } diff --git a/cpu/Cargo.toml b/cpu/Cargo.toml index 6503f3f606..d69551b3b8 100644 --- a/cpu/Cargo.toml +++ b/cpu/Cargo.toml @@ -12,6 +12,7 @@ edition = "2021" # --profile=firmware \ # --features riscv riscv = [] +std = [] [lib] test = false diff --git a/drivers/Cargo.toml b/drivers/Cargo.toml index 4602772b84..3c9fb0f17e 100644 --- a/drivers/Cargo.toml +++ b/drivers/Cargo.toml @@ -28,7 +28,9 @@ caliptra-cfi-lib-git = { workspace = true, default-features = false, features = caliptra-cfi-derive-git = { workspace = true, optional = true } [features] +std = [] emu = [] +riscv = [] runtime = ["dep:dpe", "dep:caliptra-cfi-lib-git", "dep:caliptra-cfi-derive-git"] fmc = [] fpga_realtime = ["caliptra-hw-model/fpga_realtime"] @@ -45,4 +47,3 @@ caliptra-hw-model-types.workspace = true caliptra-hw-model.workspace = true caliptra-test.workspace = true openssl.workspace = true -caliptra_common.workspace = true diff --git a/drivers/src/dma.rs b/drivers/src/dma.rs index d6b5d799c8..94f9f01a0e 100644 --- a/drivers/src/dma.rs +++ b/drivers/src/dma.rs @@ -429,7 +429,7 @@ impl<'a> DmaMmio<'a> { } } -impl<'a> Mmio for &DmaMmio<'a> { +impl Mmio for &DmaMmio<'_> { #[inline(always)] unsafe fn read_volatile(&self, src: *const T) -> T { // we only support 32-bit reads @@ -444,7 +444,7 @@ impl<'a> Mmio for &DmaMmio<'a> { } } -impl<'a> MmioMut for &DmaMmio<'a> { +impl MmioMut for &DmaMmio<'_> { #[inline(always)] unsafe fn write_volatile(&self, dst: *mut T, src: T) { // we only support 32-bit writes diff --git a/drivers/src/ecc384.rs b/drivers/src/ecc384.rs index d130f7ff70..8e2b9aad05 100644 --- a/drivers/src/ecc384.rs +++ b/drivers/src/ecc384.rs @@ -59,7 +59,7 @@ impl From for Ecc384Seed<'_> { } } -/// ECC-384 Private Key output +/// ECC-384 Public Key output #[derive(Debug)] pub enum Ecc384PrivKeyOut<'a> { /// Array @@ -76,7 +76,7 @@ impl<'a> From<&'a mut Array4x12> for Ecc384PrivKeyOut<'a> { } } -impl<'a> From for Ecc384PrivKeyOut<'a> { +impl From for Ecc384PrivKeyOut<'_> { /// Converts to this type from the input type. fn from(value: KeyWriteArgs) -> Self { Self::Key(value) @@ -654,9 +654,6 @@ trait Ecc384KeyAccessErr { /// Convert to read seed operation error fn into_read_seed_err(self) -> CaliptraError; - /// Convert to read data operation error - fn into_read_data_err(self) -> CaliptraError; - /// Convert to read private key operation error fn into_read_priv_key_err(self) -> CaliptraError; @@ -674,15 +671,6 @@ impl Ecc384KeyAccessErr for KvAccessErr { } } - /// Convert to read data operation error - fn into_read_data_err(self) -> CaliptraError { - match self { - KvAccessErr::KeyRead => CaliptraError::DRIVER_ECC384_READ_DATA_KV_READ, - KvAccessErr::KeyWrite => CaliptraError::DRIVER_ECC384_READ_DATA_KV_WRITE, - KvAccessErr::Generic => CaliptraError::DRIVER_ECC384_READ_DATA_KV_UNKNOWN, - } - } - /// Convert to reads private key operation error fn into_read_priv_key_err(self) -> CaliptraError { match self { diff --git a/drivers/src/hmac.rs b/drivers/src/hmac.rs index ecb93d91e3..fd1cbd0e0b 100644 --- a/drivers/src/hmac.rs +++ b/drivers/src/hmac.rs @@ -21,7 +21,6 @@ use crate::{ #[cfg(not(feature = "no-cfi"))] use caliptra_cfi_derive::cfi_impl_fn; use caliptra_registers::hmac::HmacReg; -use core::usize; const HMAC_BLOCK_SIZE_BYTES: usize = 128; const HMAC_BLOCK_LEN_OFFSET: usize = 112; @@ -86,7 +85,7 @@ impl<'a> From<&'a mut Array4x16> for HmacTag<'a> { } } -impl<'a> From for HmacTag<'a> { +impl From for HmacTag<'_> { /// Converts to this type from the input type. fn from(value: KeyWriteArgs) -> Self { Self::Key(value) @@ -178,7 +177,7 @@ impl Hmac { trng: &mut Trng, mut tag: HmacTag<'a>, hmac_mode: HmacMode, - ) -> CaliptraResult { + ) -> CaliptraResult> { let hmac = self.hmac.regs_mut(); let mut csr_mode = false; @@ -636,7 +635,7 @@ pub struct HmacOp<'a> { csr_mode: bool, } -impl<'a> HmacOp<'a> { +impl HmacOp<'_> { /// /// Update the digest with data /// diff --git a/drivers/src/lib.rs b/drivers/src/lib.rs index 71301d2cb7..5a88805ee9 100644 --- a/drivers/src/lib.rs +++ b/drivers/src/lib.rs @@ -12,7 +12,7 @@ Abstract: --*/ -#![no_std] +#![cfg_attr(not(feature = "std"), no_std)] mod array; mod array_concat; diff --git a/drivers/src/memory_layout.rs b/drivers/src/memory_layout.rs index 4e2a381fb0..4089132715 100644 --- a/drivers/src/memory_layout.rs +++ b/drivers/src/memory_layout.rs @@ -90,8 +90,8 @@ pub const DPE_SIZE: u32 = 5 * 1024; pub const PCR_RESET_COUNTER_SIZE: u32 = 1024; pub const AUTH_MAN_IMAGE_METADATA_MAX_SIZE: u32 = 7 * 1024; pub const IDEVID_CSR_ENVELOP_SIZE: u32 = 9 * 1024; -pub const DATA_SIZE: u32 = 95 * 1024; -pub const STACK_SIZE: u32 = 64 * 1024; +pub const DATA_SIZE: u32 = 91 * 1024; +pub const STACK_SIZE: u32 = 68 * 1024; pub const ROM_STACK_SIZE: u32 = 61 * 1024; pub const ESTACK_SIZE: u32 = 1024; pub const ROM_ESTACK_SIZE: u32 = 1024; diff --git a/drivers/src/printer.rs b/drivers/src/printer.rs index 4b6d86c97d..70c804a0f8 100644 --- a/drivers/src/printer.rs +++ b/drivers/src/printer.rs @@ -68,8 +68,20 @@ impl uDisplay for HexBytes<'_> { where W: uWrite + ?Sized, { - for byte in self.0.iter() { - ufmt::uwrite!(f, "{:02X}", *byte)?; + // Rust can't prove the indexes are correct in a ufmt uwrite! macro. + for &x in self.0.iter() { + let c = x >> 4; + if c < 10 { + f.write_char((c + b'0') as char)?; + } else { + f.write_char((c - 10 + b'A') as char)?; + } + let c = x & 0xf; + if c < 10 { + f.write_char((c + b'0') as char)?; + } else { + f.write_char((c - 10 + b'A') as char)?; + } } Ok(()) } diff --git a/drivers/src/sha1.rs b/drivers/src/sha1.rs index d332329a14..7be1b0c5f7 100644 --- a/drivers/src/sha1.rs +++ b/drivers/src/sha1.rs @@ -216,7 +216,7 @@ pub struct Sha1DigestOp<'a> { data_size: usize, } -impl<'a> Sha1DigestOp<'a> { +impl Sha1DigestOp<'_> { /// Update the digest with data /// /// # Arguments diff --git a/drivers/src/sha256.rs b/drivers/src/sha256.rs index d374d7690e..b7120e0016 100644 --- a/drivers/src/sha256.rs +++ b/drivers/src/sha256.rs @@ -12,8 +12,6 @@ Abstract: --*/ -use core::usize; - use crate::{array::Array4x16, wait, Array4x8, CaliptraError, CaliptraResult}; use caliptra_registers::sha256::Sha256Reg; @@ -548,7 +546,7 @@ impl<'a> Sha256DigestOp<'a> for Sha256DigestOpHw<'a> { Ok(()) } } -impl<'a> Sha256DigestOpHw<'a> { +impl Sha256DigestOpHw<'_> { /// Check if this the first digest operation fn is_first(&self) -> bool { self.state == Sha256DigestState::Init diff --git a/drivers/src/sha2_512_384.rs b/drivers/src/sha2_512_384.rs index 7c7b2a32b1..686fdab371 100644 --- a/drivers/src/sha2_512_384.rs +++ b/drivers/src/sha2_512_384.rs @@ -12,8 +12,6 @@ Abstract: --*/ -use core::usize; - use crate::kv_access::{KvAccess, KvAccessErr}; use crate::PcrId; use crate::{array::Array4x32, wait, Array4x12, Array4x16, Array4x8}; @@ -439,7 +437,7 @@ pub struct Sha2DigestOp<'a, V> { _phantom: core::marker::PhantomData, } -impl<'a, V> Sha2DigestOp<'a, V> { +impl Sha2DigestOp<'_, V> { /// Check if this the first digest operation fn is_first(&self) -> bool { self.state == Sha2DigestState::Init @@ -490,7 +488,7 @@ pub trait Sha2DigestOpTrait<'a, V>: Sized { /// The digest type for this SHA-2 variant type DigestType; - /// + /// Get as Digest Op fn as_digest_op(&mut self) -> &mut Sha2DigestOp<'a, V>; /// Get the SHA mode for this variant diff --git a/drivers/src/sha2_512_384acc.rs b/drivers/src/sha2_512_384acc.rs index 5b031612ff..2d593d7fb2 100644 --- a/drivers/src/sha2_512_384acc.rs +++ b/drivers/src/sha2_512_384acc.rs @@ -46,14 +46,14 @@ impl Sha2_512_384Acc { /// # Arguments /// /// * assumed_lock_state - The assumed lock state of the SHA384 Accelerator. - /// Note: Callers should pass assumed_lock_state=ShaAccLockState::NotAcquired - /// unless they are the first caller to the peripheral after a cold/warm boot. + /// Note: Callers should pass assumed_lock_state=ShaAccLockState::NotAcquired + /// unless they are the first caller to the peripheral after a cold/warm boot. /// /// # Returns /// /// * On success, either an object representing the SHA384 accelerator operation or - /// 'None' if unable to acquire the SHA384 Accelerator lock. - /// On failure, an error code. + /// 'None' if unable to acquire the SHA384 Accelerator lock. + /// On failure, an error code. /// pub fn try_start_operation( &mut self, diff --git a/drivers/test-fw/Cargo.toml b/drivers/test-fw/Cargo.toml index 09d3c91085..bf9fda9fcf 100644 --- a/drivers/test-fw/Cargo.toml +++ b/drivers/test-fw/Cargo.toml @@ -28,6 +28,7 @@ fpga_realtime = [] # --profile=firmware \ # --features riscv riscv = ["caliptra-test-harness/riscv"] +runtime = [] [[bin]] name = "mbox_send_txn_drop" diff --git a/fmc/Cargo.toml b/fmc/Cargo.toml index a2e4fd245f..bc5093a609 100644 --- a/fmc/Cargo.toml +++ b/fmc/Cargo.toml @@ -32,11 +32,12 @@ caliptra-image-types.workspace = true openssl.workspace = true [features] -default = ["std"] +default = ["std", "caliptra-drivers/no-cfi"] emu = ["caliptra_common/emu", "caliptra-drivers/emu"] -riscv = ["caliptra-cpu/riscv"] -std = ["ufmt/std", "caliptra_common/std"] +fake-fmc = [] fpga_realtime = ["caliptra-hw-model/fpga_realtime"] itrng = ["caliptra-hw-model/itrng"] +no-cfi = ["caliptra-drivers/no-cfi"] +riscv = ["caliptra-cpu/riscv"] +std = ["ufmt/std", "caliptra_common/std", "caliptra-drivers/std", "caliptra-cpu/std"] verilator = ["caliptra-hw-model/verilator"] -fake-fmc = [] diff --git a/fmc/src/flow/dice.rs b/fmc/src/flow/dice.rs index 0ba87eee8a..b2bd42c002 100644 --- a/fmc/src/flow/dice.rs +++ b/fmc/src/flow/dice.rs @@ -40,9 +40,11 @@ pub struct DiceInput { pub mldsa_auth_key_pair: MlDsaKeyPair, /// MLDSA Authority Serial Number + #[allow(dead_code)] // [TODO][CAP2] remove when used pub mldsa_auth_sn: [u8; 64], /// MLDSA Authority Key Identifier + #[allow(dead_code)] // [TODO][CAP2] remove when used pub mldsa_auth_key_id: [u8; 20], } @@ -62,11 +64,14 @@ pub struct DiceOutput { pub ecc_subj_key_id: [u8; 20], /// MLDSA Subject key pair for this layer + #[allow(dead_code)] // [TODO][CAP2] remove when used pub mldsa_subj_key_pair: MlDsaKeyPair, /// MLDSA Subject Serial Number + #[allow(dead_code)] // [TODO][CAP2] remove when used pub mldsa_subj_sn: [u8; 64], /// MLDSA Subject Key Identifier + #[allow(dead_code)] // [TODO][CAP2] remove when used pub mldsa_subj_key_id: [u8; 20], } diff --git a/hw-model/c-binding/src/caliptra_model.rs b/hw-model/c-binding/src/caliptra_model.rs index 1e08bb9d49..52aa2bedc8 100644 --- a/hw-model/c-binding/src/caliptra_model.rs +++ b/hw-model/c-binding/src/caliptra_model.rs @@ -151,7 +151,7 @@ pub unsafe extern "C" fn caliptra_model_output_peek(model: *mut caliptra_model) assert!(!model.is_null()); let peek_str = (*{ model as *mut DefaultHwModel }).output().peek(); caliptra_buffer { - data: peek_str.as_ptr() as *const u8, + data: peek_str.as_ptr(), len: peek_str.len(), } } diff --git a/hw-model/src/lib.rs b/hw-model/src/lib.rs index 3b2b99fc98..a14ff6448e 100644 --- a/hw-model/src/lib.rs +++ b/hw-model/src/lib.rs @@ -91,14 +91,13 @@ pub const DEFAULT_APB_PAUSER: u32 = 0x01; /// should use [`new`] instead. pub fn new_unbooted(params: InitParams) -> Result> { let summary = params.summary(); - DefaultHwModel::new_unbooted(params).map(|hw| { + DefaultHwModel::new_unbooted(params).inspect(|hw| { println!( "Using hardware-model {} trng={:?}", hw.type_name(), hw.trng_mode() ); println!("{summary:#?}"); - hw }) } @@ -192,7 +191,7 @@ pub struct InitParams<'a> { // overflows. pub stack_info: Option, } -impl<'a> Default for InitParams<'a> { +impl Default for InitParams<'_> { fn default() -> Self { let seed = std::env::var("CPTRA_TRNG_SEED") .ok() @@ -234,7 +233,7 @@ impl<'a> Default for InitParams<'a> { } } -impl<'a> InitParams<'a> { +impl InitParams<'_> { fn summary(&self) -> InitParamsSummary { InitParamsSummary { rom_sha384: sha2::Sha384::digest(self.rom).into(), @@ -276,7 +275,7 @@ pub struct BootParams<'a> { pub wdt_timeout_cycles: u64, } -impl<'a> Default for BootParams<'a> { +impl Default for BootParams<'_> { fn default() -> Self { Self { fuses: Default::default(), @@ -474,7 +473,7 @@ pub struct MailboxRecvTxn<'a, TModel: HwModel> { model: &'a mut TModel, pub req: MailboxRequest, } -impl<'a, Model: HwModel> MailboxRecvTxn<'a, Model> { +impl MailboxRecvTxn<'_, Model> { pub fn respond_success(self) { self.complete(MboxStatusE::CmdComplete); } diff --git a/hw-model/src/model_emulated.rs b/hw-model/src/model_emulated.rs index 1d90303275..a6fd07a3c3 100644 --- a/hw-model/src/model_emulated.rs +++ b/hw-model/src/model_emulated.rs @@ -34,7 +34,7 @@ pub struct EmulatedApbBus<'a> { model: &'a mut ModelEmulated, } -impl<'a> Bus for EmulatedApbBus<'a> { +impl Bus for EmulatedApbBus<'_> { fn read(&mut self, size: RvSize, addr: RvAddr) -> Result { let result = self.model.soc_to_caliptra_bus.read(size, addr); self.model.cpu.bus.log_read("SoC", size, addr, result); diff --git a/hw-model/tests/model_tests.rs b/hw-model/tests/model_tests.rs index 6b64bf3dcc..7fed1955aa 100644 --- a/hw-model/tests/model_tests.rs +++ b/hw-model/tests/model_tests.rs @@ -29,7 +29,8 @@ fn wait_with_timeout(child: &mut Child, timeout: Duration) -> Option { fn run_fw_elf(elf: &[u8]) -> DefaultHwModel { let rom = caliptra_builder::elf2rom(elf).unwrap(); - let model = caliptra_hw_model::new( + + caliptra_hw_model::new( InitParams { rom: &rom, random_sram_puf: false, @@ -37,21 +38,20 @@ fn run_fw_elf(elf: &[u8]) -> DefaultHwModel { }, BootParams::default(), ) - .unwrap(); - model + .unwrap() } fn run_fw_elf_with_rand_puf(elf: &[u8]) -> DefaultHwModel { let rom = caliptra_builder::elf2rom(elf).unwrap(); - let model = caliptra_hw_model::new( + + caliptra_hw_model::new( InitParams { rom: &rom, ..Default::default() }, BootParams::default(), ) - .unwrap(); - model + .unwrap() } #[test] diff --git a/hw-model/types/src/lib.rs b/hw-model/types/src/lib.rs index 471bde0330..622ba4e16f 100644 --- a/hw-model/types/src/lib.rs +++ b/hw-model/types/src/lib.rs @@ -1,6 +1,6 @@ // Licensed under the Apache-2.0 license -use caliptra_api_types::{self, Fuses, SecurityState}; +use caliptra_api_types::{self}; use std::array; pub use caliptra_api_types::DeviceLifecycle; @@ -30,15 +30,6 @@ pub const DEFAULT_CPTRA_OBF_KEY: [u32; 8] = [ pub const DEFAULT_MANUF_DEBUG_UNLOCK_TOKEN: [u32; 4] = [0xcfcecdcc, 0xcbcac9c8, 0xc7c6c5c4, 0xc3c2c1c0]; -struct SecurityStateWrapper(SecurityState); -impl std::fmt::Debug for SecurityStateWrapper { - fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { - f.debug_struct("SecurityState") - .field("debug_locked", &self.0.debug_locked()) - .field("device_lifecycle", &self.0.device_lifecycle()) - .finish() - } -} #[derive(Clone, Copy, PartialEq, Eq, Debug, Default)] pub enum U4 { #[default] @@ -109,33 +100,8 @@ impl TryFrom for U4 { } } -struct FusesWrapper(Fuses); -impl std::fmt::Debug for FusesWrapper { - fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { - f.debug_struct("Fuses") - .field("uds_seed", &HexSlice(&self.0.uds_seed)) - .field("field_entropy", &HexSlice(&self.0.field_entropy)) - .field("vendor_pk_hash", &HexSlice(&self.0.vendor_pk_hash)) - .field("fuse_ecc_revocation", &self.0.fuse_ecc_revocation) - .field("owner_pk_hash", &HexSlice(&self.0.owner_pk_hash)) - .field("firmware_svn", &HexSlice(&self.0.fw_svn)) - .field("anti_rollback_disable", &self.0.anti_rollback_disable) - .field("idevid_cert_attr", &HexSlice(&self.0.idevid_cert_attr)) - .field( - "idevid_manuf_hsm_id", - &HexSlice(&self.0.idevid_manuf_hsm_id), - ) - .field("life_cycle", &self.0.life_cycle) - .field("fuse_lms_revocation", &self.0.fuse_lms_revocation) - .field("fuse_mldsa_revocation", &self.0.fuse_mldsa_revocation) - .field("soc_stepping_id", &self.0.soc_stepping_id) - .field("fuse_pqc_key_type", &self.0.fuse_pqc_key_type) - .finish() - } -} - pub struct HexSlice<'a, T: std::fmt::LowerHex + PartialEq>(pub &'a [T]); -impl<'a, T: std::fmt::LowerHex + PartialEq> std::fmt::Debug for HexSlice<'a, T> { +impl std::fmt::Debug for HexSlice<'_, T> { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { let width = std::mem::size_of::() * 2 + 2; if self.0.len() > 1 && self.0.iter().all(|item| item == &self.0[0]) { @@ -155,7 +121,7 @@ impl<'a, T: std::fmt::LowerHex + PartialEq> std::fmt::Debug for HexSlice<'a, T> } pub struct HexBytes<'a>(pub &'a [u8]); -impl<'a> std::fmt::Debug for HexBytes<'a> { +impl std::fmt::Debug for HexBytes<'_> { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { write!(f, "\"")?; for val in self.0.iter() { diff --git a/image/crypto/src/lib.rs b/image/crypto/src/lib.rs index 7ce1a2f98e..3e7e9c9847 100644 --- a/image/crypto/src/lib.rs +++ b/image/crypto/src/lib.rs @@ -192,8 +192,8 @@ fn generate_lms_pubkey_helper( Some(_) => 1, None => (((1 << tree_height) as u32) + q.unwrap()) ^ 1, }; - let mut k = vec![0u8; SHA192_DIGEST_BYTE_SIZE]; - let zero_k = vec![0u8; SHA192_DIGEST_BYTE_SIZE]; + let mut k = [0u8; SHA192_DIGEST_BYTE_SIZE]; + let zero_k = [0u8; SHA192_DIGEST_BYTE_SIZE]; let mut level: usize = 0; let mut pub_key_stack = vec![0u8; SHA192_DIGEST_BYTE_SIZE * (tree_height as usize)]; diff --git a/image/elf/src/lib.rs b/image/elf/src/lib.rs index ef4db31c02..1e91154991 100644 --- a/image/elf/src/lib.rs +++ b/image/elf/src/lib.rs @@ -64,7 +64,12 @@ impl ElfExecutable { bail!("ELF file has no segments"); }; - let Some(load_addr) = segments.iter().filter(|s| s.p_type == PT_LOAD).map(|s| s.p_paddr as u32).min() else { + let Some(load_addr) = segments + .iter() + .filter(|s| s.p_type == PT_LOAD) + .map(|s| s.p_paddr as u32) + .min() + else { bail!("ELF file has no LOAD segments"); }; diff --git a/image/gen/src/lib.rs b/image/gen/src/lib.rs index 4ebec2823b..3fc4ee66f0 100644 --- a/image/gen/src/lib.rs +++ b/image/gen/src/lib.rs @@ -123,7 +123,7 @@ pub fn from_hw_format(value: &[u32; ECC384_SCALAR_WORD_SIZE]) -> [u8; ECC384_SCA } /// Image Generator Vendor Configuration -#[derive(Default, Clone)] +#[derive(Default, Clone, Copy)] pub struct ImageGeneratorVendorConfig { pub ecc_key_count: u32, diff --git a/lms-types/src/lib.rs b/lms-types/src/lib.rs index 31faaf8025..1b890922f5 100644 --- a/lms-types/src/lib.rs +++ b/lms-types/src/lib.rs @@ -1,6 +1,7 @@ // Licensed under the Apache-2.0 license -#![cfg_attr(all(not(test), not(fuzzing)), no_std)] +// TODO not(fuzzing), attribute not found +#![cfg_attr(not(test), no_std)] use core::mem::size_of; diff --git a/rom/dev/src/flow/cold_reset/dice.rs b/rom/dev/src/flow/cold_reset/dice.rs index 98afca43cc..78612570d9 100644 --- a/rom/dev/src/flow/cold_reset/dice.rs +++ b/rom/dev/src/flow/cold_reset/dice.rs @@ -32,9 +32,11 @@ pub struct DiceInput<'a> { pub mldsa_auth_key_pair: &'a MlDsaKeyPair, /// MLDSA Authority Serial Number + #[allow(dead_code)] // [TODO][CAP2] remove when used pub mldsa_auth_sn: &'a [u8; 64], /// MLDSA Authority Key Identifier + #[allow(dead_code)] // [TODO][CAP2] remove when used pub mldsa_auth_key_id: &'a [u8; 20], } diff --git a/rom/dev/src/flow/cold_reset/fw_processor.rs b/rom/dev/src/flow/cold_reset/fw_processor.rs index 7f8f77674a..c2310bcce5 100644 --- a/rom/dev/src/flow/cold_reset/fw_processor.rs +++ b/rom/dev/src/flow/cold_reset/fw_processor.rs @@ -77,7 +77,7 @@ impl FirmwareProcessor { // Hmac-512/384 Engine hmac: &mut env.hmac, - /// Cryptographically Secure Random Number Generator + // Cryptographically Secure Random Number Generator trng: &mut env.trng, // LMS Engine @@ -86,10 +86,10 @@ impl FirmwareProcessor { // Mldsa87 Engine mldsa87: &mut env.mldsa87, - /// Ecc384 Engine + // Ecc384 Engine ecc384: &mut env.ecc384, - /// SHA Acc lock state + // SHA Acc lock state sha_acc_lock_state: ShaAccLockState::NotAcquired, }; // Process mailbox commands. diff --git a/rom/dev/src/flow/cold_reset/mod.rs b/rom/dev/src/flow/cold_reset/mod.rs index a81835ee0e..7f66e72ca9 100644 --- a/rom/dev/src/flow/cold_reset/mod.rs +++ b/rom/dev/src/flow/cold_reset/mod.rs @@ -108,7 +108,7 @@ impl ColdResetFlow { #[cfg_attr(not(feature = "no-cfi"), cfi_mod_fn)] #[inline(never)] pub fn copy_tbs(tbs: &[u8], tbs_type: TbsType, env: &mut RomEnv) -> CaliptraResult<()> { - let mut persistent_data = env.persistent_data.get_mut(); + let persistent_data = env.persistent_data.get_mut(); let dst = match tbs_type { TbsType::EccLdevid => { persistent_data.fht.ecc_ldevid_tbs_size = tbs.len() as u16; diff --git a/rom/dev/src/flow/fake.rs b/rom/dev/src/flow/fake.rs index 7bcb712bd0..6565829bd3 100644 --- a/rom/dev/src/flow/fake.rs +++ b/rom/dev/src/flow/fake.rs @@ -216,7 +216,12 @@ pub fn copy_canned_ldev_cert(env: &mut RomEnv) -> CaliptraResult<()> { // Copy TBS to DCCM let tbs = &FAKE_LDEV_TBS; env.persistent_data.get_mut().fht.ecc_ldevid_tbs_size = u16::try_from(tbs.len()).unwrap(); - let Some(dst) = env.persistent_data.get_mut().ecc_ldevid_tbs.get_mut(..tbs.len()) else { + let Some(dst) = env + .persistent_data + .get_mut() + .ecc_ldevid_tbs + .get_mut(..tbs.len()) + else { return Err(CaliptraError::ROM_GLOBAL_UNSUPPORTED_LDEVID_TBS_SIZE); }; dst.copy_from_slice(tbs); @@ -236,7 +241,12 @@ pub fn copy_canned_fmc_alias_cert(env: &mut RomEnv) -> CaliptraResult<()> { // Copy TBS to DCCM let tbs = &FAKE_FMC_ALIAS_TBS; env.persistent_data.get_mut().fht.ecc_fmcalias_tbs_size = u16::try_from(tbs.len()).unwrap(); - let Some(dst) = env.persistent_data.get_mut().ecc_fmcalias_tbs.get_mut(..tbs.len()) else { + let Some(dst) = env + .persistent_data + .get_mut() + .ecc_fmcalias_tbs + .get_mut(..tbs.len()) + else { return Err(CaliptraError::ROM_GLOBAL_UNSUPPORTED_FMCALIAS_TBS_SIZE); }; dst.copy_from_slice(tbs); diff --git a/rom/dev/src/main.rs b/rom/dev/src/main.rs index e9d8c7ae42..ee14549852 100644 --- a/rom/dev/src/main.rs +++ b/rom/dev/src/main.rs @@ -153,7 +153,7 @@ pub extern "C" fn rom_entry() -> ! { // Hmac-512/384 Engine hmac: &mut env.hmac, - /// Cryptographically Secure Random Number Generator + // Cryptographically Secure Random Number Generator trng: &mut env.trng, // LMS Engine @@ -162,13 +162,13 @@ pub extern "C" fn rom_entry() -> ! { // MLDSA87 Engine mldsa87: &mut env.mldsa87, - /// Ecc384 Engine + // Ecc384 Engine ecc384: &mut env.ecc384, - /// SHA Acc lock state. - /// SHA Acc is guaranteed to be locked on Cold and Warm Resets; - /// On an Update Reset, it is expected to be unlocked. - /// Not having it unlocked will result in a fatal error. + // SHA Acc lock state. + // SHA Acc is guaranteed to be locked on Cold and Warm Resets; + // On an Update Reset, it is expected to be unlocked. + // Not having it unlocked will result in a fatal error. sha_acc_lock_state: if reset_reason == ResetReason::UpdateReset { ShaAccLockState::NotAcquired } else { diff --git a/rom/dev/src/rom_env.rs b/rom/dev/src/rom_env.rs index 81eeb95f05..0ed8760fc8 100644 --- a/rom/dev/src/rom_env.rs +++ b/rom/dev/src/rom_env.rs @@ -15,7 +15,6 @@ Abstract: --*/ -use crate::fht::FhtDataStore; use caliptra_drivers::{ DeobfuscationEngine, Dma, Ecc384, Hmac, KeyVault, Lms, Mailbox, Mldsa87, PcrBank, PersistentDataAccessor, Sha1, Sha256, Sha2_512_384, Sha2_512_384Acc, SocIfc, Trng, @@ -65,9 +64,6 @@ pub struct RomEnv { /// PCR Bank pub pcr_bank: PcrBank, - /// FHT Data Store - pub fht_data_store: FhtDataStore, - /// Cryptographically Secure Random Number Generator pub trng: Trng, @@ -103,7 +99,6 @@ impl RomEnv { soc_ifc: SocIfc::new(SocIfcReg::new()), mbox: Mailbox::new(MboxCsr::new()), pcr_bank: PcrBank::new(PvReg::new()), - fht_data_store: FhtDataStore::default(), trng, persistent_data: PersistentDataAccessor::new(), mldsa87: Mldsa87::new(MldsaReg::new()), diff --git a/rom/dev/tests/rom_integration_tests/test_image_validation.rs b/rom/dev/tests/rom_integration_tests/test_image_validation.rs index 206142b886..784a7d37f2 100644 --- a/rom/dev/tests/rom_integration_tests/test_image_validation.rs +++ b/rom/dev/tests/rom_integration_tests/test_image_validation.rs @@ -136,7 +136,7 @@ fn test_invalid_manifest_size() { fn test_invalid_pqc_key_type() { let (mut hw, mut image_bundle) = helpers::build_hw_model_and_image_bundle(Fuses::default(), ImageOptions::default()); - for pqc_key_type in 0..std::u8::MAX { + for pqc_key_type in 0..u8::MAX { if pqc_key_type == FwVerificationPqcKeyType::LMS as u8 || pqc_key_type == FwVerificationPqcKeyType::MLDSA as u8 { @@ -496,7 +496,7 @@ fn test_preamble_vendor_ecc_pubkey_revocation() { }; let rom = caliptra_builder::build_firmware_rom(firmware::rom_from_env()).unwrap(); const LAST_KEY_IDX: u32 = VENDOR_ECC_MAX_KEY_COUNT - 1; - const VENDOR_CONFIG_LIST: [ImageGeneratorVendorConfig; VENDOR_ECC_MAX_KEY_COUNT as usize] = [ + static VENDOR_CONFIG_LIST: [ImageGeneratorVendorConfig; VENDOR_ECC_MAX_KEY_COUNT as usize] = [ VENDOR_CONFIG_KEY_0, VENDOR_CONFIG_KEY_1, VENDOR_CONFIG_KEY_2, diff --git a/rom/dev/tools/test-fmc/src/main.rs b/rom/dev/tools/test-fmc/src/main.rs index a0f3ac3a80..44d2314c7a 100644 --- a/rom/dev/tools/test-fmc/src/main.rs +++ b/rom/dev/tools/test-fmc/src/main.rs @@ -372,7 +372,7 @@ fn read_pcrs(mbox: &caliptra_registers::mbox::RegisterBlock) { const PCR_COUNT: usize = 32; for i in 0..PCR_COUNT { let pcr = pcr_bank.read_pcr(PcrId::try_from(i as u8).unwrap()); - let mut pcr_bytes: [u32; 12] = pcr.try_into().unwrap(); + let mut pcr_bytes: [u32; 12] = pcr.into(); swap_word_bytes_inplace(&mut pcr_bytes); send_to_mailbox(mbox, pcr.as_bytes(), false); diff --git a/runtime/src/authorize_and_stash.rs b/runtime/src/authorize_and_stash.rs index ea5a123a65..d8ad28c662 100644 --- a/runtime/src/authorize_and_stash.rs +++ b/runtime/src/authorize_and_stash.rs @@ -12,37 +12,18 @@ Abstract: --*/ -use core::cmp::{self, min}; -use core::mem::size_of; - -use crate::{dpe_crypto::DpeCrypto, CptraDpeTypes, DpePlatform, Drivers, StashMeasurementCmd}; +use crate::{Drivers, StashMeasurementCmd}; use caliptra_auth_man_types::{ - AuthManifestImageMetadata, AuthManifestImageMetadataCollection, AuthManifestPreamble, - ImageMetadataFlags, AUTH_MANIFEST_MARKER, + AuthManifestImageMetadata, AuthManifestImageMetadataCollection, ImageMetadataFlags, }; use caliptra_cfi_derive_git::cfi_impl_fn; use caliptra_cfi_lib_git::{cfi_assert, cfi_assert_eq, cfi_launder}; use caliptra_common::mailbox_api::{ AuthAndStashFlags, AuthorizeAndStashReq, AuthorizeAndStashResp, ImageHashSource, MailboxResp, - MailboxRespHeader, SetAuthManifestReq, -}; -use caliptra_drivers::{ - pcr_log::PCR_ID_STASH_MEASUREMENT, Array4x12, Array4xN, AuthManifestImageMetadataList, - CaliptraError, CaliptraResult, Ecc384, Ecc384PubKey, Ecc384Signature, HashValue, Lms, - PersistentData, Sha256, Sha2_512_384, SocIfc, -}; -use caliptra_image_types::{ - ImageDigest384, ImageEccPubKey, ImageEccSignature, ImageLmsPublicKey, ImageLmsSignature, - ImagePreamble, SHA192_DIGEST_WORD_SIZE, SHA384_DIGEST_BYTE_SIZE, -}; -use crypto::{AlgLen, Crypto}; -use dpe::{ - commands::{CommandExecution, DeriveContextCmd, DeriveContextFlags}, - context::ContextHandle, - dpe_instance::DpeEnv, - response::DpeErrorCode, + MailboxRespHeader, }; -use memoffset::offset_of; +use caliptra_drivers::{Array4x12, CaliptraError, CaliptraResult}; +use dpe::response::DpeErrorCode; use zerocopy::{FromBytes, IntoBytes}; pub const IMAGE_AUTHORIZED: u32 = 0xDEADC0DE; // Either FW ID and image digest matched or 'ignore_auth_check' is set for the FW ID. @@ -137,6 +118,10 @@ impl AuthorizeAndStashCmd { .image_metadata_list .binary_search_by(|metadata| metadata.fw_id.cmp(&cmd_fw_id)) .ok() - .map(|index| &auth_manifest_image_metadata_col.image_metadata_list[index]) + .map(|index| { + auth_manifest_image_metadata_col + .image_metadata_list + .get(index) + })? } } diff --git a/runtime/src/certify_key_extended.rs b/runtime/src/certify_key_extended.rs index afd4d93c96..322ad50ebe 100644 --- a/runtime/src/certify_key_extended.rs +++ b/runtime/src/certify_key_extended.rs @@ -12,25 +12,18 @@ Abstract: --*/ -use core::str::from_utf8; - -use arrayvec::ArrayVec; -use bitflags::bitflags; use caliptra_common::mailbox_api::{ CertifyKeyExtendedFlags, CertifyKeyExtendedReq, CertifyKeyExtendedResp, MailboxResp, MailboxRespHeader, }; use caliptra_error::{CaliptraError, CaliptraResult}; use dpe::{ - commands::{CertifyKeyCmd, Command, CommandExecution}, + commands::{CertifyKeyCmd, CommandExecution}, response::Response, }; use zerocopy::{FromBytes, IntoBytes}; -use crate::{ - CptraDpeTypes, DpeCrypto, DpeEnv, DpePlatform, Drivers, PauserPrivileges, MAX_CERT_CHAIN_SIZE, - PL0_PAUSER_FLAG, -}; +use crate::{CptraDpeTypes, DpeCrypto, DpeEnv, DpePlatform, Drivers, PauserPrivileges}; pub struct CertifyKeyExtendedCmd; impl CertifyKeyExtendedCmd { diff --git a/runtime/src/dice.rs b/runtime/src/dice.rs index ca0c072cc6..e8fbdf15c4 100644 --- a/runtime/src/dice.rs +++ b/runtime/src/dice.rs @@ -19,10 +19,7 @@ use caliptra_common::mailbox_api::{ use crate::Drivers; -use caliptra_drivers::{ - hand_off::DataStore, CaliptraError, CaliptraResult, DataVault, Ecc384Scalar, Ecc384Signature, - PersistentData, -}; +use caliptra_drivers::{CaliptraError, CaliptraResult, Ecc384Signature, PersistentData}; use caliptra_x509::{Ecdsa384CertBuilder, Ecdsa384Signature}; use zerocopy::IntoBytes; @@ -44,7 +41,8 @@ impl IDevIdCertCmd { s: cmd.signature_s, }; - let Some(builder) = Ecdsa384CertBuilder::new(&cmd.tbs[..cmd.tbs_size as usize], &sig) else { + let Some(builder) = Ecdsa384CertBuilder::new(&cmd.tbs[..cmd.tbs_size as usize], &sig) + else { return Err(CaliptraError::RUNTIME_GET_IDEVID_CERT_FAILED); }; diff --git a/runtime/src/disable.rs b/runtime/src/disable.rs index 3d46845164..491b9c0af3 100644 --- a/runtime/src/disable.rs +++ b/runtime/src/disable.rs @@ -16,8 +16,8 @@ use crate::Drivers; use caliptra_cfi_derive_git::cfi_impl_fn; use caliptra_common::mailbox_api::MailboxResp; use caliptra_drivers::{ - hmac_kdf, Array4x12, CaliptraError, CaliptraResult, Ecc384Seed, HmacKey, HmacMode, KeyReadArgs, - KeyUsage, KeyWriteArgs, + hmac_kdf, Array4x12, CaliptraResult, Ecc384Seed, HmacKey, HmacMode, KeyReadArgs, KeyUsage, + KeyWriteArgs, }; use dpe::U8Bool; diff --git a/runtime/src/dpe_crypto.rs b/runtime/src/dpe_crypto.rs index f399f41fc2..642de1c098 100644 --- a/runtime/src/dpe_crypto.rs +++ b/runtime/src/dpe_crypto.rs @@ -18,7 +18,7 @@ use caliptra_cfi_derive_git::cfi_impl_fn; use caliptra_cfi_lib_git::{cfi_assert, cfi_assert_eq, cfi_launder}; use caliptra_common::keyids::{KEY_ID_DPE_CDI, KEY_ID_DPE_PRIV_KEY, KEY_ID_TMP}; use caliptra_drivers::{ - cprintln, hmac_kdf, + hmac_kdf, sha2_512_384::{Sha2DigestOpTrait, Sha384}, Array4x12, Ecc384, Ecc384PrivKeyIn, Ecc384PubKey, Ecc384Scalar, Ecc384Seed, Hmac, HmacData, HmacKey, HmacMode, HmacTag, KeyId, KeyReadArgs, KeyUsage, KeyVault, KeyWriteArgs, Sha2DigestOp, @@ -82,7 +82,7 @@ impl<'a> DpeHasher<'a> { } } -impl<'a> Hasher for DpeHasher<'a> { +impl Hasher for DpeHasher<'_> { fn update(&mut self, bytes: &[u8]) -> Result<(), CryptoError> { self.op .update(bytes) @@ -98,9 +98,12 @@ impl<'a> Hasher for DpeHasher<'a> { } } -impl<'a> Crypto for DpeCrypto<'a> { +impl Crypto for DpeCrypto<'_> { type Cdi = KeyId; - type Hasher<'b> = DpeHasher<'b> where Self: 'b; + type Hasher<'b> + = DpeHasher<'b> + where + Self: 'b; type PrivKey = KeyId; fn rand_bytes(&mut self, dst: &mut [u8]) -> Result<(), CryptoError> { diff --git a/runtime/src/dpe_platform.rs b/runtime/src/dpe_platform.rs index 46abb3080d..4b6c863340 100644 --- a/runtime/src/dpe_platform.rs +++ b/runtime/src/dpe_platform.rs @@ -16,19 +16,13 @@ use core::cmp::min; use arrayvec::ArrayVec; use caliptra_drivers::cprintln; -use caliptra_image_types::{ImageHeader, ImageManifest}; use caliptra_x509::{NotAfter, NotBefore}; use crypto::Digest; -use dpe::{ - x509::{CertWriter, DirectoryString, Name}, - DPE_PROFILE, -}; +use dpe::x509::{CertWriter, DirectoryString, Name}; use platform::{ CertValidity, OtherName, Platform, PlatformError, SignerIdentifier, SubjectAltName, - MAX_CHUNK_SIZE, MAX_ISSUER_NAME_SIZE, MAX_KEY_IDENTIFIER_SIZE, MAX_OTHER_NAME_SIZE, - MAX_SN_SIZE, + MAX_CHUNK_SIZE, MAX_ISSUER_NAME_SIZE, MAX_KEY_IDENTIFIER_SIZE, }; -use zerocopy::IntoBytes; use crate::{subject_alt_name::AddSubjectAltNameCmd, MAX_CERT_CHAIN_SIZE}; diff --git a/runtime/src/drivers.rs b/runtime/src/drivers.rs index a893c8e59a..7f473cd1f8 100644 --- a/runtime/src/drivers.rs +++ b/runtime/src/drivers.rs @@ -12,10 +12,10 @@ Abstract: --*/ -#![cfg_attr(not(feature = "fip-self-test"), allow(unused))] +#![cfg_attr(not(feature = "fips_self_test"), allow(unused))] #[cfg(feature = "fips_self_test")] -pub use crate::fips::{fips_self_test_cmd, fips_self_test_cmd::SelfTestStatus}; +pub use crate::fips::fips_self_test_cmd::SelfTestStatus; use crate::recovery_flow::RecoveryFlow; use crate::{ dice, CptraDpeTypes, DisableAttestationCmd, DpeCrypto, DpePlatform, Mailbox, DPE_SUPPORT, @@ -24,34 +24,21 @@ use crate::{ }; use arrayvec::ArrayVec; -use caliptra_auth_man_types::AuthorizationManifest; -use caliptra_cfi_derive_git::{cfi_impl_fn, cfi_mod_fn}; +use caliptra_cfi_derive_git::cfi_impl_fn; use caliptra_cfi_lib_git::{cfi_assert, cfi_assert_eq, cfi_assert_eq_12_words, cfi_launder}; use caliptra_common::mailbox_api::AddSubjectAltNameReq; use caliptra_drivers::Dma; use caliptra_drivers::{ - cprint, cprintln, hand_off::DataStore, pcr_log::RT_FW_JOURNEY_PCR, - sha2_512_384::Sha2DigestOpTrait, Array4x12, CaliptraError, CaliptraResult, DataVault, Ecc384, - Ecc384PubKey, Hmac, KeyId, KeyVault, Lms, Mldsa87, PcrBank, PcrId, PersistentDataAccessor, Pic, - ResetReason, Sha1, Sha256, Sha256Alg, Sha2_512_384, Sha2_512_384Acc, SocIfc, Trng, + cprintln, hand_off::DataStore, pcr_log::RT_FW_JOURNEY_PCR, sha2_512_384::Sha2DigestOpTrait, + Array4x12, CaliptraError, CaliptraResult, Ecc384, Hmac, KeyId, KeyVault, Lms, Mldsa87, PcrBank, + PersistentDataAccessor, Pic, ResetReason, Sha1, Sha256, Sha256Alg, Sha2_512_384, + Sha2_512_384Acc, SocIfc, Trng, }; use caliptra_image_types::ImageManifest; use caliptra_registers::{ - csrng::CsrngReg, - dv::DvReg, - ecc::EccReg, - el2_pic_ctrl::El2PicCtrl, - entropy_src::EntropySrcReg, - hmac::HmacReg, - kv::KvReg, - mbox::{enums::MboxStatusE, MboxCsr}, - mldsa::MldsaReg, - pv::PvReg, - sha256::Sha256Reg, - sha512::Sha512Reg, - sha512_acc::Sha512AccCsr, - soc_ifc::SocIfcReg, - soc_ifc_trng::SocIfcTrngReg, + csrng::CsrngReg, ecc::EccReg, el2_pic_ctrl::El2PicCtrl, entropy_src::EntropySrcReg, + hmac::HmacReg, kv::KvReg, mbox::MboxCsr, mldsa::MldsaReg, pv::PvReg, sha256::Sha256Reg, + sha512::Sha512Reg, sha512_acc::Sha512AccCsr, soc_ifc::SocIfcReg, soc_ifc_trng::SocIfcTrngReg, }; use caliptra_x509::{NotAfter, NotBefore}; use dpe::context::{Context, ContextState, ContextType}; @@ -61,13 +48,12 @@ use dpe::MAX_HANDLES; use dpe::{ commands::{CommandExecution, DeriveContextCmd, DeriveContextFlags}, context::ContextHandle, - dpe_instance::{DpeEnv, DpeInstance, DpeTypes}, - support::Support, + dpe_instance::{DpeEnv, DpeInstance}, DPE_PROFILE, }; use core::cmp::Ordering::{Equal, Greater}; -use crypto::{AlgLen, Crypto, CryptoBuf, Hasher}; +use crypto::CryptoBuf; use zerocopy::IntoBytes; #[derive(PartialEq, Clone)] @@ -217,7 +203,7 @@ impl Drivers { .contexts .iter() .enumerate() - .find(|&(idx, context)| { + .find(|&(_idx, context)| { context.state != ContextState::Inactive && context.parent_idx == Context::ROOT_INDEX && context.context_type == ContextType::Normal @@ -231,13 +217,13 @@ impl Drivers { } /// Validate DPE and disable attestation if validation fails - fn validate_dpe_structure(mut drivers: &mut Drivers) -> CaliptraResult<()> { + fn validate_dpe_structure(drivers: &mut Drivers) -> CaliptraResult<()> { let dpe = &mut drivers.persistent_data.get_mut().dpe; let dpe_validator = DpeValidator { dpe }; let validation_result = dpe_validator.validate_dpe(); if let Err(e) = validation_result { // If SRAM Dpe Instance validation fails, disable attestation - let mut result = DisableAttestationCmd::execute(drivers); + let result = DisableAttestationCmd::execute(drivers); if cfi_launder(result.is_ok()) { cfi_assert!(result.is_ok()); } else { @@ -258,7 +244,7 @@ impl Drivers { } } } else { - let pl0_pauser = drivers.persistent_data.get().manifest1.header.pl0_pauser; + let _pl0_pauser = drivers.persistent_data.get().manifest1.header.pl0_pauser; // check that DPE used context limits are not exceeded let dpe_context_threshold_exceeded = drivers.is_dpe_context_threshold_exceeded(); if cfi_launder(dpe_context_threshold_exceeded.is_ok()) { @@ -304,7 +290,7 @@ impl Drivers { } /// Check that RT_FW_JOURNEY_PCR == DPE Root Context's TCI measurement - fn check_dpe_rt_journey_unchanged(mut drivers: &mut Drivers) -> CaliptraResult<()> { + fn check_dpe_rt_journey_unchanged(drivers: &mut Drivers) -> CaliptraResult<()> { let dpe = &drivers.persistent_data.get().dpe; let root_idx = Self::get_dpe_root_context_idx(dpe)?; let latest_tci = Array4x12::from(&dpe.contexts[root_idx].tci.tci_current.0); @@ -342,13 +328,13 @@ impl Drivers { } /// Check that inactive DPE contexts do not have context tags set - fn validate_context_tags(mut drivers: &mut Drivers) -> CaliptraResult<()> { + fn validate_context_tags(drivers: &mut Drivers) -> CaliptraResult<()> { let pdata = drivers.persistent_data.get(); let context_has_tag = &pdata.context_has_tag; let context_tags = &pdata.context_tags; let dpe = &pdata.dpe; - for i in (0..MAX_HANDLES) { + for i in 0..MAX_HANDLES { if dpe.contexts[i].state == ContextState::Inactive { if context_tags[i] != 0 { return Err(CaliptraError::RUNTIME_CONTEXT_TAGS_VALIDATION_FAILED); @@ -396,7 +382,7 @@ impl Drivers { let key_id_rt_cdi = Drivers::get_key_id_rt_cdi(drivers)?; let key_id_rt_priv_key = Drivers::get_key_id_rt_priv_key(drivers)?; let pdata = drivers.persistent_data.get_mut(); - let mut crypto = DpeCrypto::new( + let crypto = DpeCrypto::new( &mut drivers.sha2_512_384, &mut drivers.trng, &mut drivers.ecc384, @@ -601,7 +587,7 @@ impl Drivers { let locality = self.mbox.id(); // When the PL0_PAUSER_FLAG bit is not set there can be no PL0 PAUSER. - if (flags & PL0_PAUSER_FLAG == 0) { + if flags & PL0_PAUSER_FLAG == 0 { return PauserPrivileges::PL1; } diff --git a/runtime/src/fips.rs b/runtime/src/fips.rs index cf45378545..5b7583ff7f 100644 --- a/runtime/src/fips.rs +++ b/runtime/src/fips.rs @@ -13,7 +13,7 @@ Abstract: --*/ use caliptra_cfi_derive_git::{cfi_impl_fn, cfi_mod_fn}; use caliptra_common::cprintln; -use caliptra_common::mailbox_api::{MailboxResp, MailboxRespHeader}; +use caliptra_common::mailbox_api::MailboxResp; use caliptra_drivers::CaliptraError; use caliptra_drivers::CaliptraResult; use caliptra_drivers::Ecc384; @@ -22,7 +22,6 @@ use caliptra_drivers::KeyVault; use caliptra_drivers::Sha256; use caliptra_drivers::Sha2_512_384; use caliptra_drivers::Sha2_512_384Acc; -use caliptra_registers::mbox::enums::MboxStatusE; use zeroize::Zeroize; use crate::Drivers; @@ -91,7 +90,7 @@ pub mod fips_self_test_cmd { env.persistent_data.get().manifest1.size + env.persistent_data.get().manifest1.fmc.size + env.persistent_data.get().manifest1.runtime.size, - ); + )?; env.mbox .copy_bytes_to_mbox(env.persistent_data.get().manifest1.as_bytes())?; @@ -163,7 +162,7 @@ pub mod fips_self_test_cmd { // Hmac-512/384 Engine hmac: &mut env.hmac, - /// Cryptographically Secure Random Number Generator + // Cryptographically Secure Random Number Generator trng: &mut env.trng, // LMS Engine @@ -172,10 +171,10 @@ pub mod fips_self_test_cmd { // MLDSA87 Engine mldsa87: &mut env.mldsa87, - /// Ecc384 Engine + // Ecc384 Engine ecc384: &mut env.ecc384, - /// SHA Acc Lock State + // SHA Acc Lock State sha_acc_lock_state: ShaAccLockState::NotAcquired, }; diff --git a/runtime/src/get_idev_csr.rs b/runtime/src/get_idev_csr.rs index 5175816069..cd8fb9d796 100644 --- a/runtime/src/get_idev_csr.rs +++ b/runtime/src/get_idev_csr.rs @@ -3,12 +3,8 @@ use crate::Drivers; use caliptra_cfi_derive_git::cfi_impl_fn; -use caliptra_cfi_lib_git::cfi_launder; -use caliptra_common::{ - cprintln, - mailbox_api::{GetIdevCsrReq, GetIdevCsrResp, MailboxResp, MailboxRespHeader}, -}; +use caliptra_common::mailbox_api::{GetIdevCsrResp, MailboxResp}; use caliptra_error::{CaliptraError, CaliptraResult}; use caliptra_drivers::Ecc384IdevIdCsr; @@ -19,38 +15,34 @@ pub struct GetIdevCsrCmd; impl GetIdevCsrCmd { #[cfg_attr(not(feature = "no-cfi"), cfi_impl_fn)] #[inline(never)] - pub(crate) fn execute(drivers: &mut Drivers, cmd_args: &[u8]) -> CaliptraResult { - if let Ok(cmd) = GetIdevCsrReq::ref_from_bytes(cmd_args) { - let csr_persistent_mem = &drivers.persistent_data.get().idevid_csr_envelop.ecc_csr; - - match csr_persistent_mem.get_csr_len() { - Ecc384IdevIdCsr::UNPROVISIONED_CSR => { - Err(CaliptraError::RUNTIME_GET_IDEV_ID_UNPROVISIONED) - } - 0 => Err(CaliptraError::RUNTIME_GET_IDEV_ID_UNSUPPORTED_ROM), - len => { - let csr = csr_persistent_mem - .get() - .ok_or(CaliptraError::RUNTIME_GET_IDEV_ID_UNPROVISIONED)?; - - let mut resp = GetIdevCsrResp { - data_size: len, - ..Default::default() - }; - // NOTE: This code will not panic. - // - // csr is guranteed to be the same size as `len`, and therefore - // `resp.data_size` by the `IDevIDCsr::get` API. - // - // A valid `IDevIDCsr` cannot be larger than `MAX_CSR_SIZE`, which is the max - // size of the buffer in `GetIdevIdCsrResp` - resp.data[..resp.data_size as usize].copy_from_slice(csr); - - Ok(MailboxResp::GetIdevCsr(resp)) - } + pub(crate) fn execute(drivers: &mut Drivers, _cmd_args: &[u8]) -> CaliptraResult { + let csr_persistent_mem = &drivers.persistent_data.get().idevid_csr_envelop.ecc_csr; + + match csr_persistent_mem.get_csr_len() { + Ecc384IdevIdCsr::UNPROVISIONED_CSR => { + Err(CaliptraError::RUNTIME_GET_IDEV_ID_UNPROVISIONED) + } + 0 => Err(CaliptraError::RUNTIME_GET_IDEV_ID_UNSUPPORTED_ROM), + len => { + let csr = csr_persistent_mem + .get() + .ok_or(CaliptraError::RUNTIME_GET_IDEV_ID_UNPROVISIONED)?; + + let mut resp = GetIdevCsrResp { + data_size: len, + ..Default::default() + }; + // NOTE: This code will not panic. + // + // csr is guranteed to be the same size as `len`, and therefore + // `resp.data_size` by the `IDevIDCsr::get` API. + // + // A valid `IDevIDCsr` cannot be larger than `MAX_CSR_SIZE`, which is the max + // size of the buffer in `GetIdevCsrResp` + resp.data[..resp.data_size as usize].copy_from_slice(csr); + + Ok(MailboxResp::GetIdevCsr(resp)) } - } else { - Err(CaliptraError::RUNTIME_INSUFFICIENT_MEMORY) } } } diff --git a/runtime/src/hmac.rs b/runtime/src/hmac.rs index 706a1c44ea..2f45a7bd58 100644 --- a/runtime/src/hmac.rs +++ b/runtime/src/hmac.rs @@ -16,8 +16,8 @@ use caliptra_cfi_derive_git::{cfi_impl_fn, cfi_mod_fn}; use caliptra_cfi_lib_git::{cfi_assert, cfi_assert_eq, cfi_launder}; use caliptra_common::{crypto::Ecc384KeyPair, keyids::KEY_ID_TMP}; use caliptra_drivers::{ - hmac_kdf, sha2_512_384::Sha2DigestOpTrait, Array4x12, Ecc384PrivKeyOut, Ecc384PubKey, HmacData, - HmacKey, HmacMode, HmacTag, KeyId, KeyReadArgs, KeyUsage, KeyWriteArgs, + hmac_kdf, sha2_512_384::Sha2DigestOpTrait, Array4x12, HmacData, HmacKey, HmacMode, HmacTag, + KeyId, KeyReadArgs, KeyUsage, KeyWriteArgs, }; use caliptra_error::CaliptraResult; use zerocopy::IntoBytes; diff --git a/runtime/src/info.rs b/runtime/src/info.rs index 07f2fdf367..330eb01548 100644 --- a/runtime/src/info.rs +++ b/runtime/src/info.rs @@ -15,7 +15,6 @@ Abstract: use crate::{handoff::RtHandoff, Drivers}; use caliptra_common::mailbox_api::{FwInfoResp, GetIdevInfoResp, MailboxResp, MailboxRespHeader}; use caliptra_drivers::CaliptraResult; -use caliptra_image_types::RomInfo; pub struct FwInfoCmd; impl FwInfoCmd { diff --git a/runtime/src/invoke_dpe.rs b/runtime/src/invoke_dpe.rs index 7c78867e77..85902f67fb 100644 --- a/runtime/src/invoke_dpe.rs +++ b/runtime/src/invoke_dpe.rs @@ -12,18 +12,13 @@ Abstract: --*/ -use crate::{ - CptraDpeTypes, DpeCrypto, DpeEnv, DpePlatform, Drivers, PauserPrivileges, PL0_PAUSER_FLAG, -}; +use crate::{CptraDpeTypes, DpeCrypto, DpeEnv, DpePlatform, Drivers, PauserPrivileges}; use caliptra_cfi_derive_git::cfi_impl_fn; use caliptra_common::mailbox_api::{InvokeDpeReq, InvokeDpeResp, MailboxResp, MailboxRespHeader}; use caliptra_drivers::{CaliptraError, CaliptraResult}; -use crypto::{AlgLen, Crypto}; use dpe::{ - commands::{ - CertifyKeyCmd, Command, CommandExecution, DeriveContextCmd, DeriveContextFlags, InitCtxCmd, - }, - context::{Context, ContextState}, + commands::{CertifyKeyCmd, Command, CommandExecution, DeriveContextCmd, InitCtxCmd}, + context::ContextState, response::{Response, ResponseHdr}, DpeInstance, U8Bool, MAX_HANDLES, }; @@ -83,11 +78,11 @@ impl InvokeDpeCmd { } let command = Command::deserialize(&cmd.data[..cmd.data_size as usize]) .map_err(|_| CaliptraError::RUNTIME_DPE_COMMAND_DESERIALIZATION_FAILED)?; - let flags = pdata.manifest1.header.flags; + let _flags = pdata.manifest1.header.flags; - let mut dpe = &mut pdata.dpe; - let mut context_has_tag = &mut pdata.context_has_tag; - let mut context_tags = &mut pdata.context_tags; + let dpe = &mut pdata.dpe; + let context_has_tag = &mut pdata.context_has_tag; + let context_tags = &mut pdata.context_tags; let resp = match command { Command::GetProfile => Ok(Response::GetProfile( dpe.get_profile(&mut env.platform) diff --git a/runtime/src/lib.rs b/runtime/src/lib.rs index dad68e4c63..8f73e1c705 100644 --- a/runtime/src/lib.rs +++ b/runtime/src/lib.rs @@ -11,7 +11,7 @@ Abstract: File contains exports for the Runtime library and mailbox command handling logic. --*/ -#![cfg_attr(not(feature = "fip-self-test"), allow(unused))] +#![cfg_attr(not(feature = "fips_self_test"), allow(unused))] #![no_std] mod authorize_and_stash; mod capabilities; @@ -41,7 +41,6 @@ mod verify; pub mod mailbox; use authorize_and_stash::AuthorizeAndStashCmd; use caliptra_cfi_lib_git::{cfi_assert, cfi_assert_eq, cfi_assert_ne, cfi_launder, CfiCounter}; -use caliptra_registers::soc_ifc::SocIfcReg; pub use drivers::{Drivers, PauserPrivileges}; use mailbox::Mailbox; @@ -77,15 +76,12 @@ use tagging::{GetTaggedTciCmd, TagTciCmd}; use caliptra_common::cprintln; use caliptra_drivers::{CaliptraError, CaliptraResult, ResetReason}; -use caliptra_registers::el2_pic_ctrl::El2PicCtrl; -use caliptra_registers::{mbox::enums::MboxStatusE, soc_ifc}; +use caliptra_registers::mbox::enums::MboxStatusE; +pub use dpe::{context::ContextState, tci::TciMeasurement, DpeInstance, U8Bool, MAX_HANDLES}; use dpe::{ - commands::{CommandExecution, DeriveContextCmd, DeriveContextFlags}, dpe_instance::{DpeEnv, DpeTypes}, support::Support, - DPE_PROFILE, }; -pub use dpe::{context::ContextState, tci::TciMeasurement, DpeInstance, U8Bool, MAX_HANDLES}; use crate::{ dice::GetRtAliasCertCmd, @@ -266,7 +262,7 @@ pub fn handle_mailbox_commands(drivers: &mut Drivers) -> CaliptraResult<()> { let reset_reason = drivers.soc_ifc.reset_reason(); if reset_reason == ResetReason::WarmReset { cfi_assert_eq(drivers.soc_ifc.reset_reason(), ResetReason::WarmReset); - let mut result = DisableAttestationCmd::execute(drivers); + let result = DisableAttestationCmd::execute(drivers); if cfi_launder(result.is_ok()) { cfi_assert!(result.is_ok()); } else { @@ -345,5 +341,5 @@ pub fn handle_mailbox_commands(drivers: &mut Drivers) -> CaliptraResult<()> { cfi_assert!(!cmd_ready); } } - Ok(()) + // Ok(()) } diff --git a/runtime/src/mailbox.rs b/runtime/src/mailbox.rs index 3f4440bb47..19a47de439 100644 --- a/runtime/src/mailbox.rs +++ b/runtime/src/mailbox.rs @@ -148,7 +148,7 @@ impl Mailbox { /// Write a word-aligned `buf` to the mailbox pub fn write_response(&mut self, buf: &[u8]) -> CaliptraResult<()> { self.set_dlen(buf.len() as u32)?; - self.copy_bytes_to_mbox(buf); + self.copy_bytes_to_mbox(buf)?; Ok(()) } diff --git a/runtime/src/pcr.rs b/runtime/src/pcr.rs index 50692ca17d..56456073b9 100644 --- a/runtime/src/pcr.rs +++ b/runtime/src/pcr.rs @@ -18,7 +18,7 @@ use caliptra_common::mailbox_api::{ ExtendPcrReq, IncrementPcrResetCounterReq, MailboxResp, MailboxRespHeader, QuotePcrsReq, QuotePcrsResp, }; -use caliptra_drivers::{hand_off::DataStore, CaliptraError, CaliptraResult, PcrBank, PcrId}; +use caliptra_drivers::{CaliptraError, CaliptraResult, PcrId}; use zerocopy::FromBytes; pub struct IncrementPcrResetCounterCmd; diff --git a/runtime/src/recovery_flow.rs b/runtime/src/recovery_flow.rs index bbf29c54f5..12aeaf67b3 100644 --- a/runtime/src/recovery_flow.rs +++ b/runtime/src/recovery_flow.rs @@ -13,12 +13,9 @@ Abstract: --*/ use crate::Drivers; -use caliptra_auth_man_types::{ - AuthManifestImageMetadataCollection, AuthManifestPreamble, AuthorizationManifest, - AUTH_MANIFEST_PREAMBLE_SIZE, -}; -use caliptra_cfi_derive_git::{cfi_impl_fn, cfi_mod_fn}; -use caliptra_drivers::{AxiAddr, Dma, DmaReadTarget, DmaReadTransaction, DmaRecovery}; +use caliptra_auth_man_types::AuthorizationManifest; +use caliptra_cfi_derive_git::cfi_impl_fn; +use caliptra_drivers::DmaRecovery; use caliptra_kat::{CaliptraError, CaliptraResult}; use caliptra_registers::i3ccsr::RegisterBlock; use core::{ @@ -43,7 +40,9 @@ impl RecoveryFlow { // // download SoC manifest let _soc_size_bytes = dma_recovery.download_image_to_mbox(SOC_MANIFEST_INDEX)?; - let Ok((manifest, _)) = AuthorizationManifest::read_from_prefix(drivers.mbox.raw_mailbox_contents()) else { + let Ok((manifest, _)) = + AuthorizationManifest::read_from_prefix(drivers.mbox.raw_mailbox_contents()) + else { return Err(CaliptraError::IMAGE_VERIFIER_ERR_MANIFEST_SIZE_MISMATCH); }; // [TODO][CAP2]: authenticate SoC manifest using keys available through Caliptra Image diff --git a/runtime/src/set_auth_manifest.rs b/runtime/src/set_auth_manifest.rs index 9c094dacce..86b66b4573 100644 --- a/runtime/src/set_auth_manifest.rs +++ b/runtime/src/set_auth_manifest.rs @@ -15,33 +15,22 @@ Abstract: use core::cmp::min; use core::mem::size_of; -use crate::verify; -use crate::{dpe_crypto::DpeCrypto, CptraDpeTypes, DpePlatform, Drivers}; +use crate::Drivers; use caliptra_auth_man_types::{ AuthManifestFlags, AuthManifestImageMetadata, AuthManifestImageMetadataCollection, AuthManifestPreamble, AUTH_MANIFEST_IMAGE_METADATA_MAX_COUNT, AUTH_MANIFEST_MARKER, }; use caliptra_cfi_derive_git::cfi_impl_fn; use caliptra_cfi_lib_git::cfi_launder; -use caliptra_common::mailbox_api::{ - MailboxResp, MailboxRespHeader, SetAuthManifestReq, StashMeasurementReq, StashMeasurementResp, -}; +use caliptra_common::mailbox_api::{MailboxResp, SetAuthManifestReq}; use caliptra_drivers::{ - pcr_log::PCR_ID_STASH_MEASUREMENT, Array4x12, Array4xN, AuthManifestImageMetadataList, - CaliptraError, CaliptraResult, Ecc384, Ecc384PubKey, Ecc384Signature, HashValue, Lms, - PersistentData, Sha256, Sha2_512_384, SocIfc, + Array4x12, Array4xN, CaliptraError, CaliptraResult, Ecc384, Ecc384PubKey, Ecc384Signature, + HashValue, Lms, Sha256, Sha2_512_384, }; use caliptra_image_types::{ ImageDigest384, ImageEccPubKey, ImageEccSignature, ImageLmsPublicKey, ImageLmsSignature, ImagePreamble, SHA192_DIGEST_WORD_SIZE, SHA384_DIGEST_BYTE_SIZE, }; -use crypto::{AlgLen, Crypto}; -use dpe::{ - commands::{CommandExecution, DeriveContextCmd, DeriveContextFlags}, - context::ContextHandle, - dpe_instance::DpeEnv, - response::DpeErrorCode, -}; use memoffset::offset_of; use zerocopy::{FromBytes, IntoBytes}; use zeroize::Zeroize; @@ -103,7 +92,6 @@ impl SetAuthManifestCmd { sha2: &mut Sha2_512_384, ecc384: &mut Ecc384, sha256: &mut Sha256, - soc_ifc: &SocIfc, ) -> CaliptraResult<()> { let range = AuthManifestPreamble::vendor_signed_data_range(); let digest_vendor = Self::sha384_digest( @@ -164,7 +152,6 @@ impl SetAuthManifestCmd { sha2: &mut Sha2_512_384, ecc384: &mut Ecc384, sha256: &mut Sha256, - soc_ifc: &SocIfc, ) -> CaliptraResult<()> { let range = AuthManifestPreamble::owner_pub_keys_range(); let digest_owner = Self::sha384_digest( @@ -223,10 +210,8 @@ impl SetAuthManifestCmd { fn verify_vendor_image_metadata_col( auth_manifest_preamble: &AuthManifestPreamble, image_metadata_col_digest: &ImageDigest384, - sha2: &mut Sha2_512_384, ecc384: &mut Ecc384, sha256: &mut Sha256, - soc_ifc: &SocIfc, ) -> CaliptraResult<()> { let flags = AuthManifestFlags::from(auth_manifest_preamble.flags); if !flags.contains(AuthManifestFlags::VENDOR_SIGNATURE_REQUIRED) { @@ -284,10 +269,8 @@ impl SetAuthManifestCmd { fn verify_owner_image_metadata_col( auth_manifest_preamble: &AuthManifestPreamble, image_metadata_col_digest: &ImageDigest384, - sha2: &mut Sha2_512_384, ecc384: &mut Ecc384, sha256: &mut Sha256, - soc_ifc: &SocIfc, ) -> CaliptraResult<()> { // Verify the owner ECC signature. let verify_r = Self::ecc384_verify( @@ -346,7 +329,6 @@ impl SetAuthManifestCmd { sha2: &mut Sha2_512_384, ecc384: &mut Ecc384, sha256: &mut Sha256, - soc_ifc: &SocIfc, ) -> CaliptraResult<()> { if cmd_buf.len() < size_of::() { Err(CaliptraError::RUNTIME_AUTH_MANIFEST_IMAGE_METADATA_LIST_INVALID_SIZE)?; @@ -386,19 +368,15 @@ impl SetAuthManifestCmd { Self::verify_vendor_image_metadata_col( auth_manifest_preamble, &digest_metadata_col, - sha2, ecc384, sha256, - soc_ifc, )?; Self::verify_owner_image_metadata_col( auth_manifest_preamble, &digest_metadata_col, - sha2, ecc384, sha256, - soc_ifc, )?; // Sort the image metadata list by firmware ID in place. Also check for duplicate firmware IDs. let slice = @@ -497,7 +475,6 @@ impl SetAuthManifestCmd { &mut drivers.sha2_512_384, &mut drivers.ecc384, &mut drivers.sha256, - &drivers.soc_ifc, )?; // Verify the owner public keys. @@ -507,7 +484,6 @@ impl SetAuthManifestCmd { &mut drivers.sha2_512_384, &mut drivers.ecc384, &mut drivers.sha256, - &drivers.soc_ifc, )?; Self::process_image_metadata_col( @@ -519,14 +495,13 @@ impl SetAuthManifestCmd { &mut drivers.sha2_512_384, &mut drivers.ecc384, &mut drivers.sha256, - &drivers.soc_ifc, )?; Ok(MailboxResp::default()) } } -#[cfg(all(test))] +#[cfg(test)] mod tests { use super::*; diff --git a/runtime/src/stash_measurement.rs b/runtime/src/stash_measurement.rs index 2e6209e578..d324f4971e 100644 --- a/runtime/src/stash_measurement.rs +++ b/runtime/src/stash_measurement.rs @@ -18,7 +18,6 @@ use caliptra_common::mailbox_api::{ MailboxResp, MailboxRespHeader, StashMeasurementReq, StashMeasurementResp, }; use caliptra_drivers::{pcr_log::PCR_ID_STASH_MEASUREMENT, CaliptraError, CaliptraResult}; -use crypto::{AlgLen, Crypto}; use dpe::{ commands::{CommandExecution, DeriveContextCmd, DeriveContextFlags}, context::ContextHandle, @@ -53,7 +52,7 @@ impl StashMeasurementCmd { let key_id_rt_cdi = Drivers::get_key_id_rt_cdi(drivers)?; let key_id_rt_priv_key = Drivers::get_key_id_rt_priv_key(drivers)?; let pdata = drivers.persistent_data.get_mut(); - let mut crypto = DpeCrypto::new( + let crypto = DpeCrypto::new( &mut drivers.sha2_512_384, &mut drivers.trng, &mut drivers.ecc384, diff --git a/runtime/src/subject_alt_name.rs b/runtime/src/subject_alt_name.rs index daad1e127b..acf64c7e08 100644 --- a/runtime/src/subject_alt_name.rs +++ b/runtime/src/subject_alt_name.rs @@ -19,7 +19,7 @@ use caliptra_common::mailbox_api::{AddSubjectAltNameReq, MailboxResp}; use caliptra_error::{CaliptraError, CaliptraResult}; use zerocopy::IntoBytes; -use crate::{Drivers, MAX_CERT_CHAIN_SIZE, PL0_PAUSER_FLAG}; +use crate::Drivers; pub struct AddSubjectAltNameCmd; impl AddSubjectAltNameCmd { diff --git a/runtime/src/tagging.rs b/runtime/src/tagging.rs index 84447c8e98..c5f80d9c4c 100644 --- a/runtime/src/tagging.rs +++ b/runtime/src/tagging.rs @@ -12,21 +12,15 @@ Abstract: --*/ -use crate::CfiCounter; use caliptra_cfi_derive_git::cfi_impl_fn; use caliptra_common::mailbox_api::{ GetTaggedTciReq, GetTaggedTciResp, MailboxResp, MailboxRespHeader, TagTciReq, }; -use caliptra_drivers::cprintln; use caliptra_error::{CaliptraError, CaliptraResult}; -use dpe::{ - context::{ContextHandle, ContextState}, - dpe_instance::DpeEnv, - U8Bool, MAX_HANDLES, -}; +use dpe::{context::ContextHandle, U8Bool, MAX_HANDLES}; use zerocopy::FromBytes; -use crate::{dpe_crypto::DpeCrypto, CptraDpeTypes, DpePlatform, Drivers}; +use crate::Drivers; pub struct TagTciCmd; impl TagTciCmd { @@ -36,9 +30,9 @@ impl TagTciCmd { let cmd = TagTciReq::ref_from_bytes(cmd_args) .map_err(|_| CaliptraError::RUNTIME_INSUFFICIENT_MEMORY)?; let pdata_mut = drivers.persistent_data.get_mut(); - let mut dpe = &mut pdata_mut.dpe; - let mut context_has_tag = &mut pdata_mut.context_has_tag; - let mut context_tags = &mut pdata_mut.context_tags; + let dpe = &mut pdata_mut.dpe; + let context_has_tag = &mut pdata_mut.context_has_tag; + let context_tags = &mut pdata_mut.context_tags; // Make sure the tag isn't used by any other contexts. if (0..MAX_HANDLES).any(|i| { diff --git a/runtime/test-fw/Cargo.toml b/runtime/test-fw/Cargo.toml index 75acc16088..7c1d69f79d 100644 --- a/runtime/test-fw/Cargo.toml +++ b/runtime/test-fw/Cargo.toml @@ -6,6 +6,7 @@ version = "0.1.0" edition = "2021" [features] +std = [] runtime = ["caliptra-test-harness/runtime"] riscv = [ "caliptra-cpu/riscv", diff --git a/runtime/tests/runtime_integration_tests/test_certify_key_extended.rs b/runtime/tests/runtime_integration_tests/test_certify_key_extended.rs index 393e9f5a1c..1ab637bf50 100644 --- a/runtime/tests/runtime_integration_tests/test_certify_key_extended.rs +++ b/runtime/tests/runtime_integration_tests/test_certify_key_extended.rs @@ -111,7 +111,7 @@ fn test_dmtf_other_name_extension_present() { assert!(!ext.critical); let san = ext.value; assert_eq!(san.general_names.len(), 1); - let general_name = san.general_names.get(0).unwrap(); + let general_name = san.general_names.first().unwrap(); match general_name { GeneralName::OtherName(oid, other_name_value) => { assert_eq!(oid.as_bytes(), AddSubjectAltNameCmd::DMTF_OID); diff --git a/runtime/tests/runtime_integration_tests/test_certs.rs b/runtime/tests/runtime_integration_tests/test_certs.rs index 623bd87044..699482e7aa 100644 --- a/runtime/tests/runtime_integration_tests/test_certs.rs +++ b/runtime/tests/runtime_integration_tests/test_certs.rs @@ -489,8 +489,8 @@ pub fn test_all_measurement_apis() { DpeResult::Success, ); let Some(Response::DeriveContext(_derive_ctx_resp)) = resp else { - panic!("Wrong response type!"); - }; + panic!("Wrong response type!"); + }; // Get DPE cert let dpe_cert_resp = get_dpe_leaf_cert(&mut hw); diff --git a/runtime/tests/runtime_integration_tests/test_pauser_privilege_levels.rs b/runtime/tests/runtime_integration_tests/test_pauser_privilege_levels.rs index f874275cad..895fefd5ae 100644 --- a/runtime/tests/runtime_integration_tests/test_pauser_privilege_levels.rs +++ b/runtime/tests/runtime_integration_tests/test_pauser_privilege_levels.rs @@ -132,8 +132,8 @@ fn test_pl1_derive_context_dpe_context_thresholds() { DpeResult::Success, ); let Some(Response::InitCtx(init_ctx_resp)) = resp else { - panic!("Wrong response type!"); - }; + panic!("Wrong response type!"); + }; let mut handle = init_ctx_resp.handle; // Call DeriveContext with PL1 enough times to breach the threshold on the last iteration. @@ -170,8 +170,8 @@ fn test_pl1_derive_context_dpe_context_thresholds() { DpeResult::Success, ); let Some(Response::DeriveContext(derive_context_resp)) = resp else { - panic!("Wrong response type!"); - }; + panic!("Wrong response type!"); + }; handle = derive_context_resp.handle; } } @@ -258,8 +258,8 @@ fn test_pl1_init_ctx_dpe_context_thresholds() { DpeResult::Success, ); let Some(Response::InitCtx(_)) = resp else { - panic!("Wrong response type!"); - }; + panic!("Wrong response type!"); + }; } } } @@ -440,8 +440,8 @@ fn test_derive_context_cannot_be_called_from_pl1_if_changes_locality_to_pl0() { DpeResult::Success, ); let Some(Response::InitCtx(init_ctx_resp)) = resp else { - panic!("Wrong response type!"); - }; + panic!("Wrong response type!"); + }; let derive_context_cmd = DeriveContextCmd { handle: init_ctx_resp.handle, diff --git a/runtime/tests/runtime_integration_tests/test_pcr.rs b/runtime/tests/runtime_integration_tests/test_pcr.rs index 47a9763a96..c80eac6f92 100644 --- a/runtime/tests/runtime_integration_tests/test_pcr.rs +++ b/runtime/tests/runtime_integration_tests/test_pcr.rs @@ -100,9 +100,9 @@ pub fn get_model_pcrs(model: &mut DefaultHwModel) -> [[u8; 48]; 32] { .unwrap() .unwrap(); - return QuotePcrsResp::read_from_bytes(resp.as_slice()) + QuotePcrsResp::read_from_bytes(resp.as_slice()) .unwrap() - .pcrs; + .pcrs } #[test] diff --git a/rust-toolchain.toml b/rust-toolchain.toml index 0d9ca873ec..c6964b41f0 100644 --- a/rust-toolchain.toml +++ b/rust-toolchain.toml @@ -1,7 +1,7 @@ # Licensed under the Apache-2.0 license [toolchain] -channel = "1.70" +channel = "1.84" targets = ["riscv32imc-unknown-none-elf"] profile = "minimal" components = ["rustfmt", "clippy"] diff --git a/sw-emulator/app/src/main.rs b/sw-emulator/app/src/main.rs index 36d32df6c5..bd9c8d4354 100644 --- a/sw-emulator/app/src/main.rs +++ b/sw-emulator/app/src/main.rs @@ -453,7 +453,7 @@ fn main() -> io::Result<()> { Ok(()) } -fn change_dword_endianess(data: &mut Vec) { +fn change_dword_endianess(data: &mut [u8]) { for idx in (0..data.len()).step_by(4) { data.swap(idx, idx + 3); data.swap(idx + 1, idx + 2); diff --git a/sw-emulator/compliance-test/src/main.rs b/sw-emulator/compliance-test/src/main.rs index 1c84eab0a1..8272d64b54 100644 --- a/sw-emulator/compliance-test/src/main.rs +++ b/sw-emulator/compliance-test/src/main.rs @@ -171,7 +171,7 @@ fn main() -> Result<(), Box> { } } if !is_test_complete(&mut cpu.bus) { - return Err(std::io::Error::new( + Err(std::io::Error::new( ErrorKind::Other, "test did not complete", ))?; diff --git a/sw-emulator/lib/bus/src/testing/log.rs b/sw-emulator/lib/bus/src/testing/log.rs index 9d8026ef11..2e24f09c46 100644 --- a/sw-emulator/lib/bus/src/testing/log.rs +++ b/sw-emulator/lib/bus/src/testing/log.rs @@ -77,7 +77,7 @@ impl Default for Log { struct LogWriter<'a> { log: &'a RefCell, } -impl<'a> Write for LogWriter<'a> { +impl Write for LogWriter<'_> { fn write_str(&mut self, s: &str) -> std::fmt::Result { Write::write_str(&mut *self.log.borrow_mut(), s) } diff --git a/sw-emulator/lib/cpu/src/cpu.rs b/sw-emulator/lib/cpu/src/cpu.rs index b4aae462c2..87ea129edf 100644 --- a/sw-emulator/lib/cpu/src/cpu.rs +++ b/sw-emulator/lib/cpu/src/cpu.rs @@ -23,6 +23,7 @@ use caliptra_emu_types::{RvAddr, RvData, RvException, RvSize}; pub type InstrTracer<'a> = dyn FnMut(u32, RvInstr) + 'a; /// Describes a Caliptra stack memory region +#[allow(dead_code)] // Stack start never checked pub struct StackRange(u32, u32); impl StackRange { /// **Note:** `stack_start` MUST be greater than `stack_end`. Caliptra's stack grows @@ -746,7 +747,9 @@ impl Cpu { if self.write_csr_machine(Csr::MEIHAP, meihap.0).is_err() { return StepAction::Fatal; } - let Ok(next_pc) = self.read_bus(RvSize::Word, next_pc_ptr) else { return StepAction::Fatal; }; + let Ok(next_pc) = self.read_bus(RvSize::Word, next_pc_ptr) else { + return StepAction::Fatal; + }; const MACHINE_EXTERNAL_INT: u32 = 0x8000_000B; let ret = self.handle_trap(self.read_pc(), MACHINE_EXTERNAL_INT, 0, next_pc); match ret { @@ -1814,7 +1817,7 @@ mod tests { #[test] fn test_coverage() { // represent program as an array of 16-bit and 32-bit instructions - let instructions = vec![ + let instructions = [ Instr::Compressed(0x1234), Instr::Compressed(0xABCD), Instr::General(0xDEADBEEF), diff --git a/sw-emulator/lib/cpu/src/csr_file.rs b/sw-emulator/lib/cpu/src/csr_file.rs index bc4ee59c8f..284c60587a 100644 --- a/sw-emulator/lib/cpu/src/csr_file.rs +++ b/sw-emulator/lib/cpu/src/csr_file.rs @@ -87,7 +87,6 @@ impl Csr { /// /// * `val` - Reset value /// * `mask` - Write Mask - ///' pub fn new(default_val: RvData, mask: RvData) -> Self { Self { val: default_val, diff --git a/sw-emulator/lib/cpu/src/instr/mod.rs b/sw-emulator/lib/cpu/src/instr/mod.rs index 08aee4a1a1..6962ba5cfe 100644 --- a/sw-emulator/lib/cpu/src/instr/mod.rs +++ b/sw-emulator/lib/cpu/src/instr/mod.rs @@ -93,7 +93,7 @@ impl Cpu { fn fetch(&mut self) -> Result { let instr = self.read_instr(RvSize::HalfWord, self.read_pc())?; match instr & 0b11 { - 0 | 1 | 2 => Ok(Instr::Compressed(instr as u16)), + 0..=2 => Ok(Instr::Compressed(instr as u16)), _ => Ok(Instr::General( self.read_instr(RvSize::Word, self.read_pc())?, )), diff --git a/sw-emulator/lib/derive/src/util/token_iter.rs b/sw-emulator/lib/derive/src/util/token_iter.rs index 9f806f43e9..462b33273f 100644 --- a/sw-emulator/lib/derive/src/util/token_iter.rs +++ b/sw-emulator/lib/derive/src/util/token_iter.rs @@ -29,7 +29,7 @@ pub struct FieldWithAttributes { } pub struct DisplayToken<'a>(pub &'a Option); -impl<'a> Display for DisplayToken<'a> { +impl Display for DisplayToken<'_> { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { match self.0 { Some(TokenTree::Ident(i)) => write!(f, "identifier {}", i), diff --git a/sw-emulator/lib/periph/src/csrng/health_test.rs b/sw-emulator/lib/periph/src/csrng/health_test.rs index 241f0c3358..c13be50814 100644 --- a/sw-emulator/lib/periph/src/csrng/health_test.rs +++ b/sw-emulator/lib/periph/src/csrng/health_test.rs @@ -110,7 +110,7 @@ impl RepetitionCountTester { _ => unreachable!("bit {i} of nibble={nibble} should only be 0 or 1"), }; - let is_repeat = self.prev_nibble[i].map_or(false, |prev_bit| prev_bit == bit); + let is_repeat = self.prev_nibble[i] == Some(bit); if is_repeat { self.repetition_count[i] += 1; diff --git a/sw-emulator/lib/periph/src/hash_sha512.rs b/sw-emulator/lib/periph/src/hash_sha512.rs index a1a25a12f7..d2a2eeaf9f 100644 --- a/sw-emulator/lib/periph/src/hash_sha512.rs +++ b/sw-emulator/lib/periph/src/hash_sha512.rs @@ -847,7 +847,7 @@ mod tests { let mut hash_write_fail_test = false; let mut block_disallowed_for_sha = false; - for (_idx, action) in keyvault_actions.iter().enumerate() { + for action in keyvault_actions.iter() { match action { KeyVaultAction::BlockFromVault(id) => { block_via_kv = true; diff --git a/sw-emulator/lib/periph/src/hmac.rs b/sw-emulator/lib/periph/src/hmac.rs index a0aaa5a1ef..aafc970c5c 100644 --- a/sw-emulator/lib/periph/src/hmac.rs +++ b/sw-emulator/lib/periph/src/hmac.rs @@ -832,7 +832,7 @@ mod tests { let mut tag_write_fail_test = false; let mut block_disallowed_for_hmac = false; - for (_idx, action) in keyvault_actions.iter().enumerate() { + for action in keyvault_actions.iter() { match action { KeyVaultAction::KeyFromVault(id) => { key_via_kv = true; diff --git a/sw-emulator/lib/periph/src/mailbox.rs b/sw-emulator/lib/periph/src/mailbox.rs index 49d1ecaf6f..3de8f155e2 100644 --- a/sw-emulator/lib/periph/src/mailbox.rs +++ b/sw-emulator/lib/periph/src/mailbox.rs @@ -129,7 +129,6 @@ pub struct MailboxInternal { } /// Mailbox Peripheral - impl MailboxInternal { pub fn new(clock: &Clock, ram: MailboxRam) -> Self { Self { @@ -250,7 +249,7 @@ pub struct MailboxRegs { /// Trigger interrupt irq: bool, - /// + /// Timer timer: Timer, } @@ -490,8 +489,6 @@ pub struct Context { pub locked: u32, /// Who acquired the lock. pub user: MailboxRequester, - /// Execute flag - pub exec: bool, /// number of data elements pub dlen: u32, /// Fifo storage @@ -511,7 +508,6 @@ impl Context { Self { locked: 0, user: MailboxRequester::Caliptra, - exec: false, dlen: 0, status: LocalRegisterCopy::new(0), fifo: Fifo::new(ram), diff --git a/sw-emulator/lib/periph/src/root_bus.rs b/sw-emulator/lib/periph/src/root_bus.rs index 536747eaea..01893d57d0 100644 --- a/sw-emulator/lib/periph/src/root_bus.rs +++ b/sw-emulator/lib/periph/src/root_bus.rs @@ -67,7 +67,7 @@ pub struct ReadyForFwCbArgs<'a> { pub mailbox: &'a mut MailboxInternal, pub(crate) sched_fn: Box>, } -impl<'a> ReadyForFwCbArgs<'a> { +impl ReadyForFwCbArgs<'_> { pub fn schedule_later( self, ticks_from_now: u64, diff --git a/sw-emulator/lib/periph/src/sha512_acc.rs b/sw-emulator/lib/periph/src/sha512_acc.rs index 427e3ee152..5b31c16b22 100644 --- a/sw-emulator/lib/periph/src/sha512_acc.rs +++ b/sw-emulator/lib/periph/src/sha512_acc.rs @@ -409,7 +409,7 @@ impl Sha512AcceleratorRegs { /// * `BusError` - Exception with cause `BusError::StoreAccessFault` or `BusError::StoreAddrMisaligned` fn compute_mbox_hash(&mut self) { let data_len = self.dlen.reg.get() as usize; - let totaldwords = (data_len + (RvSize::Word as usize - 1)) / (RvSize::Word as usize); + let totaldwords = data_len.div_ceil(RvSize::Word as usize); let totalblocks = ((data_len + 16) + SHA512_BLOCK_SIZE) / SHA512_BLOCK_SIZE; let totalbytes = totalblocks * SHA512_BLOCK_SIZE; let mut block_arr: Vec = vec![0; totalbytes]; diff --git a/systemrdl/src/component_meta.rs b/systemrdl/src/component_meta.rs index 91d4aab0c2..2a9745d01a 100644 --- a/systemrdl/src/component_meta.rs +++ b/systemrdl/src/component_meta.rs @@ -9,7 +9,6 @@ use crate::{RdlError, Result}; pub struct PropertyMeta { pub name: &'static str, pub ty: PropertyType, - pub is_dynamic: bool, } pub struct ComponentMeta { @@ -25,13 +24,13 @@ static SIGNAL: ComponentMeta = ComponentMeta { can_instantiate: true, deep_subelement_types: &[], properties: &[ - PropertyMeta{name: "signalwidth", ty: PropertyType::U64, is_dynamic: false }, - PropertyMeta{name: "sync", ty: PropertyType::Boolean, is_dynamic: true }, - PropertyMeta{name: "async", ty: PropertyType::Boolean, is_dynamic: true }, - PropertyMeta{name: "cpuif_reset", ty: PropertyType::Boolean, is_dynamic: true }, - PropertyMeta{name: "field_reset", ty: PropertyType::Boolean, is_dynamic: true }, - PropertyMeta{name: "activelow", ty: PropertyType::Boolean, is_dynamic: true }, - PropertyMeta{name: "activehigh", ty: PropertyType::Boolean, is_dynamic: true }, + PropertyMeta{name: "signalwidth", ty: PropertyType::U64}, + PropertyMeta{name: "sync", ty: PropertyType::Boolean}, + PropertyMeta{name: "async", ty: PropertyType::Boolean}, + PropertyMeta{name: "cpuif_reset", ty: PropertyType::Boolean}, + PropertyMeta{name: "field_reset", ty: PropertyType::Boolean}, + PropertyMeta{name: "activelow", ty: PropertyType::Boolean}, + PropertyMeta{name: "activehigh", ty: PropertyType::Boolean}, ], }; @@ -42,73 +41,73 @@ static FIELD: ComponentMeta = ComponentMeta { deep_subelement_types: &[], properties: &[ // Structural properties - PropertyMeta{name: "donttest", ty: PropertyType::Bits, is_dynamic: true}, - PropertyMeta{name: "dontcompare", ty: PropertyType::Bits, is_dynamic: true}, + PropertyMeta{name: "donttest", ty: PropertyType::Bits}, + PropertyMeta{name: "dontcompare", ty: PropertyType::Bits}, // Field access properties - PropertyMeta{name: "hw", ty: PropertyType::AccessType, is_dynamic: false}, - PropertyMeta{name: "sw", ty: PropertyType::AccessType, is_dynamic: true}, + PropertyMeta{name: "hw", ty: PropertyType::AccessType}, + PropertyMeta{name: "sw", ty: PropertyType::AccessType}, // Hardware signal properties - PropertyMeta{name: "next", ty: PropertyType::Reference, is_dynamic: true}, - PropertyMeta{name: "reset", ty: PropertyType::BitOrReference, is_dynamic: true}, - PropertyMeta{name: "resetsignal", ty: PropertyType::Reference, is_dynamic: true}, + PropertyMeta{name: "next", ty: PropertyType::Reference}, + PropertyMeta{name: "reset", ty: PropertyType::BitOrReference}, + PropertyMeta{name: "resetsignal", ty: PropertyType::Reference}, // Software access properties - PropertyMeta{name: "rclr", ty: PropertyType::Boolean, is_dynamic: true}, - PropertyMeta{name: "rset", ty: PropertyType::Boolean, is_dynamic: true}, - PropertyMeta{name: "onread", ty: PropertyType::OnReadType, is_dynamic: true}, - PropertyMeta{name: "woset", ty: PropertyType::Boolean, is_dynamic: true}, - PropertyMeta{name: "woclr", ty: PropertyType::Boolean, is_dynamic: true}, - PropertyMeta{name: "onwrite", ty: PropertyType::OnWriteType, is_dynamic: true}, - PropertyMeta{name: "swwe", ty: PropertyType::BooleanOrReference, is_dynamic: true}, - PropertyMeta{name: "swwel", ty: PropertyType::BooleanOrReference, is_dynamic: true}, - PropertyMeta{name: "swmod", ty: PropertyType::Boolean, is_dynamic: true}, - PropertyMeta{name: "swacc", ty: PropertyType::Boolean, is_dynamic: true}, - PropertyMeta{name: "singlepulse", ty: PropertyType::Boolean, is_dynamic: true}, + PropertyMeta{name: "rclr", ty: PropertyType::Boolean}, + PropertyMeta{name: "rset", ty: PropertyType::Boolean}, + PropertyMeta{name: "onread", ty: PropertyType::OnReadType}, + PropertyMeta{name: "woset", ty: PropertyType::Boolean}, + PropertyMeta{name: "woclr", ty: PropertyType::Boolean}, + PropertyMeta{name: "onwrite", ty: PropertyType::OnWriteType}, + PropertyMeta{name: "swwe", ty: PropertyType::BooleanOrReference}, + PropertyMeta{name: "swwel", ty: PropertyType::BooleanOrReference}, + PropertyMeta{name: "swmod", ty: PropertyType::Boolean}, + PropertyMeta{name: "swacc", ty: PropertyType::Boolean}, + PropertyMeta{name: "singlepulse", ty: PropertyType::Boolean}, // Hardware access properties - PropertyMeta{name: "we", ty: PropertyType::BooleanOrReference, is_dynamic: true}, - PropertyMeta{name: "wel", ty: PropertyType::BooleanOrReference, is_dynamic: true}, - PropertyMeta{name: "anded", ty: PropertyType::Boolean, is_dynamic: true}, - PropertyMeta{name: "ored", ty: PropertyType::Boolean, is_dynamic: true}, - PropertyMeta{name: "xored", ty: PropertyType::Boolean, is_dynamic: true}, - PropertyMeta{name: "fieldwidth", ty: PropertyType::U64, is_dynamic: true}, - PropertyMeta{name: "hwclr", ty: PropertyType::BooleanOrReference, is_dynamic: true}, - PropertyMeta{name: "hwset", ty: PropertyType::BooleanOrReference, is_dynamic: true}, - PropertyMeta{name: "hwenable", ty: PropertyType::Reference, is_dynamic: true}, - PropertyMeta{name: "hwmask", ty: PropertyType::Reference, is_dynamic: true}, + PropertyMeta{name: "we", ty: PropertyType::BooleanOrReference}, + PropertyMeta{name: "wel", ty: PropertyType::BooleanOrReference}, + PropertyMeta{name: "anded", ty: PropertyType::Boolean}, + PropertyMeta{name: "ored", ty: PropertyType::Boolean}, + PropertyMeta{name: "xored", ty: PropertyType::Boolean}, + PropertyMeta{name: "fieldwidth", ty: PropertyType::U64}, + PropertyMeta{name: "hwclr", ty: PropertyType::BooleanOrReference}, + PropertyMeta{name: "hwset", ty: PropertyType::BooleanOrReference}, + PropertyMeta{name: "hwenable", ty: PropertyType::Reference}, + PropertyMeta{name: "hwmask", ty: PropertyType::Reference}, // Counter field properties - PropertyMeta{name: "counter", ty: PropertyType::Boolean, is_dynamic: true}, - PropertyMeta{name: "threshold", ty: PropertyType::BitOrReference, is_dynamic: true}, // alias incrthreshold - PropertyMeta{name: "saturate", ty: PropertyType::BitOrReference, is_dynamic: true}, // alias incrsaturate - PropertyMeta{name: "incrthreshold", ty: PropertyType::BitOrReference, is_dynamic: true}, - PropertyMeta{name: "incrsaturate", ty: PropertyType::BitOrReference, is_dynamic: true}, - PropertyMeta{name: "overflow", ty: PropertyType::Boolean, is_dynamic: true}, - PropertyMeta{name: "underflow", ty: PropertyType::Boolean, is_dynamic: true}, - PropertyMeta{name: "incrvalue", ty: PropertyType::BitOrReference, is_dynamic: true}, - PropertyMeta{name: "incr", ty: PropertyType::Reference, is_dynamic: true}, - PropertyMeta{name: "incrwidth", ty: PropertyType::U64, is_dynamic: true}, - PropertyMeta{name: "decrvalue", ty: PropertyType::BitOrReference, is_dynamic: true}, - PropertyMeta{name: "decr", ty: PropertyType::Reference, is_dynamic: true}, - PropertyMeta{name: "decrwidth", ty: PropertyType::U64, is_dynamic: true}, - PropertyMeta{name: "decrsaturate", ty: PropertyType::BitOrReference, is_dynamic: true}, - PropertyMeta{name: "decrthreshold", ty: PropertyType::BitOrReference, is_dynamic: true}, + PropertyMeta{name: "counter", ty: PropertyType::Boolean}, + PropertyMeta{name: "threshold", ty: PropertyType::BitOrReference}, // alias incrthreshold + PropertyMeta{name: "saturate", ty: PropertyType::BitOrReference}, // alias incrsaturate + PropertyMeta{name: "incrthreshold", ty: PropertyType::BitOrReference}, + PropertyMeta{name: "incrsaturate", ty: PropertyType::BitOrReference}, + PropertyMeta{name: "overflow", ty: PropertyType::Boolean}, + PropertyMeta{name: "underflow", ty: PropertyType::Boolean}, + PropertyMeta{name: "incrvalue", ty: PropertyType::BitOrReference}, + PropertyMeta{name: "incr", ty: PropertyType::Reference}, + PropertyMeta{name: "incrwidth", ty: PropertyType::U64}, + PropertyMeta{name: "decrvalue", ty: PropertyType::BitOrReference}, + PropertyMeta{name: "decr", ty: PropertyType::Reference}, + PropertyMeta{name: "decrwidth", ty: PropertyType::U64}, + PropertyMeta{name: "decrsaturate", ty: PropertyType::BitOrReference}, + PropertyMeta{name: "decrthreshold", ty: PropertyType::BitOrReference}, // Field access interrupt properties - PropertyMeta{name: "intr" , ty: PropertyType::FieldInterrupt, is_dynamic: true}, // also - PropertyMeta{name: "enable", ty: PropertyType::Reference, is_dynamic: true}, - PropertyMeta{name: "mask", ty: PropertyType::Reference, is_dynamic: true}, - PropertyMeta{name: "haltenable", ty: PropertyType::Reference, is_dynamic: true}, - PropertyMeta{name: "haltmask", ty: PropertyType::Reference, is_dynamic: true}, - PropertyMeta{name: "sticky", ty: PropertyType::Boolean, is_dynamic: true}, - PropertyMeta{name: "stickybit", ty: PropertyType::Boolean, is_dynamic: true}, + PropertyMeta{name: "intr" , ty: PropertyType::FieldInterrupt}, // also + PropertyMeta{name: "enable", ty: PropertyType::Reference}, + PropertyMeta{name: "mask", ty: PropertyType::Reference}, + PropertyMeta{name: "haltenable", ty: PropertyType::Reference}, + PropertyMeta{name: "haltmask", ty: PropertyType::Reference}, + PropertyMeta{name: "sticky", ty: PropertyType::Boolean}, + PropertyMeta{name: "stickybit", ty: PropertyType::Boolean}, // Miscellaneous field properties - PropertyMeta{name: "encode", ty: PropertyType::EnumReference, is_dynamic: true}, - PropertyMeta{name: "precedence", ty: PropertyType::PrecedenceType, is_dynamic: true}, - PropertyMeta{name: "paritycheck", ty: PropertyType::Boolean, is_dynamic: true}, + PropertyMeta{name: "encode", ty: PropertyType::EnumReference}, + PropertyMeta{name: "precedence", ty: PropertyType::PrecedenceType}, + PropertyMeta{name: "paritycheck", ty: PropertyType::Boolean}, ], }; @@ -118,10 +117,10 @@ static REG: ComponentMeta = ComponentMeta { can_instantiate: true, deep_subelement_types: &[&FIELD], properties: &[ - PropertyMeta{name: "regwidth", ty: PropertyType::U64, is_dynamic: true}, - PropertyMeta{name: "accesswidth", ty: PropertyType::U64, is_dynamic: true}, - PropertyMeta{name: "errextbus", ty: PropertyType::Boolean, is_dynamic: true}, - PropertyMeta{name: "shared", ty: PropertyType::Boolean, is_dynamic: true}, + PropertyMeta{name: "regwidth", ty: PropertyType::U64}, + PropertyMeta{name: "accesswidth", ty: PropertyType::U64}, + PropertyMeta{name: "errextbus", ty: PropertyType::Boolean}, + PropertyMeta{name: "shared", ty: PropertyType::Boolean}, ], }; @@ -131,9 +130,9 @@ static MEM: ComponentMeta = ComponentMeta { can_instantiate: true, deep_subelement_types: &[], properties: &[ - PropertyMeta{name: "mementries", ty: PropertyType::U64, is_dynamic: true}, - PropertyMeta{name: "memwidth", ty: PropertyType::U64, is_dynamic: true}, - PropertyMeta{name: "sw", ty: PropertyType::AccessType, is_dynamic: true}, + PropertyMeta{name: "mementries", ty: PropertyType::U64}, + PropertyMeta{name: "memwidth", ty: PropertyType::U64}, + PropertyMeta{name: "sw", ty: PropertyType::AccessType}, ], }; @@ -143,9 +142,9 @@ static REGFILE: ComponentMeta = ComponentMeta { can_instantiate: true, deep_subelement_types: &[®, ®FILE, &FIELD, &SIGNAL], properties: &[ - PropertyMeta{name: "alignment", ty: PropertyType::U64, is_dynamic: true}, - PropertyMeta{name: "sharedextbus", ty: PropertyType::Boolean, is_dynamic: true}, - PropertyMeta{name: "errextbus", ty: PropertyType::Boolean, is_dynamic: true}, + PropertyMeta{name: "alignment", ty: PropertyType::U64}, + PropertyMeta{name: "sharedextbus", ty: PropertyType::Boolean}, + PropertyMeta{name: "errextbus", ty: PropertyType::Boolean}, ], }; @@ -155,16 +154,16 @@ static ADDRMAP: ComponentMeta = ComponentMeta { can_instantiate: true, deep_subelement_types: &[®, ®FILE, &FIELD, &SIGNAL], properties: &[ - PropertyMeta{name: "alignment", ty: PropertyType::U64, is_dynamic: false}, - PropertyMeta{name: "sharedextbus", ty: PropertyType::Boolean, is_dynamic: false}, - PropertyMeta{name: "errextbus", ty: PropertyType::Boolean, is_dynamic: false}, - PropertyMeta{name: "bigendian", ty: PropertyType::Boolean, is_dynamic: true}, - PropertyMeta{name: "littleendian", ty: PropertyType::Boolean, is_dynamic: true}, - PropertyMeta{name: "addressing", ty: PropertyType::AddressingType, is_dynamic: false}, - PropertyMeta{name: "rsvdset", ty: PropertyType::Boolean, is_dynamic: false}, - PropertyMeta{name: "rsvdsetX", ty: PropertyType::Boolean, is_dynamic: false}, - PropertyMeta{name: "msb0", ty: PropertyType::Boolean, is_dynamic: false}, - PropertyMeta{name: "lsb0", ty: PropertyType::Boolean, is_dynamic: false}, + PropertyMeta{name: "alignment", ty: PropertyType::U64}, + PropertyMeta{name: "sharedextbus", ty: PropertyType::Boolean}, + PropertyMeta{name: "errextbus", ty: PropertyType::Boolean}, + PropertyMeta{name: "bigendian", ty: PropertyType::Boolean}, + PropertyMeta{name: "littleendian", ty: PropertyType::Boolean}, + PropertyMeta{name: "addressing", ty: PropertyType::AddressingType}, + PropertyMeta{name: "rsvdset", ty: PropertyType::Boolean}, + PropertyMeta{name: "rsvdsetX", ty: PropertyType::Boolean}, + PropertyMeta{name: "msb0", ty: PropertyType::Boolean}, + PropertyMeta{name: "lsb0", ty: PropertyType::Boolean}, ], }; @@ -220,12 +219,10 @@ static GENERAL_PROPERTIES: [PropertyMeta; 2] = [ PropertyMeta { name: "name", ty: PropertyType::String, - is_dynamic: true, }, PropertyMeta { name: "desc", ty: PropertyType::String, - is_dynamic: true, }, ]; diff --git a/systemrdl/src/scope.rs b/systemrdl/src/scope.rs index 3bdb867884..22f07060c2 100644 --- a/systemrdl/src/scope.rs +++ b/systemrdl/src/scope.rs @@ -528,7 +528,7 @@ impl<'a> ParentScope<'a> { }, }) } - pub fn type_iter(&'a self) -> impl Iterator)> { + pub fn type_iter(&'a self) -> impl Iterator)> { self.scope.types.iter().map(|(name, scope)| { ( name.as_str(), @@ -591,7 +591,7 @@ pub fn lookup_parameter<'a, 'b>( } return lookup_parameter(p.parent, name); } - return Err(RdlError::UnknownIdentifier(name)); + Err(RdlError::UnknownIdentifier(name)) } pub fn lookup_parameter_of_type<'a, 'b>( @@ -679,13 +679,12 @@ pub struct Instance { } impl Instance { pub fn element_size(&self) -> u64 { - let width = if let Ok(Some(w)) = self.scope.property_val_opt::("regwidth") { + if let Ok(Some(w)) = self.scope.property_val_opt::("regwidth") { w / 8 } else { // According to section 10.1 of the SystemRDL 2.0 spec, the default regwidth is 32-bits 4 - }; - width + } } pub fn total_size(&self) -> Result<'static, u64> { let stride = if let Some(stride) = self.stride { @@ -776,6 +775,74 @@ impl Instance { } } +fn is_intr_modifier(token: &Token) -> bool { + matches!( + *token, + Token::Identifier("posedge" | "negedge" | "bothedge" | "level" | "nonsticky" | "sticky") + ) +} + +struct PropertyAssignment<'a> { + prop_name: &'a str, + value: Value, +} + +static INTR_BOOL_PROPERTY: PropertyMeta = PropertyMeta { + name: "intr", + ty: PropertyType::Boolean, +}; +fn intr_bool_property<'a>(_name: &str) -> Result<'a, &'static PropertyMeta> { + Ok(&INTR_BOOL_PROPERTY) +} + +impl<'a> PropertyAssignment<'a> { + fn parse( + tokens: &mut TokenIter<'a>, + parameters: Option<&ParameterScope<'_>>, + meta_lookup_fn: impl Fn(&'a str) -> Result<'a, &'static PropertyMeta>, + ) -> Result<'a, Self> { + if is_intr_modifier(tokens.peek(0)) && *tokens.peek(1) == Token::Identifier("intr") { + let intr_modifier = tokens.expect_identifier()?; + // skip the bool tokens... + PropertyAssignment::parse(tokens, parameters, intr_bool_property)?; + return Ok(Self { + prop_name: "intr", + value: match intr_modifier { + "posedge" => InterruptType::PosEdge.into(), + "negedge" => InterruptType::NegEdge.into(), + "bothedge" => InterruptType::BothEdge.into(), + "level" => InterruptType::Level.into(), + "nonsticky" => InterruptType::NonSticky.into(), + "sticky" => InterruptType::Sticky.into(), + _ => InterruptType::Level.into(), + }, + }); + } + + let prop_name = tokens.expect_identifier()?; + let prop_meta = meta_lookup_fn(prop_name)?; + + let value = if *tokens.peek(0) == Token::Semicolon { + // This must be a boolean property set to true or an intr + if prop_meta.ty != PropertyType::Boolean + && prop_meta.ty != PropertyType::BooleanOrReference + && prop_meta.ty != PropertyType::FieldInterrupt + { + return Err(RdlError::UnexpectedPropertyType { + expected_type: prop_meta.ty, + value: true.into(), + }); + } + true.into() + } else { + tokens.expect(Token::Equals)?; + prop_meta.ty.eval(tokens, parameters)? + }; + tokens.expect(Token::Semicolon)?; + Ok(Self { prop_name, value }) + } +} + #[cfg(test)] mod tests { use crate::{file_source::MemFileSource, value::AccessType, EnumReference}; @@ -1035,72 +1102,3 @@ mod tests { ); } } - -fn is_intr_modifier(token: &Token) -> bool { - matches!( - *token, - Token::Identifier("posedge" | "negedge" | "bothedge" | "level" | "nonsticky" | "sticky") - ) -} - -struct PropertyAssignment<'a> { - prop_name: &'a str, - value: Value, -} - -static INTR_BOOL_PROPERTY: PropertyMeta = PropertyMeta { - name: "intr", - ty: PropertyType::Boolean, - is_dynamic: true, -}; -fn intr_bool_property<'a>(_name: &str) -> Result<'a, &'static PropertyMeta> { - Ok(&INTR_BOOL_PROPERTY) -} - -impl<'a> PropertyAssignment<'a> { - fn parse( - tokens: &mut TokenIter<'a>, - parameters: Option<&ParameterScope<'_>>, - meta_lookup_fn: impl Fn(&'a str) -> Result<'a, &'static PropertyMeta>, - ) -> Result<'a, Self> { - if is_intr_modifier(tokens.peek(0)) && *tokens.peek(1) == Token::Identifier("intr") { - let intr_modifier = tokens.expect_identifier()?; - // skip the bool tokens... - PropertyAssignment::parse(tokens, parameters, intr_bool_property)?; - return Ok(Self { - prop_name: "intr", - value: match intr_modifier { - "posedge" => InterruptType::PosEdge.into(), - "negedge" => InterruptType::NegEdge.into(), - "bothedge" => InterruptType::BothEdge.into(), - "level" => InterruptType::Level.into(), - "nonsticky" => InterruptType::NonSticky.into(), - "sticky" => InterruptType::Sticky.into(), - _ => InterruptType::Level.into(), - }, - }); - } - - let prop_name = tokens.expect_identifier()?; - let prop_meta = meta_lookup_fn(prop_name)?; - - let value = if *tokens.peek(0) == Token::Semicolon { - // This must be a boolean property set to true or an intr - if prop_meta.ty != PropertyType::Boolean - && prop_meta.ty != PropertyType::BooleanOrReference - && prop_meta.ty != PropertyType::FieldInterrupt - { - return Err(RdlError::UnexpectedPropertyType { - expected_type: prop_meta.ty, - value: true.into(), - }); - } - true.into() - } else { - tokens.expect(Token::Equals)?; - prop_meta.ty.eval(tokens, parameters)? - }; - tokens.expect(Token::Semicolon)?; - Ok(Self { prop_name, value }) - } -} diff --git a/systemrdl/src/token_iter.rs b/systemrdl/src/token_iter.rs index a40c85e2b7..653624d2e8 100644 --- a/systemrdl/src/token_iter.rs +++ b/systemrdl/src/token_iter.rs @@ -97,9 +97,7 @@ impl<'a> TokenIter<'a> { continue; } None => { - let Some(stack_entry) = self.iter_stack.pop() else { - return None; - }; + let stack_entry = self.iter_stack.pop()?; // this file was included from another file; resume // processing the original file. self.lex = stack_entry.lex; diff --git a/test/src/lib.rs b/test/src/lib.rs index 16603fd761..fd9b449465 100644 --- a/test/src/lib.rs +++ b/test/src/lib.rs @@ -78,7 +78,7 @@ pub fn run_test( .unwrap(); let image_bytes = image.to_bytes().unwrap(); - let boot_params = boot_params.unwrap_or(BootParams::default()); + let boot_params = boot_params.unwrap_or_default(); // Use image in boot_params if provided // Otherwise, add our newly built image diff --git a/test/src/x509.rs b/test/src/x509.rs index 09ac3374f1..7de26bda32 100644 --- a/test/src/x509.rs +++ b/test/src/x509.rs @@ -103,7 +103,7 @@ impl DiceTcbInfo { } pub fn find_single_in_cert(cert_der: &[u8]) -> Result, asn1::ParseError> { let Some(ext_der) = get_cert_extension(cert_der, &DICE_TCB_INFO_OID)? else { - return Ok(None) + return Ok(None); }; asn1::parse(ext_der, Self::parse_single).map(Some) } diff --git a/test/tests/caliptra_integration_tests/jtag_test.rs b/test/tests/caliptra_integration_tests/jtag_test.rs index b1f2cf4747..1ce1bd4864 100644 --- a/test/tests/caliptra_integration_tests/jtag_test.rs +++ b/test/tests/caliptra_integration_tests/jtag_test.rs @@ -125,6 +125,8 @@ fn gdb_test() { .spawn() .unwrap(); + gdb.wait().unwrap(); + let mut stdin = gdb.stdin.take().expect("Failed to open stdin"); let mut stderr = BufReader::new(gdb.stderr.as_mut().unwrap()); diff --git a/test/tests/fips_test_suite/common.rs b/test/tests/fips_test_suite/common.rs index c1e62faf50..10ff5685dc 100755 --- a/test/tests/fips_test_suite/common.rs +++ b/test/tests/fips_test_suite/common.rs @@ -130,7 +130,7 @@ impl RtExpVals { pub fn fips_test_init_model(init_params: Option) -> DefaultHwModel { // Create params if not provided - let mut init_params = init_params.unwrap_or(InitParams::default()); + let mut init_params = init_params.unwrap_or_default(); // Check that ROM was not provided if the immutable_rom feature is set #[cfg(feature = "test_env_immutable_rom")] @@ -161,7 +161,7 @@ pub fn fips_test_init_model(init_params: Option) -> DefaultHwModel { fn fips_test_boot(hw: &mut T, boot_params: Option) { // Create params if not provided - let boot_params = boot_params.unwrap_or(BootParams::default()); + let boot_params = boot_params.unwrap_or_default(); // Boot hw.boot(boot_params).unwrap(); @@ -223,7 +223,7 @@ pub fn fips_test_init_to_rt( boot_params: Option, ) -> DefaultHwModel { // Create params if not provided - let mut boot_params = boot_params.unwrap_or(BootParams::default()); + let mut boot_params = boot_params.unwrap_or_default(); if boot_params.fw_image.is_some() { fips_test_init_base(init_params, Some(boot_params)) diff --git a/ureg/lib/schema/src/validate.rs b/ureg/lib/schema/src/validate.rs index 8f3ca782a0..acaa25a204 100644 --- a/ureg/lib/schema/src/validate.rs +++ b/ureg/lib/schema/src/validate.rs @@ -233,7 +233,9 @@ impl ValidatedRegisterBlock { // Keep this register in self.registers return true; } - let Ok(index) = reg.name[reg_name.len()..].parse::() else { return true; }; + let Ok(index) = reg.name[reg_name.len()..].parse::() else { + return true; + }; let reg_name = reg_name.trim_start_matches(block_name); instances_by_name @@ -484,36 +486,6 @@ fn compute_common_name<'a>(reg_names: &'a [&'a str]) -> Option { .and_then(|s| if s.is_empty() { None } else { Some(s) }) } -#[cfg(test)] -mod compute_reg_type_name_tests { - use super::*; - - #[test] - fn test() { - assert_eq!( - compute_common_name(&["UART0", "UART1", "UART10"]), - Some("UART".into()) - ); - assert_eq!(compute_common_name(&["UART0"]), Some("UART0".into())); - assert_eq!( - compute_common_name(&["DIEPTCTL", "DOEPTCTL"]), - Some("DXEPTCTL".into()) - ); - assert_eq!( - compute_common_name(&["dieptctl", "doeptctl"]), - Some("dxeptctl".into()) - ); - assert_eq!( - compute_common_name(&["DIEPTCTL0", "DIEPTCTL1", "DOEPTCTL0", "DOEPTCTL1"]), - Some("DXEPTCTL".into()) - ); - assert_eq!( - compute_common_name(&["PROG_LB0_POST_OVRD", "LB0_POST_OVRD"]), - Some("LB0_POST_OVRD".into()) - ); - } -} - fn hash_u64(v: &impl Hash) -> u64 { let mut h = DefaultHasher::new(); v.hash(&mut h); @@ -778,3 +750,33 @@ impl RegisterBlock { } } } + +#[cfg(test)] +mod compute_reg_type_name_tests { + use super::*; + + #[test] + fn test() { + assert_eq!( + compute_common_name(&["UART0", "UART1", "UART10"]), + Some("UART".into()) + ); + assert_eq!(compute_common_name(&["UART0"]), Some("UART0".into())); + assert_eq!( + compute_common_name(&["DIEPTCTL", "DOEPTCTL"]), + Some("DXEPTCTL".into()) + ); + assert_eq!( + compute_common_name(&["dieptctl", "doeptctl"]), + Some("dxeptctl".into()) + ); + assert_eq!( + compute_common_name(&["DIEPTCTL0", "DIEPTCTL1", "DOEPTCTL0", "DOEPTCTL1"]), + Some("DXEPTCTL".into()) + ); + assert_eq!( + compute_common_name(&["PROG_LB0_POST_OVRD", "LB0_POST_OVRD"]), + Some("LB0_POST_OVRD".into()) + ); + } +} diff --git a/ureg/lib/systemrdl/src/lib.rs b/ureg/lib/systemrdl/src/lib.rs index 0dba7a33e2..a726c2e81d 100644 --- a/ureg/lib/systemrdl/src/lib.rs +++ b/ureg/lib/systemrdl/src/lib.rs @@ -362,23 +362,6 @@ fn next_multiple_of(x: u64, mult: u64) -> u64 { } } -#[cfg(test)] -mod next_multiple_of_tests { - use super::*; - #[test] - fn test_next_multiple_of() { - assert_eq!(0, next_multiple_of(0, 3)); - assert_eq!(3, next_multiple_of(1, 3)); - assert_eq!(3, next_multiple_of(2, 3)); - assert_eq!(3, next_multiple_of(3, 3)); - assert_eq!(6, next_multiple_of(4, 3)); - for i in 1..128 { - assert_eq!(128, next_multiple_of(i, 128)); - assert_eq!(256, next_multiple_of(128 + i, 128)); - } - } -} - fn translate_block(iref: InstanceRef, top: bool) -> Result { let wrap_err = |err: Error| Error::BlockError { block_name: iref.instance.name.clone(), @@ -473,3 +456,20 @@ pub fn translate_addrmap(addrmap: systemrdl::ParentScope) -> Result { pub tcb_info_fw_svn: &'a [u8; 1usize], pub tcb_info_fw_svn_fuses: &'a [u8; 1usize], } -impl<'a> FmcAliasCertTbsEcc384Params<'a> { +impl FmcAliasCertTbsEcc384Params<'_> { pub const PUBLIC_KEY_LEN: usize = 97usize; pub const SUBJECT_SN_LEN: usize = 64usize; pub const ISSUER_SN_LEN: usize = 64usize; diff --git a/x509/build/fmc_alias_cert_tbs_mldsa_87.rs b/x509/build/fmc_alias_cert_tbs_mldsa_87.rs index 40287bca7a..cff22eba01 100644 --- a/x509/build/fmc_alias_cert_tbs_mldsa_87.rs +++ b/x509/build/fmc_alias_cert_tbs_mldsa_87.rs @@ -5,9 +5,7 @@ Licensed under the Apache-2.0 license. Abstract: --"] - // TODO generate when x509 libraries support MLDSA - pub struct FmcAliasCertTbsMlDsa87Params<'a> { pub public_key: &'a [u8; 2592usize], pub subject_sn: &'a [u8; 64usize], @@ -26,7 +24,7 @@ pub struct FmcAliasCertTbsMlDsa87Params<'a> { } #[allow(dead_code)] -impl<'a> FmcAliasCertTbsMlDsa87Params<'a> { +impl FmcAliasCertTbsMlDsa87Params<'_> { pub const PUBLIC_KEY_LEN: usize = 2592usize; pub const SUBJECT_SN_LEN: usize = 64usize; pub const ISSUER_SN_LEN: usize = 64usize; diff --git a/x509/build/init_dev_id_csr_tbs_ecc_384.rs b/x509/build/init_dev_id_csr_tbs_ecc_384.rs index 04b0542f8e..baad0612d4 100644 --- a/x509/build/init_dev_id_csr_tbs_ecc_384.rs +++ b/x509/build/init_dev_id_csr_tbs_ecc_384.rs @@ -12,7 +12,7 @@ pub struct InitDevIdCsrTbsEcc384Params<'a> { pub public_key: &'a [u8; 97usize], pub subject_sn: &'a [u8; 64usize], } -impl<'a> InitDevIdCsrTbsEcc384Params<'a> { +impl InitDevIdCsrTbsEcc384Params<'_> { pub const UEID_LEN: usize = 17usize; pub const PUBLIC_KEY_LEN: usize = 97usize; pub const SUBJECT_SN_LEN: usize = 64usize; diff --git a/x509/build/init_dev_id_csr_tbs_mldsa_87.rs b/x509/build/init_dev_id_csr_tbs_mldsa_87.rs index 3e0c2b0708..48c93b9244 100644 --- a/x509/build/init_dev_id_csr_tbs_mldsa_87.rs +++ b/x509/build/init_dev_id_csr_tbs_mldsa_87.rs @@ -14,7 +14,7 @@ pub struct InitDevIdCsrTbsMlDsa87Params<'a> { } #[allow(dead_code)] -impl<'a> InitDevIdCsrTbsMlDsa87Params<'a> { +impl InitDevIdCsrTbsMlDsa87Params<'_> { pub const UEID_LEN: usize = 17usize; pub const PUBLIC_KEY_LEN: usize = 2592usize; pub const SUBJECT_SN_LEN: usize = 64usize; diff --git a/x509/build/local_dev_id_cert_tbs_ecc_384.rs b/x509/build/local_dev_id_cert_tbs_ecc_384.rs index cb4622260c..8bb540b008 100644 --- a/x509/build/local_dev_id_cert_tbs_ecc_384.rs +++ b/x509/build/local_dev_id_cert_tbs_ecc_384.rs @@ -18,7 +18,7 @@ pub struct LocalDevIdCertTbsEcc384Params<'a> { pub not_before: &'a [u8; 15usize], pub not_after: &'a [u8; 15usize], } -impl<'a> LocalDevIdCertTbsEcc384Params<'a> { +impl LocalDevIdCertTbsEcc384Params<'_> { pub const PUBLIC_KEY_LEN: usize = 97usize; pub const SUBJECT_SN_LEN: usize = 64usize; pub const ISSUER_SN_LEN: usize = 64usize; diff --git a/x509/build/local_dev_id_cert_tbs_mldsa_87.rs b/x509/build/local_dev_id_cert_tbs_mldsa_87.rs index 7645b1b535..f34b5bad54 100644 --- a/x509/build/local_dev_id_cert_tbs_mldsa_87.rs +++ b/x509/build/local_dev_id_cert_tbs_mldsa_87.rs @@ -7,9 +7,7 @@ Abstract: Regenerate the template by building caliptra-x509-build with the generate-templates flag. --"] - // TODO generate when x509 libraries support MLDSA - #[allow(dead_code)] pub struct LocalDevIdCertTbsMlDsa87Params<'a> { pub public_key: &'a [u8; 2592usize], @@ -23,7 +21,7 @@ pub struct LocalDevIdCertTbsMlDsa87Params<'a> { pub not_after: &'a [u8; 15usize], } #[allow(dead_code)] -impl<'a> LocalDevIdCertTbsMlDsa87Params<'a> { +impl LocalDevIdCertTbsMlDsa87Params<'_> { pub const PUBLIC_KEY_LEN: usize = 97usize; pub const SUBJECT_SN_LEN: usize = 64usize; pub const ISSUER_SN_LEN: usize = 64usize; diff --git a/x509/build/rt_alias_cert_tbs_ecc_384.rs b/x509/build/rt_alias_cert_tbs_ecc_384.rs index 84a23d1905..e896d1f01c 100644 --- a/x509/build/rt_alias_cert_tbs_ecc_384.rs +++ b/x509/build/rt_alias_cert_tbs_ecc_384.rs @@ -20,7 +20,7 @@ pub struct RtAliasCertTbsEcc384Params<'a> { pub not_after: &'a [u8; 15usize], pub tcb_info_fw_svn: &'a [u8; 1usize], } -impl<'a> RtAliasCertTbsEcc384Params<'a> { +impl RtAliasCertTbsEcc384Params<'_> { pub const PUBLIC_KEY_LEN: usize = 97usize; pub const SUBJECT_SN_LEN: usize = 64usize; pub const ISSUER_SN_LEN: usize = 64usize; diff --git a/x509/build/rt_alias_cert_tbs_mldsa_87.rs b/x509/build/rt_alias_cert_tbs_mldsa_87.rs index a2b3a46fb5..f89a7eba17 100644 --- a/x509/build/rt_alias_cert_tbs_mldsa_87.rs +++ b/x509/build/rt_alias_cert_tbs_mldsa_87.rs @@ -23,7 +23,7 @@ pub struct RtAliasCertTbsMlDsa87Params<'a> { pub tcb_info_fw_svn: &'a [u8; 1usize], } #[allow(dead_code)] -impl<'a> RtAliasCertTbsMlDsa87Params<'a> { +impl RtAliasCertTbsMlDsa87Params<'_> { pub const PUBLIC_KEY_LEN: usize = 2592usize; pub const SUBJECT_SN_LEN: usize = 64usize; pub const ISSUER_SN_LEN: usize = 64usize; diff --git a/x509/src/cert_bldr.rs b/x509/src/cert_bldr.rs index 52759c50bc..e86f1ff4a1 100644 --- a/x509/src/cert_bldr.rs +++ b/x509/src/cert_bldr.rs @@ -57,10 +57,10 @@ impl Ecdsa384Signature { impl Signature<108> for Ecdsa384Signature { fn to_der(&self, buf: &mut [u8; 108]) -> Option { // Encode Signature R Coordinate - let r_uint_len = der_uint_len(&self.r)?; + let r_uint_len = der_uint_len(&self.r); // Encode Signature S Coordinate - let s_uint_len = der_uint_len(&self.s)?; + let s_uint_len = der_uint_len(&self.s); // // Signature DER Sequence encoding @@ -115,7 +115,7 @@ impl Default for Mldsa87Signature { impl Signature<4641> for Mldsa87Signature { fn to_der(&self, buf: &mut [u8; 4641]) -> Option { - let ml_dsa_signature_len = der_uint_len(&self.sig)?; + let ml_dsa_signature_len = der_uint_len(&self.sig); // // Signature DER Sequence encoding diff --git a/x509/src/der_helper.rs b/x509/src/der_helper.rs index 956ad5a0af..1cb4b584d9 100644 --- a/x509/src/der_helper.rs +++ b/x509/src/der_helper.rs @@ -39,17 +39,16 @@ fn encode_length(val: &[u8]) -> usize { /// Compute len of DER encoding of an unsinged integer #[inline(never)] -pub fn der_uint_len(val: &[u8]) -> Option { +pub fn der_uint_len(val: &[u8]) -> usize { let encode_length = encode_length(val); let len_field_size = match encode_length { 0..=127 => 1, 128.. => trim_leading_zeros(&encode_length.to_be_bytes()).len(), - _ => None?, }; // Tag + len + int - Some(1 + len_field_size + encode_length) + 1 + len_field_size + encode_length } /// Encode a DER length