refactor: share CRC-32 and byte-field readers through stela-contracts

This commit is contained in:
Tyler Smith committed 2026-11-10 09:38:05 +00:00
1 parent 94659cb94f
commit 0ece6a35b4
53 files changed
+297 -411

No files matched your search

Generated
+2
View File
@@ -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 = [
+1 -1
View File
@@ -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;
@@ -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;
@@ -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 {
+1 -1
View File
@@ -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;
@@ -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;
+1 -1
View File
@@ -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;
+1 -1
View File
@@ -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;
+1 -1
View File
@@ -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 {
+1
View File
@@ -1063,6 +1063,7 @@ dependencies = [
name = "stela-driver-core"
version = "0.1.0"
dependencies = [
"stela-contracts",
"stela-crypto",
]
+6 -11
View File
@@ -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<u64> {
/// (name, value) of every property of a node.
type Properties<'a> = Vec<(&'a [u8], &'a [u8])>;
fn u32_at(data: &[u8], offset: usize) -> Option<u32> {
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<Property<'_>> {
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> {
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());
}
+67
View File
@@ -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<const N: usize>(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<const N: usize>(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);
}
}
+77
View File
@@ -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);
}
}
+2
View File
@@ -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;
@@ -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 {
@@ -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<Encoded, Error>
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
@@ -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<u8>,
pub entries: Vec<Entry>,
@@ -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());
}
@@ -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 { .. })));
+1
View File
@@ -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]
-43
View File
@@ -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<u16> {
Some(u16::from_le_bytes(get_field(bytes, at)?))
}
pub fn get_le32(bytes: &[u8], at: usize) -> Option<u32> {
Some(u32::from_le_bytes(get_field(bytes, at)?))
}
fn field<const N: usize>(bytes: &[u8], at: usize) -> [u8; N] {
bytes[at..at + N].try_into().unwrap()
}
fn get_field<const N: usize>(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);
}
}
+2 -1
View File
@@ -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;
@@ -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" }
+4 -9
View File
@@ -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<u16> {
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<u32> {
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<u64> {
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<usize> {
+4 -11
View File
@@ -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
}
@@ -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)
@@ -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<u16, ParseError> {
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<u32, ParseError> {
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 {
@@ -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<u16, Error> {
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<u32, Error> {
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<usize, Error> {
Ok(usize::from(be16(data, at)?) * 4)
@@ -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`.
@@ -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 {
+7 -26
View File
@@ -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<T> = core::result::Result<T, ApfsError>;
/// 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<u16> {
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<u32> {
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<u64> {
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.
+5 -8
View File
@@ -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<u32> {
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<u32> {
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`.
+2 -4
View File
@@ -150,13 +150,11 @@ fn byte(bytes: &[u8], at: usize) -> Result<u8> {
}
fn be32(bytes: &[u8], at: usize) -> Result<u32> {
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<u32> {
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<String> {
+4 -12
View File
@@ -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<u16> {
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<u32> {
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<u64> {
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.
+2 -1
View File
@@ -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.
+29 -40
View File
@@ -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<Entry>,
}
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<Progress, PayloadError> {
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")),
@@ -12,7 +12,7 @@ pub fn archive(members: &[(&str, &[u8], bool)], zip64: bool) -> Vec<u8> {
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());
+7 -10
View File
@@ -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<u16> {
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<u32> {
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<u64> {
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> {
u64::try_from(i128::from(address) + slide)
@@ -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<u32> {
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<u64> {
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<String> {
// The complete selected geometry/flags/provenance and omitted family stay
@@ -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<u32> {
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<u64> {
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
+1 -1
View File
@@ -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]
+1 -1
View File
@@ -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)]
+2 -2
View File
@@ -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;
+8 -15
View File
@@ -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<Vec<EcamWindow>, 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],
@@ -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<usize, Error> {
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<Self, Error> {
@@ -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
+8 -19
View File
@@ -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<u32> {
Some(u32::from_le_bytes(
bytes.get(offset..offset + 4)?.try_into().ok()?,
))
}
fn u64_at(bytes: &[u8], offset: usize) -> Option<u64> {
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<usize>, extended: usize) -> Result<Option<u1
return Err(refuse!("an ACPI register block outside system I/O space"));
}
_ => 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<usize>, extended: usize) -> Result<Option<u1
}
fn reset_register(fadt: &[u8]) -> Result<Option<(ResetRegister, u8)>> {
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,
}
}
@@ -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<u32, Error> {
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<u64, Error> {
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)]
+2 -2
View File
@@ -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)]
-58
View File
@@ -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);
}
}
-1
View File
@@ -21,7 +21,6 @@ use stela_contracts::interrupt;
/// A refused request names the values that decided it.
pub type Result<T, E = Refusal> = core::result::Result<T, E>;
mod checksum;
pub mod machine;
#[cfg(test)]
mod research;
+1 -1
View File
@@ -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;
+1 -3
View File
@@ -492,9 +492,7 @@ impl Environment {
}
fn u32_at(bytes: &[u8], at: usize) -> Result<u32> {
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"))
}
+1 -10
View File
@@ -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)
+1 -7
View File
@@ -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<Value> {
)
}
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!(