From 0ece6a35b40fd0e3ef49ac5b38b3300a19e7b0ec Mon Sep 17 00:00:00 2001 From: Tyler Smith <74526874+tylertms@users.noreply.github.com> Date: Tue, 10 Nov 2026 09:38:05 +0000 Subject: [PATCH] refactor: share CRC-32 and byte-field readers through stela-contracts --- Cargo.lock | 2 + crates/stela-boot-core/src/guarded_stacks.rs | 2 +- .../src/guarded_stacks/mappings.rs | 2 +- .../src/host_resources/smbios.rs | 2 +- crates/stela-boot-core/src/memory_budget.rs | 2 +- .../stela-boot-core/src/native_resources.rs | 2 +- crates/stela-boot-core/src/page_window.rs | 2 +- crates/stela-boot-core/src/pe.rs | 2 +- crates/stela-boot-core/src/resident_image.rs | 2 +- crates/stela-boot/Cargo.lock | 1 + crates/stela-contracts/src/adt.rs | 17 ++-- crates/stela-contracts/src/bytes.rs | 67 ++++++++++++++++ crates/stela-contracts/src/crc.rs | 77 +++++++++++++++++++ crates/stela-contracts/src/lib.rs | 2 + .../stela-driver-base/src/bus/mmio/owned.rs | 3 +- .../src/bus/thunderbolt/config.rs | 13 +--- .../src/bus/thunderbolt/drom.rs | 28 ++----- .../src/bus/thunderbolt/drom/tests.rs | 4 +- crates/stela-driver-core/Cargo.toml | 1 + crates/stela-driver-core/src/bytes.rs | 43 ----------- crates/stela-driver-core/src/lib.rs | 3 +- .../src/metal/input/Cargo.toml | 1 + crates/stela-driver-gpu/src/metal/library.rs | 13 +--- crates/stela-driver-net/src/tg3/filter.rs | 15 +--- .../src/wifi/mediatek/firmware.rs | 4 +- .../src/wifi/realtek/firmware.rs | 8 +- .../src/wifi/regulatory/database.rs | 4 +- .../stela-driver-net/src/wifi/scan/six_ghz.rs | 2 +- .../stela-driver-net/src/wifi/security/wep.rs | 14 +--- crates/stela-formats/src/apfs.rs | 33 ++------ crates/stela-formats/src/apfs/decmpfs.rs | 13 ++-- crates/stela-formats/src/code_signature.rs | 6 +- crates/stela-formats/src/lzfse.rs | 16 +--- crates/stela-formats/src/payload/staging.rs | 3 +- crates/stela-formats/src/payload/zip.rs | 69 +++++++---------- .../src/payload/zip/test_support.rs | 2 +- crates/stela-loader/src/chained_fixups.rs | 17 ++-- .../coprocessor/configuration/finalization.rs | 23 ++---- .../configuration/tuning/source.rs | 21 ++--- crates/stela-loader/src/gpu_dvfs.rs | 2 +- crates/stela-loader/src/kernel_collection.rs | 2 +- crates/stela-loader/src/plugin.rs | 4 +- crates/stela-runtime/src/platform/pc/acpi.rs | 23 ++---- .../src/platform/pc/board_flash.rs | 11 +-- crates/stela-runtime/src/platform/pc/power.rs | 27 ++----- .../src/pmgr/t6000/reconfiguration.rs | 10 +-- crates/stela-soc/src/ans/bfh.rs | 4 +- crates/stela-soc/src/checksum.rs | 58 -------------- crates/stela-soc/src/lib.rs | 1 - crates/stela-soc/src/research/nhi/control.rs | 2 +- crates/stela-soc/src/sep/keystore.rs | 4 +- crates/stela-soc/src/usb/storage.rs | 11 +-- xtask/src/boot/audio_check.rs | 8 +- 53 files changed, 297 insertions(+), 411 deletions(-) create mode 100644 crates/stela-contracts/src/bytes.rs create mode 100644 crates/stela-contracts/src/crc.rs delete mode 100644 crates/stela-driver-core/src/bytes.rs delete mode 100644 crates/stela-soc/src/checksum.rs diff --git a/Cargo.lock b/Cargo.lock index 89f91dbbcd..408ec7cf29 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -2261,6 +2261,7 @@ dependencies = [ name = "stela-driver-core" version = "0.1.0" dependencies = [ + "stela-contracts", "sha2", "stela-crypto", ] @@ -2418,6 +2419,7 @@ dependencies = [ ] [[package]] + "stela-contracts", name = "stela-metal-input" version = "0.1.0" dependencies = [ diff --git a/crates/stela-boot-core/src/guarded_stacks.rs b/crates/stela-boot-core/src/guarded_stacks.rs index ab0da189b2..8f1817ecd0 100644 --- a/crates/stela-boot-core/src/guarded_stacks.rs +++ b/crates/stela-boot-core/src/guarded_stacks.rs @@ -6,7 +6,7 @@ pub mod mappings; mod mixed; use core::ops::Range; pub use mixed::{Geometry, MixedLayout}; -const PAGE: u64 = 4096; +use stela_contracts::bytes::HOST_PAGE_BYTES as PAGE; /// The most stacks a layout holds: the BSP's whole work pool. const MAX_STACKS: usize = crate::native_resources::TASK_STACKS; diff --git a/crates/stela-boot-core/src/guarded_stacks/mappings.rs b/crates/stela-boot-core/src/guarded_stacks/mappings.rs index ca1967ad36..87033c5577 100644 --- a/crates/stela-boot-core/src/guarded_stacks/mappings.rs +++ b/crates/stela-boot-core/src/guarded_stacks/mappings.rs @@ -1,6 +1,6 @@ //! Read-only page-table validation, separate from ownership admission. use super::Slot; -const PAGE: u64 = 4096; +use stela_contracts::bytes::HOST_PAGE_BYTES as PAGE; const ADDRESS: u64 = 0x000f_ffff_ffff_f000; const PRESENT: u64 = 1; const WRITE: u64 = 2; diff --git a/crates/stela-boot-core/src/host_resources/smbios.rs b/crates/stela-boot-core/src/host_resources/smbios.rs index e17f036581..56f02d61ad 100644 --- a/crates/stela-boot-core/src/host_resources/smbios.rs +++ b/crates/stela-boot-core/src/host_resources/smbios.rs @@ -9,7 +9,7 @@ use stela_crypto::digest::Digest; use stela_drivers::firmware::smbios::{self, Error, Format, MAX_ENTRY_BYTES}; use uefi_raw::table::boot::MemoryType; -const PAGE: u64 = 4096; +use stela_contracts::bytes::HOST_PAGE_BYTES as PAGE; #[derive(Clone, Copy, Debug, Eq, PartialEq)] pub enum Stage { diff --git a/crates/stela-boot-core/src/memory_budget.rs b/crates/stela-boot-core/src/memory_budget.rs index a3baeedcc1..a865a70975 100644 --- a/crates/stela-boot-core/src/memory_budget.rs +++ b/crates/stela-boot-core/src/memory_budget.rs @@ -1,6 +1,6 @@ //! Memory budgets for allocations made while UEFI still owns boot services. use core::fmt; -const PAGE: u64 = 4096; +use stela_contracts::bytes::HOST_PAGE_BYTES as PAGE; const MIB: u64 = 1024 * 1024; const MINIMUM: u64 = 16 * MIB; const MAXIMUM: u64 = 384 * MIB; diff --git a/crates/stela-boot-core/src/native_resources.rs b/crates/stela-boot-core/src/native_resources.rs index 4af58664f2..3593cc186e 100644 --- a/crates/stela-boot-core/src/native_resources.rs +++ b/crates/stela-boot-core/src/native_resources.rs @@ -6,7 +6,7 @@ use alloc::vec::Vec; use core::ops::Range; use stela_contracts::refuse; -const PAGE: u64 = 4096; +use stela_contracts::bytes::HOST_PAGE_BYTES as PAGE; const MIB: u64 = 1024 * 1024; pub const STACK_BYTES: u64 = 2 * 1024 * 1024; diff --git a/crates/stela-boot-core/src/page_window.rs b/crates/stela-boot-core/src/page_window.rs index ea89c7b8b2..f41b662ea2 100644 --- a/crates/stela-boot-core/src/page_window.rs +++ b/crates/stela-boot-core/src/page_window.rs @@ -10,7 +10,7 @@ use alloc::{collections::BTreeMap, vec::Vec}; use core::ops::Range; -pub const PAGE: u64 = 4096; +pub use stela_contracts::bytes::HOST_PAGE_BYTES as PAGE; /// Bytes one paging-structure entry's level covers, from the leaf up. const DIRECTORY_BYTES: u64 = PAGE << 9; const DIRECTORY_POINTER_BYTES: u64 = DIRECTORY_BYTES << 9; diff --git a/crates/stela-boot-core/src/pe.rs b/crates/stela-boot-core/src/pe.rs index f591712701..4cf2c0cbb5 100644 --- a/crates/stela-boot-core/src/pe.rs +++ b/crates/stela-boot-core/src/pe.rs @@ -5,7 +5,7 @@ use crate::Result; use alloc::vec::Vec; use stela_contracts::refuse; -pub const PAGE: usize = 4096; +pub const PAGE: usize = stela_contracts::bytes::HOST_PAGE_BYTES as usize; const DOS_HEADER: usize = 64; const PE_HEADER: usize = 24; const OPTIONAL_HEADER: usize = 112; diff --git a/crates/stela-boot-core/src/resident_image.rs b/crates/stela-boot-core/src/resident_image.rs index e89e97dfcf..6d86b0c09c 100644 --- a/crates/stela-boot-core/src/resident_image.rs +++ b/crates/stela-boot-core/src/resident_image.rs @@ -2,7 +2,7 @@ //! This describes byte ranges only; it creates no allocation, code or root pin. use core::ops::Range; -const PAGE: u64 = 4096; +use stela_contracts::bytes::HOST_PAGE_BYTES as PAGE; #[derive(Clone, Copy, Debug, Eq, PartialEq)] pub enum Error { diff --git a/crates/stela-boot/Cargo.lock b/crates/stela-boot/Cargo.lock index 58a37f0690..0f50b9251d 100644 --- a/crates/stela-boot/Cargo.lock +++ b/crates/stela-boot/Cargo.lock @@ -1063,6 +1063,7 @@ dependencies = [ name = "stela-driver-core" version = "0.1.0" dependencies = [ + "stela-contracts", "stela-crypto", ] diff --git a/crates/stela-contracts/src/adt.rs b/crates/stela-contracts/src/adt.rs index 8d87669325..0c8045f69d 100644 --- a/crates/stela-contracts/src/adt.rs +++ b/crates/stela-contracts/src/adt.rs @@ -2,6 +2,7 @@ //! count, a child count, properties (32-byte name, 32-bit length whose top //! bit is a flag, value padded to 4 bytes), then children //! (m1n1 `adt.c`; the format `stela-loader` parses and serializes exactly). +use crate::bytes::get_le32; use alloc::vec::Vec; const NODE_HEADER_BYTES: usize = 8; @@ -33,12 +34,6 @@ fn cells(value: &[u8]) -> Vec { /// (name, value) of every property of a node. type Properties<'a> = Vec<(&'a [u8], &'a [u8])>; -fn u32_at(data: &[u8], offset: usize) -> Option { - Some(u32::from_le_bytes( - data.get(offset..offset.checked_add(4)?)?.try_into().ok()?, - )) -} - struct Property<'a> { name: &'a [u8], value: &'a [u8], @@ -51,7 +46,7 @@ fn property_at(data: &[u8], offset: usize) -> Option> { let value_start = offset.checked_add(PROPERTY_HEADER_BYTES)?; let name = data.get(offset..name_end)?; let name = &name[..name.iter().position(|&b| b == 0).unwrap_or(name.len())]; - let encoded_length = u32_at(data, name_end)?; + let encoded_length = get_le32(data, name_end)?; let length = (encoded_length & 0x7fff_ffff) as usize; let value_end = value_start.checked_add(length)?; let padded = length.checked_add(3)? & !3; @@ -142,8 +137,8 @@ impl<'a> Node<'a> { return None; } let start = offset.checked_add(NODE_HEADER_BYTES)?; - let properties = u32_at(data, offset)? as usize; - let children = u32_at(data, offset.checked_add(4)?)? as usize; + let properties = get_le32(data, offset)? as usize; + let children = get_le32(data, offset.checked_add(4)?)? as usize; let minimum = properties .checked_mul(PROPERTY_HEADER_BYTES)? .checked_add(children.checked_mul(NODE_HEADER_BYTES)?)?; @@ -330,7 +325,7 @@ impl<'a> Node<'a> { /// The first 32-bit cell of a property. pub fn first_u32(&self, name: &str) -> Option { - u32_at(self.property(name)?, 0) + get_le32(self.property(name)?, 0) } /// A property's first 64 bits, little-endian, when it is at least eight @@ -407,7 +402,7 @@ mod tests { assert!(Node::root(&tree).is_none()); assert!(Node::root_exact(&tree).is_none()); } - assert!(u32_at(&[], usize::MAX).is_none()); + assert!(get_le32(&[], usize::MAX).is_none()); assert!(property_at(&[], usize::MAX).is_none()); } diff --git a/crates/stela-contracts/src/bytes.rs b/crates/stela-contracts/src/bytes.rs new file mode 100644 index 0000000000..259bf0fb56 --- /dev/null +++ b/crates/stela-contracts/src/bytes.rs @@ -0,0 +1,67 @@ +//! Fixed-width fields in byte buffers, and the page sizes Stela's crates +//! share. +//! +//! `le16` to `be64` and [`array`] index like a slice and panic past the end, +//! for buffers whose length is already checked; the `get_` forms return +//! `None` instead. + +/// The x86 host's base page. +pub const HOST_PAGE_BYTES: u64 = 0x1000; +/// The 16 KiB page of Apple's ARM guests. +pub const GUEST_PAGE_BYTES: u64 = 0x4000; + +/// The `N` bytes at `at`. +pub fn array(bytes: &[u8], at: usize) -> [u8; N] { + bytes[at..at + N].try_into().unwrap() +} + +/// The `N` bytes at `at`, or `None` past the end. +pub fn get_array(bytes: &[u8], at: usize) -> Option<[u8; N]> { + bytes.get(at..at.checked_add(N)?)?.try_into().ok() +} + +macro_rules! fields { + ($($name:ident, $get:ident, $type:ty, $from:ident;)*) => {$( + pub fn $name(bytes: &[u8], at: usize) -> $type { + <$type>::$from(array(bytes, at)) + } + + pub fn $get(bytes: &[u8], at: usize) -> Option<$type> { + Some(<$type>::$from(get_array(bytes, at)?)) + } + )*}; +} + +fields! { + le16, get_le16, u16, from_le_bytes; + le32, get_le32, u32, from_le_bytes; + le64, get_le64, u64, from_le_bytes; + be16, get_be16, u16, from_be_bytes; + be32, get_be32, u32, from_be_bytes; + be64, get_be64, u64, from_be_bytes; +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn fields_read_in_their_byte_order_and_checked_forms_refuse_overruns() { + let bytes = [1, 2, 3, 4, 5, 6, 7, 8, 9]; + assert_eq!(le16(&bytes, 1), 0x0302); + assert_eq!(le32(&bytes, 0), 0x0403_0201); + assert_eq!(le64(&bytes, 1), 0x0908_0706_0504_0302); + assert_eq!(be16(&bytes, 1), 0x0203); + assert_eq!(be32(&bytes, 0), 0x0102_0304); + assert_eq!(be64(&bytes, 1), 0x0203_0405_0607_0809); + assert_eq!(array::<3>(&bytes, 6), [7, 8, 9]); + assert_eq!(get_le16(&bytes, 7), Some(0x0908)); + assert_eq!(get_be16(&bytes, 7), Some(0x0809)); + assert_eq!(get_le16(&bytes, 8), None); + assert_eq!(get_le32(&bytes, 6), None); + assert_eq!(get_be64(&bytes, 2), None); + assert_eq!(get_le64(&bytes, 1), Some(0x0908_0706_0504_0302)); + assert_eq!(get_le32(&bytes, usize::MAX), None); + assert_eq!(get_array::<2>(&bytes, 8), None); + } +} diff --git a/crates/stela-contracts/src/crc.rs b/crates/stela-contracts/src/crc.rs new file mode 100644 index 0000000000..4c7c2fab5e --- /dev/null +++ b/crates/stela-contracts/src/crc.rs @@ -0,0 +1,77 @@ +//! The two reflected CRC-32s Stela's formats and devices check: IEEE 802.3 +//! (GPT, ZIP, WEP, Ethernet) and Castagnoli, CRC-32C (Thunderbolt, ANS). +//! Both are table driven, with all-ones initial state and final XOR. + +const IEEE: u32 = 0xedb8_8320; +const CASTAGNOLI: u32 = 0x82f6_3b78; +const IEEE_TABLE: [u32; 256] = table(IEEE); +const CASTAGNOLI_TABLE: [u32; 256] = table(CASTAGNOLI); + +const fn table(polynomial: u32) -> [u32; 256] { + let mut table = [0; 256]; + let mut index = 0; + while index < 256 { + let mut crc = index as u32; + let mut bit = 0; + while bit < 8 { + crc = if crc & 1 != 0 { + (crc >> 1) ^ polynomial + } else { + crc >> 1 + }; + bit += 1; + } + table[index] = crc; + index += 1; + } + table +} + +fn update(table: &[u32; 256], mut state: u32, bytes: &[u8]) -> u32 { + for &byte in bytes { + state = table[((state ^ u32::from(byte)) & 0xff) as usize] ^ (state >> 8); + } + state +} + +/// The IEEE CRC-32 of `bytes`. +pub fn crc32_ieee(bytes: &[u8]) -> u32 { + !update(&IEEE_TABLE, !0, bytes) +} + +/// The CRC-32C of `bytes`. The integer is independent of a protocol's wire +/// byte order. +pub fn crc32c(bytes: &[u8]) -> u32 { + !crc32c_update(!0, bytes) +} + +/// The CRC-32C register after `bytes`, from `state`: start at `!0` and +/// invert the last state, for a checksum taken over several pieces. +pub fn crc32c_update(state: u32, bytes: &[u8]) -> u32 { + update(&CASTAGNOLI_TABLE, state, bytes) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn both_polynomials_match_their_check_values() { + assert_eq!(crc32_ieee(b"123456789"), 0xcbf4_3926); + assert_eq!(crc32_ieee(b""), 0); + assert_eq!(crc32c(b"123456789"), 0xe306_9283); + assert_eq!(crc32c(&[]), 0); + // The Linux kernel's CRC-32C table starts 0, f26b8303, e13b70f7. + assert_eq!(CASTAGNOLI_TABLE[..3], [0, 0xf26b_8303, 0xe13b_70f7]); + assert_eq!(IEEE_TABLE[1], 0x7707_3096); + } + + #[test] + fn crc32c_continues_across_pieces() { + assert_eq!(crc32c(&[0; 32]), 0x8a91_36aa); + assert_eq!(crc32c(&[0xff; 32]), 0x62a8_ab43); + let first = crc32c_update(!0, b"1234"); + assert_eq!(!crc32c_update(first, b"56789"), 0xe306_9283); + assert_eq!(crc32c_update(first, &[]), first); + } +} diff --git a/crates/stela-contracts/src/lib.rs b/crates/stela-contracts/src/lib.rs index 5db126486c..f4eba63665 100644 --- a/crates/stela-contracts/src/lib.rs +++ b/crates/stela-contracts/src/lib.rs @@ -5,9 +5,11 @@ extern crate alloc; pub mod adt; pub mod bus; +pub mod bytes; pub mod caches; pub mod chip; pub mod cpu_features; +pub mod crc; pub mod ctrr; pub mod dma; pub mod gate; diff --git a/crates/stela-driver-base/src/bus/mmio/owned.rs b/crates/stela-driver-base/src/bus/mmio/owned.rs index 59225e13b5..8a0c738a80 100644 --- a/crates/stela-driver-base/src/bus/mmio/owned.rs +++ b/crates/stela-driver-base/src/bus/mmio/owned.rs @@ -13,7 +13,8 @@ use core::{any::Any, mem::ManuallyDrop, ptr::NonNull}; pub mod model; pub use registry::{AliasId, Authority, Mapping, MappingView, ResourceId, Status}; -pub const PAGE_BYTES: u64 = 4096; +/// MMIO is owned and mapped in host pages. +pub use stela_driver_core::bytes::HOST_PAGE_BYTES as PAGE_BYTES; #[derive(Clone, Copy, Debug, Eq, PartialEq)] pub enum Error { diff --git a/crates/stela-driver-base/src/bus/thunderbolt/config.rs b/crates/stela-driver-base/src/bus/thunderbolt/config.rs index a7bec82467..b45a6f5ac0 100644 --- a/crates/stela-driver-base/src/bus/thunderbolt/config.rs +++ b/crates/stela-driver-base/src/bus/thunderbolt/config.rs @@ -4,6 +4,7 @@ //! Bounded raw NHI configuration packets adapted from Linux ctl.c/tb_msgs.h. //! Wire dwords and CRC are big endian; the DMA descriptor is little endian. use alloc::vec::Vec; +pub(super) use stela_driver_core::crc::crc32c; pub const FRAME_BYTES: usize = 256; pub const MAX_CONFIG_WORDS: usize = (FRAME_BYTES - 4 - 12) / 4; @@ -11,7 +12,6 @@ const ROUTE_MASK: u64 = (1 << 54) - 1; const ROUTE_HIGH_MASK: u32 = (1 << 22) - 1; const REPLY: u32 = 1 << 31; const ADDRESS_LIMIT: u16 = 1 << 13; -const CRC32C_POLYNOMIAL: u32 = 0x82f6_3b78; #[derive(Clone, Copy, Debug, PartialEq, Eq)] #[repr(u8)] @@ -135,17 +135,6 @@ pub(super) fn encode(kind: PacketType, words: &[u32]) -> Result Ok(Encoded { kind, bytes }) } -pub(super) fn crc32c(bytes: &[u8]) -> u32 { - let mut crc = !0u32; - for byte in bytes { - crc ^= u32::from(*byte); - for _ in 0..8 { - crc = (crc >> 1) ^ (CRC32C_POLYNOMIAL & 0u32.wrapping_sub(crc & 1)); - } - } - !crc -} - /// One exact outstanding operation. A transport must stop accepting replies /// after cancellation and drain/reset before reusing an ambiguous sequence. /// Serialize requests across the entire control channel: error packets lack diff --git a/crates/stela-driver-base/src/bus/thunderbolt/drom.rs b/crates/stela-driver-base/src/bus/thunderbolt/drom.rs index 9de102e6c7..0a1bd0d66d 100644 --- a/crates/stela-driver-base/src/bus/thunderbolt/drom.rs +++ b/crates/stela-driver-base/src/bus/thunderbolt/drom.rs @@ -4,6 +4,7 @@ //! DROM images: `tb_drom_parse` and its entry walks. Parsed identifiers and //! lane hints grant nothing: a router's adapters are what it reports. use alloc::vec::Vec; +use stela_driver_core::{bytes::le16, crc::crc32c}; pub const DATA_START: usize = 13; pub const MAX_LEN: usize = 4095 + DATA_START; @@ -21,11 +22,11 @@ pub enum Error { UidCrc { expected: u8, actual: u8 }, } #[derive(Clone, Copy, Debug, PartialEq, Eq)] -pub struct Crc32 { +pub struct Crc32c { pub expected: u32, pub actual: u32, } -impl Crc32 { +impl Crc32c { pub fn matches(self) -> bool { self.expected == self.actual } @@ -68,7 +69,7 @@ pub struct Image { pub uid: u64, pub uid_source: UidSource, pub revision: u8, - pub crc32: Crc32, + pub crc32c: Crc32c, pub product: (u16, u16), pub bytes: Vec, pub entries: Vec, @@ -89,7 +90,7 @@ impl Image { uid, uid_source: UidSource::Router, revision: 0, - crc32: Crc32 { + crc32c: Crc32c { expected: 0, actual: 0, }, @@ -157,19 +158,6 @@ fn crc8(data: &[u8]) -> u8 { } crc } -fn crc32(data: &[u8]) -> u32 { - let mut crc = !0u32; - for b in data { - crc ^= u32::from(*b); - for _ in 0..8 { - crc = (crc >> 1) ^ if crc & 1 != 0 { 0x82f63b78 } else { 0 }; - } - } - !crc -} -fn le16(data: &[u8], at: usize) -> u16 { - u16::from_le_bytes([data[at], data[at + 1]]) -} fn parse(image: &mut Image, max_port: u8, lanes: impl Fn(u8) -> bool) -> Result<(), Error> { if image.bytes.len() < 16 { return Err(Error::HeaderSize); @@ -202,9 +190,9 @@ fn parse(image: &mut Image, max_port: u8, lanes: impl Fn(u8) -> bool) -> Result< 3 => 16, other => return Err(Error::UnsupportedRevision(other)), }; - image.crc32 = Crc32 { + image.crc32c = Crc32c { expected: u32::from_le_bytes(bytes[9..13].try_into().unwrap()), - actual: crc32(&bytes[DATA_START..]), + actual: crc32c(&bytes[DATA_START..]), }; let mut at = header; while at < bytes.len() { @@ -275,7 +263,7 @@ pub(crate) fn seal(bytes: &mut [u8]) { let len = (bytes.len() - DATA_START) as u16; bytes[14..16].copy_from_slice(&len.to_le_bytes()); bytes[0] = crc8(&bytes[1..9]); - let crc = crc32(&bytes[13..]); + let crc = crc32c(&bytes[13..]); bytes[9..13].copy_from_slice(&crc.to_le_bytes()); } diff --git a/crates/stela-driver-base/src/bus/thunderbolt/drom/tests.rs b/crates/stela-driver-base/src/bus/thunderbolt/drom/tests.rs index cbc880db9d..67f6bc16b1 100644 --- a/crates/stela-driver-base/src/bus/thunderbolt/drom/tests.rs +++ b/crates/stela-driver-base/src/bus/thunderbolt/drom/tests.rs @@ -32,7 +32,7 @@ fn images_yield_names_products_and_lanes() { assert_eq!(image.uid_source, UidSource::Router); assert_eq!(image.vendor_name(), Some(&b"STELA"[..])); assert_eq!(image.device_name(), Some(&b"DP"[..])); - assert!(image.crc32.matches()); + assert!(image.crc32c.matches()); assert_eq!( image.product, if revision == 1 { @@ -70,7 +70,7 @@ fn a_version_1_image_supplies_a_missing_uid() { fn integrity_failures_are_explicit() { let mut bytes = rom(3); bytes[9] ^= 1; - assert!(!parsed(bytes, 7).unwrap().crc32.matches()); + assert!(!parsed(bytes, 7).unwrap().crc32c.matches()); let mut bytes = rom(1); bytes[0] ^= 1; assert!(matches!(parsed(bytes, 7), Err(Error::UidCrc { .. }))); diff --git a/crates/stela-driver-core/Cargo.toml b/crates/stela-driver-core/Cargo.toml index 45b0299630..68b870a179 100644 --- a/crates/stela-driver-core/Cargo.toml +++ b/crates/stela-driver-core/Cargo.toml @@ -8,6 +8,7 @@ license.workspace = true workspace = true [dependencies] +stela-contracts = { path = "../stela-contracts", default-features = false } stela-crypto = { path = "../stela-crypto" } [dev-dependencies] diff --git a/crates/stela-driver-core/src/bytes.rs b/crates/stela-driver-core/src/bytes.rs deleted file mode 100644 index 4becb463d1..0000000000 --- a/crates/stela-driver-core/src/bytes.rs +++ /dev/null @@ -1,43 +0,0 @@ -//! Little-endian fields in byte buffers. `le16`, `le32` and `le64` index like -//! a slice and panic past the end, for buffers whose length is already -//! checked; the `get_` forms return `None` instead. - -pub fn le16(bytes: &[u8], at: usize) -> u16 { - u16::from_le_bytes(field(bytes, at)) -} -pub fn le32(bytes: &[u8], at: usize) -> u32 { - u32::from_le_bytes(field(bytes, at)) -} -pub fn le64(bytes: &[u8], at: usize) -> u64 { - u64::from_le_bytes(field(bytes, at)) -} -pub fn get_le16(bytes: &[u8], at: usize) -> Option { - Some(u16::from_le_bytes(get_field(bytes, at)?)) -} -pub fn get_le32(bytes: &[u8], at: usize) -> Option { - Some(u32::from_le_bytes(get_field(bytes, at)?)) -} - -fn field(bytes: &[u8], at: usize) -> [u8; N] { - bytes[at..at + N].try_into().unwrap() -} -fn get_field(bytes: &[u8], at: usize) -> Option<[u8; N]> { - bytes.get(at..at.checked_add(N)?)?.try_into().ok() -} - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn fields_read_little_endian_and_checked_forms_refuse_overruns() { - let bytes = [1, 2, 3, 4, 5, 6, 7, 8, 9]; - assert_eq!(le16(&bytes, 1), 0x0302); - assert_eq!(le32(&bytes, 0), 0x0403_0201); - assert_eq!(le64(&bytes, 1), 0x0908_0706_0504_0302); - assert_eq!(get_le16(&bytes, 7), Some(0x0908)); - assert_eq!(get_le16(&bytes, 8), None); - assert_eq!(get_le32(&bytes, 6), None); - assert_eq!(get_le32(&bytes, usize::MAX), None); - } -} diff --git a/crates/stela-driver-core/src/lib.rs b/crates/stela-driver-core/src/lib.rs index b38bfd312c..fb1ce225bf 100644 --- a/crates/stela-driver-core/src/lib.rs +++ b/crates/stela-driver-core/src/lib.rs @@ -3,5 +3,6 @@ #[cfg_attr(test, macro_use)] extern crate alloc; -pub mod bytes; +/// Byte-field readers and CRCs, shared with the crates below the drivers. +pub use stela_contracts::{bytes, crc}; pub mod firmware; diff --git a/crates/stela-driver-gpu/src/metal/input/Cargo.toml b/crates/stela-driver-gpu/src/metal/input/Cargo.toml index 9fb3c1205c..f0336a22bc 100644 --- a/crates/stela-driver-gpu/src/metal/input/Cargo.toml +++ b/crates/stela-driver-gpu/src/metal/input/Cargo.toml @@ -12,4 +12,5 @@ path = "lib.rs" crate-type = ["rlib", "staticlib"] [dependencies] +stela-contracts = { path = "../../../../stela-contracts", default-features = false } stela-crypto = { path = "../../../../stela-crypto" } diff --git a/crates/stela-driver-gpu/src/metal/library.rs b/crates/stela-driver-gpu/src/metal/library.rs index 89a4f96a6c..da020caccb 100644 --- a/crates/stela-driver-gpu/src/metal/library.rs +++ b/crates/stela-driver-gpu/src/metal/library.rs @@ -5,6 +5,7 @@ //! metadata and digest remain borrowed from the original input. use alloc::vec::Vec; use core::{fmt, ops::Range, str}; +use stela_contracts::bytes::{le16, le32, le64}; use stela_crypto::{Sha256, digest::Digest}; const HEADER_BYTES: usize = 88; @@ -63,21 +64,15 @@ fn bytes(data: &[u8], offset: usize, size: usize) -> Result<&[u8]> { } fn u16_at(data: &[u8], offset: usize) -> Result { - Ok(u16::from_le_bytes( - bytes(data, offset, 2)?.try_into().unwrap(), - )) + bytes(data, offset, 2).map(|field| le16(field, 0)) } fn u32_at(data: &[u8], offset: usize) -> Result { - Ok(u32::from_le_bytes( - bytes(data, offset, 4)?.try_into().unwrap(), - )) + bytes(data, offset, 4).map(|field| le32(field, 0)) } fn u64_at(data: &[u8], offset: usize) -> Result { - Ok(u64::from_le_bytes( - bytes(data, offset, 8)?.try_into().unwrap(), - )) + bytes(data, offset, 8).map(|field| le64(field, 0)) } fn host_size(value: u64, offset: usize) -> Result { diff --git a/crates/stela-driver-net/src/tg3/filter.rs b/crates/stela-driver-net/src/tg3/filter.rs index 889e02bb3f..bcb275a15a 100644 --- a/crates/stela-driver-net/src/tg3/filter.rs +++ b/crates/stela-driver-net/src/tg3/filter.rs @@ -58,16 +58,9 @@ impl ReceiveFilter { } } -// calc_crc returns ~crc32(~0, mac, 6); the source uses ~calc_crc &0x7f. -// This bitwise IEEE implementation is compared against the unchanged Linux -// table generator and crc32_le_base, not a copy of this loop. +// calc_crc returns ~crc32(~0, mac, 6), the IEEE CRC-32; the source uses +// ~calc_crc & 0x7f. Its tests compare against the unchanged Linux table +// generator and crc32_le_base. pub(super) fn multicast_bit(mac: Mac) -> usize { - let mut crc = u32::MAX; - for byte in mac.0 { - crc ^= u32::from(byte); - for _ in 0..8 { - crc = (crc >> 1) ^ if crc & 1 != 0 { 0xedb8_8320 } else { 0 }; - } - } - (crc & 0x7f) as usize + (!stela_driver_core::crc::crc32_ieee(&mac.0) & 0x7f) as usize } diff --git a/crates/stela-driver-net/src/wifi/mediatek/firmware.rs b/crates/stela-driver-net/src/wifi/mediatek/firmware.rs index c8a5d8e767..b0e1d611b0 100644 --- a/crates/stela-driver-net/src/wifi/mediatek/firmware.rs +++ b/crates/stela-driver-net/src/wifi/mediatek/firmware.rs @@ -8,6 +8,7 @@ use crate::bytes::le32; use crate::firmware::{self as resources, Image, Provider, Requirement, Target}; use alloc::{string::String, vec::Vec}; use core::fmt; +use stela_driver_core::bytes::be32; pub mod auxiliary; pub mod clc; @@ -50,9 +51,6 @@ impl fmt::Display for FormatError { } impl core::error::Error for FormatError {} -fn be32(bytes: &[u8], at: usize) -> u32 { - u32::from_be_bytes(bytes[at..at + 4].try_into().unwrap()) -} fn checked_address(address: u32, bytes: u32) -> Result<(), FormatError> { if bytes == 0 || u64::from(address) + u64::from(bytes) > (1u64 << 32) { Err(FormatError::DeviceAddress) diff --git a/crates/stela-driver-net/src/wifi/realtek/firmware.rs b/crates/stela-driver-net/src/wifi/realtek/firmware.rs index e924a6f696..d82f7b9abb 100644 --- a/crates/stela-driver-net/src/wifi/realtek/firmware.rs +++ b/crates/stela-driver-net/src/wifi/realtek/firmware.rs @@ -46,14 +46,10 @@ fn bytes(data: &[u8], offset: usize, len: usize) -> Result<&[u8], ParseError> { .ok_or(ParseError::Truncated { offset, bytes: len }) } fn le16(data: &[u8], offset: usize) -> Result { - Ok(u16::from_le_bytes( - bytes(data, offset, 2)?.try_into().unwrap(), - )) + bytes(data, offset, 2).map(|field| stela_driver_core::bytes::le16(field, 0)) } fn le32(data: &[u8], offset: usize) -> Result { - Ok(u32::from_le_bytes( - bytes(data, offset, 4)?.try_into().unwrap(), - )) + bytes(data, offset, 4).map(|field| stela_driver_core::bytes::le32(field, 0)) } fn image_limit(data: &[u8]) -> Result<(), ParseError> { if data.len() > MAX_IMAGE { diff --git a/crates/stela-driver-net/src/wifi/regulatory/database.rs b/crates/stela-driver-net/src/wifi/regulatory/database.rs index 209fd451e5..60492c5db5 100644 --- a/crates/stela-driver-net/src/wifi/regulatory/database.rs +++ b/crates/stela-driver-net/src/wifi/regulatory/database.rs @@ -107,10 +107,10 @@ fn bytes(data: &[u8], at: usize, n: usize) -> Result<&[u8], Error> { .ok_or(Error::Truncated) } fn be16(data: &[u8], at: usize) -> Result { - Ok(u16::from_be_bytes(bytes(data, at, 2)?.try_into().unwrap())) + bytes(data, at, 2).map(|field| stela_driver_core::bytes::be16(field, 0)) } fn be32(data: &[u8], at: usize) -> Result { - Ok(u32::from_be_bytes(bytes(data, at, 4)?.try_into().unwrap())) + bytes(data, at, 4).map(|field| stela_driver_core::bytes::be32(field, 0)) } fn pointer(data: &[u8], at: usize) -> Result { Ok(usize::from(be16(data, at)?) * 4) diff --git a/crates/stela-driver-net/src/wifi/scan/six_ghz.rs b/crates/stela-driver-net/src/wifi/scan/six_ghz.rs index 7a94184754..6c5e519e70 100644 --- a/crates/stela-driver-net/src/wifi/scan/six_ghz.rs +++ b/crates/stela-driver-net/src/wifi/scan/six_ghz.rs @@ -57,7 +57,7 @@ pub struct Colocated { /// The short SSID, `~crc32_le(~0, ssid)`. pub fn short_ssid(ssid: &[u8]) -> u32 { - crate::wifi::security::wep::crc32(ssid) + stela_driver_core::crc::crc32_ieee(ssid) } /// `cfg80211_channel_is_psc`. diff --git a/crates/stela-driver-net/src/wifi/security/wep.rs b/crates/stela-driver-net/src/wifi/security/wep.rs index 67d33df9b6..29d6c98706 100644 --- a/crates/stela-driver-net/src/wifi/security/wep.rs +++ b/crates/stela-driver-net/src/wifi/security/wep.rs @@ -5,20 +5,10 @@ //! mac80211 encrypts itself before any key reaches the hardware. use super::Cipher; +// The WEP ICV is `~crc32_le(~0, bytes)`, the IEEE CRC-32. +use stela_driver_core::crc::crc32_ieee as crc32; use zeroize::Zeroize; -/// `~crc32_le(~0, bytes)`, the WEP ICV and the 6 GHz short SSID. -pub fn crc32(bytes: &[u8]) -> u32 { - let mut crc = !0u32; - for &byte in bytes { - crc ^= u32::from(byte); - for _ in 0..8 { - crc = (crc >> 1) ^ if crc & 1 != 0 { 0xedb8_8320 } else { 0 }; - } - } - !crc -} - /// One static WEP key with its on-air index. #[derive(Clone, PartialEq, Eq)] pub struct Key { diff --git a/crates/stela-formats/src/apfs.rs b/crates/stela-formats/src/apfs.rs index 47bcef42a8..2971cd2309 100644 --- a/crates/stela-formats/src/apfs.rs +++ b/crates/stela-formats/src/apfs.rs @@ -16,6 +16,7 @@ use crate::payload::{ReadAt, gpt}; use alloc::{format, string::String, vec, vec::Vec}; use core::fmt; +use stela_contracts::bytes::{get_array, get_le16, get_le32, get_le64}; pub mod btree; pub mod container; @@ -68,42 +69,22 @@ pub type Result = core::result::Result; /// Little-endian field readers over a block; out-of-range reads are /// malformed structures. +const TRUNCATED: ApfsError = ApfsError::Malformed("truncated field"); + pub(crate) fn u16_at(bytes: &[u8], at: usize) -> Result { - Ok(u16::from_le_bytes( - bytes - .get(at..at + 2) - .ok_or(ApfsError::Malformed("truncated field"))? - .try_into() - .unwrap(), - )) + get_le16(bytes, at).ok_or(TRUNCATED) } pub(crate) fn u32_at(bytes: &[u8], at: usize) -> Result { - Ok(u32::from_le_bytes( - bytes - .get(at..at + 4) - .ok_or(ApfsError::Malformed("truncated field"))? - .try_into() - .unwrap(), - )) + get_le32(bytes, at).ok_or(TRUNCATED) } pub(crate) fn u64_at(bytes: &[u8], at: usize) -> Result { - Ok(u64::from_le_bytes( - bytes - .get(at..at + 8) - .ok_or(ApfsError::Malformed("truncated field"))? - .try_into() - .unwrap(), - )) + get_le64(bytes, at).ok_or(TRUNCATED) } pub(crate) fn uuid_at(bytes: &[u8], at: usize) -> Result<[u8; 16]> { - Ok(bytes - .get(at..at + 16) - .ok_or(ApfsError::Malformed("truncated field"))? - .try_into() - .unwrap()) + get_array(bytes, at).ok_or(TRUNCATED) } /// `uuid_t` in its canonical text form. diff --git a/crates/stela-formats/src/apfs/decmpfs.rs b/crates/stela-formats/src/apfs/decmpfs.rs index a92a07b8a6..b9d4eb1b1a 100644 --- a/crates/stela-formats/src/apfs/decmpfs.rs +++ b/crates/stela-formats/src/apfs/decmpfs.rs @@ -23,6 +23,7 @@ //! size. Other types are refused by number. use super::{ApfsError, Result}; use alloc::{vec, vec::Vec}; +use stela_contracts::bytes::{get_be32, get_le32}; /// The attribute holding the header. pub const ATTRIBUTE: &str = "com.apple.decmpfs"; @@ -142,18 +143,14 @@ fn append_chunk( Ok(()) } +const MALFORMED: ApfsError = ApfsError::Malformed("decmpfs resource fork"); + fn u32_le(bytes: &[u8], at: usize) -> Result { - bytes - .get(at..at + 4) - .map(|b| u32::from_le_bytes(b.try_into().expect("4 bytes"))) - .ok_or(ApfsError::Malformed("decmpfs resource fork")) + get_le32(bytes, at).ok_or(MALFORMED) } fn u32_be(bytes: &[u8], at: usize) -> Result { - bytes - .get(at..at + 4) - .map(|b| u32::from_be_bytes(b.try_into().expect("4 bytes"))) - .ok_or(ApfsError::Malformed("decmpfs resource fork")) + get_be32(bytes, at).ok_or(MALFORMED) } /// The resource fork's chunks, as byte ranges of `fork`. diff --git a/crates/stela-formats/src/code_signature.rs b/crates/stela-formats/src/code_signature.rs index 3107d1242e..267ae01a87 100644 --- a/crates/stela-formats/src/code_signature.rs +++ b/crates/stela-formats/src/code_signature.rs @@ -150,13 +150,11 @@ fn byte(bytes: &[u8], at: usize) -> Result { } fn be32(bytes: &[u8], at: usize) -> Result { - let b = extent(bytes, at, 4)?; - Ok(u32::from_be_bytes([b[0], b[1], b[2], b[3]])) + extent(bytes, at, 4).map(|field| stela_contracts::bytes::be32(field, 0)) } fn le32(bytes: &[u8], at: usize) -> Result { - let b = extent(bytes, at, 4)?; - Ok(u32::from_le_bytes([b[0], b[1], b[2], b[3]])) + extent(bytes, at, 4).map(|field| stela_contracts::bytes::le32(field, 0)) } fn c_string(bytes: &[u8], at: usize) -> Option { diff --git a/crates/stela-formats/src/lzfse.rs b/crates/stela-formats/src/lzfse.rs index 40aaddf9f6..53885f1cff 100644 --- a/crates/stela-formats/src/lzfse.rs +++ b/crates/stela-formats/src/lzfse.rs @@ -16,6 +16,7 @@ //! declared raw size, every literal and match must stay inside its block's //! literals and the bytes decoded so far, and nothing may follow `bvx$`. use alloc::vec::Vec; +use stela_contracts::bytes::{get_le16, get_le32, get_le64}; #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub enum LzfseError { @@ -91,24 +92,15 @@ const D_BASE_VALUE: [i32; D_SYMBOLS] = [ ]; fn u16_at(bytes: &[u8], at: usize) -> Result { - bytes - .get(at..at + 2) - .map(|b| u16::from_le_bytes(b.try_into().unwrap())) - .ok_or(LzfseError::Truncated) + get_le16(bytes, at).ok_or(LzfseError::Truncated) } fn u32_at(bytes: &[u8], at: usize) -> Result { - bytes - .get(at..at + 4) - .map(|b| u32::from_le_bytes(b.try_into().unwrap())) - .ok_or(LzfseError::Truncated) + get_le32(bytes, at).ok_or(LzfseError::Truncated) } fn u64_at(bytes: &[u8], at: usize) -> Result { - bytes - .get(at..at + 8) - .map(|b| u64::from_le_bytes(b.try_into().unwrap())) - .ok_or(LzfseError::Truncated) + get_le64(bytes, at).ok_or(LzfseError::Truncated) } /// The decoded output, bounded by the caller's limit. diff --git a/crates/stela-formats/src/payload/staging.rs b/crates/stela-formats/src/payload/staging.rs index 5406ab213a..52f22f6644 100644 --- a/crates/stela-formats/src/payload/staging.rs +++ b/crates/stela-formats/src/payload/staging.rs @@ -4,9 +4,10 @@ //! Stela writes the header last. A partition whose header is missing or //! damaged holds no usable payload, so an interrupted copy is never mistaken //! for a complete one. -use super::{PayloadError, PayloadManifest, ReadAt, gpt::crc32}; +use super::{PayloadError, PayloadManifest, ReadAt}; use alloc::{string::String, vec, vec::Vec}; use serde::{Deserialize, Serialize}; +use stela_contracts::crc::crc32_ieee as crc32; const MAGIC: &[u8; 16] = b"STELA-STAGING\0\0\x01"; /// The header area; members start after it. diff --git a/crates/stela-formats/src/payload/zip.rs b/crates/stela-formats/src/payload/zip.rs index e52e840efa..de714edd68 100644 --- a/crates/stela-formats/src/payload/zip.rs +++ b/crates/stela-formats/src/payload/zip.rs @@ -10,6 +10,7 @@ use miniz_oxide::inflate::{ TINFLStatus, core::{DecompressorOxide, decompress, inflate_flags::TINFL_FLAG_HAS_MORE_INPUT}, }; +use stela_contracts::bytes::{le16, le32, le64}; const END: u32 = 0x0605_4b50; const END64: u32 = 0x0606_4b50; @@ -50,18 +51,6 @@ pub struct Archive { entries: Vec, } -fn u16_at(bytes: &[u8], at: usize) -> u16 { - u16::from_le_bytes([bytes[at], bytes[at + 1]]) -} - -fn u32_at(bytes: &[u8], at: usize) -> u32 { - u32::from_le_bytes(bytes[at..at + 4].try_into().unwrap()) -} - -fn u64_at(bytes: &[u8], at: usize) -> u64 { - u64::from_le_bytes(bytes[at..at + 8].try_into().unwrap()) -} - fn corrupt(what: &'static str) -> PayloadError { PayloadError::Archive(what) } @@ -91,15 +80,15 @@ impl Archive { let end = (0..=tail.len() - END_BYTES) .rev() .find(|&at| { - u32_at(&tail, at) == END - && at + END_BYTES + u16_at(&tail, at + 20) as usize == tail.len() + le32(&tail, at) == END + && at + END_BYTES + le16(&tail, at + 20) as usize == tail.len() }) .ok_or(corrupt("no end of central directory record"))?; let record = &tail[end..]; - let mut count = u16_at(record, 10) as u64; - let mut size = u32_at(record, 12) as u64; - let mut start = u32_at(record, 16) as u64; - if u16_at(record, 4) != 0 || u16_at(record, 6) != 0 { + let mut count = le16(record, 10) as u64; + let mut size = le32(record, 12) as u64; + let mut start = le32(record, 16) as u64; + if le16(record, 4) != 0 || le16(record, 6) != 0 { return Err(corrupt("multi-disk archives are not supported")); } let end_offset = tail_start + end as u64; @@ -108,16 +97,16 @@ impl Archive { .checked_sub(LOCATOR_BYTES) .ok_or(corrupt("no ZIP64 locator"))?; let locator = read(reader, at, LOCATOR_BYTES as usize)?; - if u32_at(&locator, 0) != LOCATOR64 { + if le32(&locator, 0) != LOCATOR64 { return Err(corrupt("no ZIP64 locator")); } - let record = read(reader, u64_at(&locator, 8), 56)?; - if u32_at(&record, 0) != END64 { + let record = read(reader, le64(&locator, 8), 56)?; + if le32(&record, 0) != END64 { return Err(corrupt("no ZIP64 end record")); } - count = u64_at(&record, 32); - size = u64_at(&record, 40); - start = u64_at(&record, 48); + count = le64(&record, 32); + size = le64(&record, 40); + start = le64(&record, 48); } if size > MAX_DIRECTORY_BYTES || count > MAX_ENTRIES { return Err(corrupt("central directory exceeds limits")); @@ -126,28 +115,28 @@ impl Archive { let mut entries = Vec::with_capacity(count as usize); let mut at = 0usize; for _ in 0..count { - if at + CENTRAL_BYTES > directory.len() || u32_at(&directory, at) != CENTRAL { + if at + CENTRAL_BYTES > directory.len() || le32(&directory, at) != CENTRAL { return Err(corrupt("bad central directory entry")); } let header = &directory[at..]; - let flags = u16_at(header, 8); - let method = u16_at(header, 10); - let name_bytes = u16_at(header, 28) as usize; - let extra_bytes = u16_at(header, 30) as usize; - let comment_bytes = u16_at(header, 32) as usize; + let flags = le16(header, 8); + let method = le16(header, 10); + let name_bytes = le16(header, 28) as usize; + let extra_bytes = le16(header, 30) as usize; + let comment_bytes = le16(header, 32) as usize; let next = at + CENTRAL_BYTES + name_bytes + extra_bytes + comment_bytes; if next > directory.len() { return Err(corrupt("central directory entry overruns")); } let name = core::str::from_utf8(&header[CENTRAL_BYTES..CENTRAL_BYTES + name_bytes]) .map_err(|_| corrupt("member name is not UTF-8"))?; - let mut bytes = u32_at(header, 24) as u64; - let mut compressed_bytes = u32_at(header, 20) as u64; - let mut local_header = u32_at(header, 42) as u64; + let mut bytes = le32(header, 24) as u64; + let mut compressed_bytes = le32(header, 20) as u64; + let mut local_header = le32(header, 42) as u64; let mut extra = &header[CENTRAL_BYTES + name_bytes..][..extra_bytes]; while extra.len() >= 4 { - let id = u16_at(extra, 0); - let field = u16_at(extra, 2) as usize; + let id = le16(extra, 0); + let field = le16(extra, 2) as usize; let body = extra .get(4..4 + field) .ok_or(corrupt("extra field overruns"))?; @@ -181,8 +170,8 @@ impl Archive { method, compressed_bytes, bytes, - crc32: u32_at(header, 16), - unix_mode: (header[5] == 3).then(|| (u32_at(header, 38) >> 16) as u16), + crc32: le32(header, 16), + unix_mode: (header[5] == 3).then(|| (le32(header, 38) >> 16) as u16), local_header, }); at = next; @@ -263,13 +252,13 @@ impl Archive { entry: &Entry, ) -> Result { let local = read(reader, entry.local_header, LOCAL_BYTES)?; - if u32_at(&local, 0) != LOCAL { + if le32(&local, 0) != LOCAL { return Err(corrupt("bad local header")); } let data = entry.local_header + LOCAL_BYTES as u64 - + u16_at(&local, 26) as u64 - + u16_at(&local, 28) as u64; + + le16(&local, 26) as u64 + + le16(&local, 28) as u64; match data.checked_add(entry.compressed_bytes) { Some(end) if end <= reader.len() => {} _ => return Err(corrupt("member data past the end of the archive")), diff --git a/crates/stela-formats/src/payload/zip/test_support.rs b/crates/stela-formats/src/payload/zip/test_support.rs index 800f82d601..a5020fa20e 100644 --- a/crates/stela-formats/src/payload/zip/test_support.rs +++ b/crates/stela-formats/src/payload/zip/test_support.rs @@ -12,7 +12,7 @@ pub fn archive(members: &[(&str, &[u8], bool)], zip64: bool) -> Vec { data.to_vec() }; let offset = out.len() as u64; - let crc = crate::payload::gpt::crc32(data); + let crc = stela_contracts::crc::crc32_ieee(data); let method: u16 = if *deflate { 8 } else { 0 }; let small = |v: u64| if zip64 { 0xffff_ffff } else { v as u32 }; out.extend_from_slice(&LOCAL.to_le_bytes()); diff --git a/crates/stela-loader/src/chained_fixups.rs b/crates/stela-loader/src/chained_fixups.rs index 909c4ea6fb..418b371c18 100644 --- a/crates/stela-loader/src/chained_fixups.rs +++ b/crates/stela-loader/src/chained_fixups.rs @@ -6,7 +6,10 @@ use super::load_plan::{LoadPlan, SegmentPlan}; use crate::{Error, Result, Within}; use serde::Serialize; use std::collections::{BTreeMap, BTreeSet}; -use stela_contracts::{refuse, require}; +use stela_contracts::{ + bytes::{le16, le32, le64}, + refuse, require, +}; const COMMAND: u32 = 0x80000034; const MAX_FIXUPS: usize = 1_048_576; @@ -197,19 +200,13 @@ fn bytes(data: &[u8], offset: usize, length: usize) -> Result<&[u8]> { .ok_or(refuse!("truncated chained-fixup extent").into()) } fn u16_at(data: &[u8], offset: usize) -> Result { - Ok(u16::from_le_bytes( - bytes(data, offset, 2)?.try_into().unwrap(), - )) + bytes(data, offset, 2).map(|field| le16(field, 0)) } fn u32_at(data: &[u8], offset: usize) -> Result { - Ok(u32::from_le_bytes( - bytes(data, offset, 4)?.try_into().unwrap(), - )) + bytes(data, offset, 4).map(|field| le32(field, 0)) } fn u64_at(data: &[u8], offset: usize) -> Result { - Ok(u64::from_le_bytes( - bytes(data, offset, 8)?.try_into().unwrap(), - )) + bytes(data, offset, 8).map(|field| le64(field, 0)) } fn moved(address: u64, slide: i128, role: &str) -> Result { u64::try_from(i128::from(address) + slide) diff --git a/crates/stela-loader/src/coprocessor/configuration/finalization.rs b/crates/stela-loader/src/coprocessor/configuration/finalization.rs index 708bfd7c1f..bbde6efd91 100644 --- a/crates/stela-loader/src/coprocessor/configuration/finalization.rs +++ b/crates/stela-loader/src/coprocessor/configuration/finalization.rs @@ -7,7 +7,10 @@ use crate::Result; use crate::coprocessor::publication; use alloc::{collections::BTreeSet, string::String, vec::Vec}; use serde::Serialize; -use stela_contracts::{refuse, require}; +use stela_contracts::{ + bytes::{get_le32, get_le64}, + refuse, require, +}; use stela_formats::sha256; const DSEG: u32 = u32::from_le_bytes(*b"dseg"); @@ -40,24 +43,10 @@ pub struct Receipt { } fn u32_at(bytes: &[u8], at: usize) -> Result { - Ok(u32::from_le_bytes( - bytes - .get(at..) - .and_then(|b| b.get(..4)) - .ok_or(refuse!("truncated native finalization u32"))? - .try_into() - .unwrap(), - )) + get_le32(bytes, at).ok_or_else(|| refuse!("truncated native finalization u32").into()) } fn u64_at(bytes: &[u8], at: usize) -> Result { - Ok(u64::from_le_bytes( - bytes - .get(at..) - .and_then(|b| b.get(..8)) - .ok_or(refuse!("truncated native finalization u64"))? - .try_into() - .unwrap(), - )) + get_le64(bytes, at).ok_or_else(|| refuse!("truncated native finalization u64").into()) } fn snapshot(proposal: &publication::Proposal) -> Result { // The complete selected geometry/flags/provenance and omitted family stay diff --git a/crates/stela-loader/src/coprocessor/configuration/tuning/source.rs b/crates/stela-loader/src/coprocessor/configuration/tuning/source.rs index 929cdd747e..a6629726db 100644 --- a/crates/stela-loader/src/coprocessor/configuration/tuning/source.rs +++ b/crates/stela-loader/src/coprocessor/configuration/tuning/source.rs @@ -4,7 +4,10 @@ use crate::Result; use crate::coprocessor::configuration::Provenance; use alloc::{string::String, vec::Vec}; use serde::Serialize; -use stela_contracts::{refuse, require}; +use stela_contracts::{ + bytes::{get_le32, get_le64}, + refuse, require, +}; use stela_formats::sha256; const GROUP_BYTES: usize = 0x38; @@ -52,22 +55,10 @@ pub struct Selection { } fn u32_at(b: &[u8], at: usize) -> Result { - Ok(u32::from_le_bytes( - b.get(at..) - .and_then(|b| b.get(..4)) - .ok_or(refuse!("truncated native tuning u32"))? - .try_into() - .unwrap(), - )) + get_le32(b, at).ok_or_else(|| refuse!("truncated native tuning u32").into()) } fn u64_at(b: &[u8], at: usize) -> Result { - Ok(u64::from_le_bytes( - b.get(at..) - .and_then(|b| b.get(..8)) - .ok_or(refuse!("truncated native tuning pointer"))? - .try_into() - .unwrap(), - )) + get_le64(b, at).ok_or_else(|| refuse!("truncated native tuning pointer").into()) } fn slice(source: &[u8], at: u64, bytes: usize) -> Result<&[u8]> { source diff --git a/crates/stela-loader/src/gpu_dvfs.rs b/crates/stela-loader/src/gpu_dvfs.rs index 6487e6a55d..c157256da1 100644 --- a/crates/stela-loader/src/gpu_dvfs.rs +++ b/crates/stela-loader/src/gpu_dvfs.rs @@ -187,7 +187,7 @@ mod tests { } fn u32_at(value: &[u8], index: usize) -> u32 { - u32::from_le_bytes(value[index * 4..index * 4 + 4].try_into().unwrap()) + stela_contracts::bytes::le32(value, index * 4) } #[test] diff --git a/crates/stela-loader/src/kernel_collection.rs b/crates/stela-loader/src/kernel_collection.rs index 56a0ae0bf1..b8fd950f36 100644 --- a/crates/stela-loader/src/kernel_collection.rs +++ b/crates/stela-loader/src/kernel_collection.rs @@ -20,7 +20,7 @@ const SEGMENT_NAME_BYTES: usize = 16; /// `LC_FILESET_ENTRY` is `0x35 | LC_REQ_DYLD`. const LC_FILESET_ENTRY: u32 = macho::LC_FILESET_ENTRY; /// The arm64 kernel page; segment and region boundaries are multiples of it. -pub const PAGE_BYTES: u64 = 0x4000; +pub use stela_contracts::bytes::GUEST_PAGE_BYTES as PAGE_BYTES; const MAX_LOAD_COMMAND_BYTES: usize = 1 << 20; #[derive(Debug, Clone, PartialEq, Eq, Serialize)] diff --git a/crates/stela-loader/src/plugin.rs b/crates/stela-loader/src/plugin.rs index a5477e7b2a..946e25a4c0 100644 --- a/crates/stela-loader/src/plugin.rs +++ b/crates/stela-loader/src/plugin.rs @@ -20,8 +20,8 @@ use std::collections::{BTreeMap, HashMap}; use std::iter; use stela_contracts::{refuse, require}; -/// Segments align to the macOS arm64 page. -const PAGE: u64 = 0x4000; +// Segments align to the macOS arm64 page. +use stela_contracts::bytes::GUEST_PAGE_BYTES as PAGE; /// A signature hashes the file in units of this. const HASH_PAGE: u64 = 0x1000; const HASH_PAGE_SHIFT: u8 = 12; diff --git a/crates/stela-runtime/src/platform/pc/acpi.rs b/crates/stela-runtime/src/platform/pc/acpi.rs index 6f9cd3f3d4..a51b979a4f 100644 --- a/crates/stela-runtime/src/platform/pc/acpi.rs +++ b/crates/stela-runtime/src/platform/pc/acpi.rs @@ -2,6 +2,7 @@ //! MCFG table that locates PCI configuration space, and any table by //! address ([`power`](super::power) reads the FADT and DSDT). use alloc::vec::Vec; +use stela_contracts::bytes::{le32, le64}; use stela_drivers::bus::pci::EcamWindow; const HEADER: usize = 36; @@ -17,14 +18,6 @@ fn checksum(bytes: &[u8]) -> bool { bytes.iter().fold(0u8, |sum, byte| sum.wrapping_add(*byte)) == 0 } -fn u32_at(bytes: &[u8], offset: usize) -> u32 { - u32::from_le_bytes(bytes[offset..offset + 4].try_into().unwrap()) -} - -fn u64_at(bytes: &[u8], offset: usize) -> u64 { - u64::from_le_bytes(bytes[offset..offset + 8].try_into().unwrap()) -} - /// # Safety /// /// `address` must be readable, identity-mapped memory holding at least an @@ -33,7 +26,7 @@ pub unsafe fn table(address: u64) -> Result<&'static [u8], AcpiError> { // SAFETY: the caller's contract covers the header. let header = unsafe { core::slice::from_raw_parts(address as *const u8, HEADER) }; let signature: [u8; 4] = header[..4].try_into().unwrap(); - let length = u32_at(header, 4) as usize; + let length = le32(header, 4) as usize; if length < HEADER { return Err(AcpiError::BadTable(signature)); } @@ -62,19 +55,19 @@ pub unsafe fn find(rsdp: u64, signature: &[u8; 4]) -> Result<&'static [u8], Acpi if !checksum(long) { return Err(AcpiError::BadRsdp); } - match u64_at(long, 24) { - 0 => (u64::from(u32_at(short, 16)), 4), + match le64(long, 24) { + 0 => (u64::from(le32(short, 16)), 4), xsdt => (xsdt, 8), } } else { - (u64::from(u32_at(short, 16)), 4) + (u64::from(le32(short, 16)), 4) }; // SAFETY: the caller's contract. let root = unsafe { table(root)? }; for entry in root[HEADER..].chunks_exact(width) { let address = match width { - 8 => u64_at(entry, 0), - _ => u64::from(u32_at(entry, 0)), + 8 => le64(entry, 0), + _ => u64::from(le32(entry, 0)), }; // SAFETY: the caller's contract. let candidate = unsafe { table(address)? }; @@ -100,7 +93,7 @@ pub fn mcfg(table: &[u8]) -> Result, AcpiError> { .iter() .map(|entry| { let window = EcamWindow { - base: u64_at(entry, 0), + base: le64(entry, 0), segment: u16::from_le_bytes([entry[8], entry[9]]), start_bus: entry[10], end_bus: entry[11], diff --git a/crates/stela-runtime/src/platform/pc/board_flash.rs b/crates/stela-runtime/src/platform/pc/board_flash.rs index ee97cb4212..3b13602679 100644 --- a/crates/stela-runtime/src/platform/pc/board_flash.rs +++ b/crates/stela-runtime/src/platform/pc/board_flash.rs @@ -27,6 +27,7 @@ //! reports, and the next bundle that carries them writes them again. use alloc::{format, string::String, vec, vec::Vec}; use core::fmt; +use stela_contracts::bytes::le32; use stela_crypto::Sha256; use stela_crypto::digest::Digest; use stela_drivers::block::{BlockDevice, BlockError}; @@ -88,10 +89,6 @@ fn block_size(device: &dyn BlockDevice) -> Result { Ok(block) } -fn u32_at(bytes: &[u8], at: usize) -> u32 { - u32::from_le_bytes(bytes[at..at + 4].try_into().expect("four bytes")) -} - impl Flash { /// The flash on `device`, the region alone. pub fn read(device: &mut dyn BlockDevice) -> Result { @@ -101,13 +98,13 @@ impl Flash { if header.iter().all(|&byte| byte == 0) { return Ok(Self::default()); } - if &header[..8] != MAGIC || u32_at(&header, 8) != VERSION { + if &header[..8] != MAGIC || le32(&header, 8) != VERSION { return Err(Error::Invalid("the region is not board flash")); } if Sha256::digest(&header[..FIELDS])[..] != header[FIELDS..] { return Err(Error::Invalid("the board flash header fails its hash")); } - let count = u32_at(&header, 12) as usize; + let count = le32(&header, 12) as usize; if count > MAXIMUM_ENTRIES { return Err(Error::Invalid( "the board flash header lists too many images", @@ -127,7 +124,7 @@ impl Flash { .unwrap_or(NAME_BYTES); let name = core::str::from_utf8(&name[..end]) .map_err(|_| Error::Invalid("a board flash image's name is not text"))?; - let (offset, length) = (u32_at(rest, 0) as usize, u32_at(rest, 4) as usize); + let (offset, length) = (le32(rest, 0) as usize, le32(rest, 4) as usize); let aligned = length.next_multiple_of(block); if !offset.is_multiple_of(block) || offset < HEADER_BYTES diff --git a/crates/stela-runtime/src/platform/pc/power.rs b/crates/stela-runtime/src/platform/pc/power.rs index 660f49bde6..77f0436baa 100644 --- a/crates/stela-runtime/src/platform/pc/power.rs +++ b/crates/stela-runtime/src/platform/pc/power.rs @@ -34,6 +34,7 @@ use super::acpi::{self, AcpiError}; use crate::Result; use stela_contracts::Refusal; +use stela_contracts::bytes::{get_le32, get_le64}; use stela_contracts::refuse; const HEADER: usize = 36; @@ -192,22 +193,10 @@ pub fn sleep_register_control(sleep_type: u8) -> u8 { (sleep_type << SLEEP_REGISTER_TYPE_SHIFT) & SLEEP_REGISTER_TYPE | SLEEP_REGISTER_ENABLE } -fn u32_at(bytes: &[u8], offset: usize) -> Option { - Some(u32::from_le_bytes( - bytes.get(offset..offset + 4)?.try_into().ok()?, - )) -} - -fn u64_at(bytes: &[u8], offset: usize) -> Option { - Some(u64::from_le_bytes( - bytes.get(offset..offset + 8)?.try_into().ok()?, - )) -} - /// A Generic Address Structure: its space and address. fn gas(bytes: &[u8], offset: usize) -> Option<(u8, u64)> { let field = bytes.get(offset..offset + GAS_BYTES)?; - Some((field[0], u64_at(field, 4)?)) + Some((field[0], get_le64(field, 4)?)) } /// An I/O port block: the X_ field when present, else the 32-bit one @@ -219,7 +208,7 @@ fn port(fadt: &[u8], legacy: Option, extended: usize) -> Result legacy - .and_then(|legacy| u32_at(fadt, legacy)) + .and_then(|legacy| get_le32(fadt, legacy)) .map_or(0, u64::from), }; match address { @@ -231,7 +220,7 @@ fn port(fadt: &[u8], legacy: Option, extended: usize) -> Result Result> { - if u32_at(fadt, FLAGS).unwrap_or(0) & RESET_SUPPORTED == 0 { + if get_le32(fadt, FLAGS).unwrap_or(0) & RESET_SUPPORTED == 0 { return Ok(None); } let (Some((space, address)), Some(&value)) = (gas(fadt, RESET_REGISTER), fadt.get(RESET_VALUE)) @@ -266,14 +255,14 @@ pub fn fadt(table: &[u8]) -> Result<(HostPower, u64), AcpiError> { if table.len() < RESET_REGISTER || &table[..4] != b"FACP" { return Err(BAD); } - let flags = u32_at(table, FLAGS).ok_or(BAD)?; + let flags = get_le32(table, FLAGS).ok_or(BAD)?; let mut power = HostPower::default(); let mut refuse = |reason: Refusal| { power.refused.get_or_insert(reason); }; - let dsdt = match u64_at(table, X_DSDT) { + let dsdt = match get_le64(table, X_DSDT) { Some(address) if address != 0 => address, - _ => u64::from(u32_at(table, DSDT).ok_or(BAD)?), + _ => u64::from(get_le32(table, DSDT).ok_or(BAD)?), }; let mut reset = None; match reset_register(table) { @@ -358,7 +347,7 @@ fn integer(bytes: &[u8]) -> Option<(u64, usize)> { u64::from(u16::from_le_bytes(bytes.get(1..3)?.try_into().ok()?)), 3, )), - DWORD_PREFIX => Some((u64::from(u32_at(bytes, 1)?), 5)), + DWORD_PREFIX => Some((u64::from(get_le32(bytes, 1)?), 5)), _ => None, } } diff --git a/crates/stela-soc-data/src/pmgr/t6000/reconfiguration.rs b/crates/stela-soc-data/src/pmgr/t6000/reconfiguration.rs index f1c8b0a833..f75bb61d4e 100644 --- a/crates/stela-soc-data/src/pmgr/t6000/reconfiguration.rs +++ b/crates/stela-soc-data/src/pmgr/t6000/reconfiguration.rs @@ -212,16 +212,10 @@ fn relative(bytes: &[u8], offset: u64, length: u64) -> Result<&[u8], Error> { .ok_or(Error::Extent) } fn u32_at(bytes: &[u8], offset: usize) -> Result { - let word = bytes.get(offset..offset + 4).ok_or(Error::Extent)?; - Ok(u32::from_le_bytes( - word.try_into().map_err(|_| Error::Extent)?, - )) + stela_contracts::bytes::get_le32(bytes, offset).ok_or(Error::Extent) } fn u64_at(bytes: &[u8], offset: usize) -> Result { - let word = bytes.get(offset..offset + 8).ok_or(Error::Extent)?; - Ok(u64::from_le_bytes( - word.try_into().map_err(|_| Error::Extent)?, - )) + stela_contracts::bytes::get_le64(bytes, offset).ok_or(Error::Extent) } #[cfg(test)] diff --git a/crates/stela-soc/src/ans/bfh.rs b/crates/stela-soc/src/ans/bfh.rs index b4037aefdf..6580fbc542 100644 --- a/crates/stela-soc/src/ans/bfh.rs +++ b/crates/stela-soc/src/ans/bfh.rs @@ -33,8 +33,8 @@ pub(super) const SECTIONS: usize = 3; /// replace the image and activate it at the next reset (NVMe 1.4 figure /// 181). No other slot or action is ever sent. pub(super) const ACTIVATE_SLOT0_REPLACE: u32 = 1 << 3; -pub(super) use crate::checksum::crc32c; -use crate::checksum::crc32c_update as crc_update; +pub(super) use stela_contracts::crc::crc32c; +use stela_contracts::crc::crc32c_update as crc_update; /// A transferred byte string's identity. #[derive(Debug, Clone, PartialEq, Eq)] diff --git a/crates/stela-soc/src/checksum.rs b/crates/stela-soc/src/checksum.rs deleted file mode 100644 index e806093b6a..0000000000 --- a/crates/stela-soc/src/checksum.rs +++ /dev/null @@ -1,58 +0,0 @@ -//! Shared CRC32C/Castagnoli for protocols using the same checksum polynomial. -//! ANS BFH and Thunderbolt control traffic independently use this form. -const CASTAGNOLI: u32 = 0x82f6_3b78; -const CRC_TABLE: [u32; 256] = crc_table(); - -const fn crc_table() -> [u32; 256] { - let mut table = [0; 256]; - let mut i = 0; - while i < 256 { - let mut crc = i as u32; - let mut bit = 0; - while bit < 8 { - crc = if crc & 1 != 0 { - (crc >> 1) ^ CASTAGNOLI - } else { - crc >> 1 - }; - bit += 1; - } - table[i] = crc; - i += 1; - } - table -} - -pub(crate) fn crc32c_update(mut state: u32, data: &[u8]) -> u32 { - for &byte in data { - state = CRC_TABLE[((state ^ u32::from(byte)) & 0xff) as usize] ^ (state >> 8); - } - state -} - -/// Reflected CRC32C/Castagnoli, with all-ones initial state and final XOR. -/// The returned integer is independent of a protocol's wire byte order. -pub(crate) fn crc32c(data: &[u8]) -> u32 { - !crc32c_update(!0, data) -} - -#[cfg(test)] -mod tests { - use super::*; - #[test] - fn crc32c_matches_the_castagnoli_check_value_and_kernel_table() { - assert_eq!(crc32c(b"123456789"), 0xe306_9283); - // The kernel's table at file 0xb09000 starts 0, f26b8303, e13b70f7. - assert_eq!(CRC_TABLE[..3], [0, 0xf26b_8303, 0xe13b_70f7]); - assert_eq!(crc32c(&[]), 0); - } - - #[test] - fn incremental_state_matches_independent_castagnoli_vectors() { - assert_eq!(crc32c(&[0; 32]), 0x8a91_36aa); - assert_eq!(crc32c(&[0xff; 32]), 0x62a8_ab43); - let first = crc32c_update(!0, b"1234"); - assert_eq!(!crc32c_update(first, b"56789"), 0xe306_9283); - assert_eq!(crc32c_update(first, &[]), first); - } -} diff --git a/crates/stela-soc/src/lib.rs b/crates/stela-soc/src/lib.rs index d9128dc6c1..fb0f5b7158 100644 --- a/crates/stela-soc/src/lib.rs +++ b/crates/stela-soc/src/lib.rs @@ -21,7 +21,6 @@ use stela_contracts::interrupt; /// A refused request names the values that decided it. pub type Result = core::result::Result; -mod checksum; pub mod machine; #[cfg(test)] mod research; diff --git a/crates/stela-soc/src/research/nhi/control.rs b/crates/stela-soc/src/research/nhi/control.rs index 97cb95a6d0..7bfd7b04d6 100644 --- a/crates/stela-soc/src/research/nhi/control.rs +++ b/crates/stela-soc/src/research/nhi/control.rs @@ -4,8 +4,8 @@ //! fields and CRC32C; Reset and Error use the same framing. See the original //! address/source matrix in `docs/research/usb4-acio.md`. This codec supplies //! no register values, routing decisions, reset completion or acknowledgments. -use crate::checksum::crc32c; use alloc::vec::Vec; +use stela_contracts::crc::crc32c; const ROUTE_MASK: u64 = (1 << 54) - 1; const REPLY: u32 = 1 << 31; diff --git a/crates/stela-soc/src/sep/keystore.rs b/crates/stela-soc/src/sep/keystore.rs index 9b945db08e..442a2f890b 100644 --- a/crates/stela-soc/src/sep/keystore.rs +++ b/crates/stela-soc/src/sep/keystore.rs @@ -492,9 +492,7 @@ impl Environment { } fn u32_at(bytes: &[u8], at: usize) -> Result { - bytes - .get(at..at + 4) - .map(|word| u32::from_le_bytes(word.try_into().unwrap())) + stela_contracts::bytes::get_le32(bytes, at) .ok_or(refuse!("SEP keystore IPC message ends inside its header")) } diff --git a/crates/stela-soc/src/usb/storage.rs b/crates/stela-soc/src/usb/storage.rs index f39c2a2153..71a8cb8d42 100644 --- a/crates/stela-soc/src/usb/storage.rs +++ b/crates/stela-soc/src/usb/storage.rs @@ -32,6 +32,7 @@ use super::{ }; use crate::Result; use alloc::{boxed::Box, string::String, vec, vec::Vec}; +use stela_contracts::bytes::{be16, be32, be64}; use stela_contracts::refuse; use stela_drivers::block::BlockDevice; @@ -284,16 +285,6 @@ impl MassStorage { } } -fn be16(cdb: &[u8], at: usize) -> u16 { - u16::from_be_bytes([cdb[at], cdb[at + 1]]) -} -fn be32(cdb: &[u8], at: usize) -> u32 { - u32::from_be_bytes(cdb[at..at + 4].try_into().unwrap()) -} -fn be64(cdb: &[u8], at: usize) -> u64 { - u64::from_be_bytes(cdb[at..at + 8].try_into().unwrap()) -} - impl State { fn block_size(&self) -> u64 { u64::from(self.device.identity().block_size) diff --git a/xtask/src/boot/audio_check.rs b/xtask/src/boot/audio_check.rs index d4d9d7e838..ab8cb5ceb9 100644 --- a/xtask/src/boot/audio_check.rs +++ b/xtask/src/boot/audio_check.rs @@ -11,6 +11,7 @@ use std::{ thread, time::{Duration, Instant}, }; +use stela_contracts::bytes::{le16, le32}; use stela_formats::sha256; const RING_BYTES: usize = 16_384; @@ -320,13 +321,6 @@ fn serial(mode: Mode, serial: &str) -> Result { ) } -fn le16(bytes: &[u8], offset: usize) -> u16 { - u16::from_le_bytes(bytes[offset..offset + 2].try_into().unwrap()) -} -fn le32(bytes: &[u8], offset: usize) -> u32 { - u32::from_le_bytes(bytes[offset..offset + 4].try_into().unwrap()) -} - /// Parse finalized RIFF, including size and format, before comparing audio. fn wav(bytes: &[u8]) -> Result<&[u8]> { ensure!(