diff --git a/src/fdt.rs b/src/fdt.rs index dd20b35..4a39f66 100644 --- a/src/fdt.rs +++ b/src/fdt.rs @@ -271,8 +271,7 @@ impl<'a> Tree<'a> for Fdt<'a> { type Node = FdtNode<'a>; fn root(self) -> FdtNode<'a> { - let offset = self.header().off_dt_struct() as usize; - FdtNode::new(self, offset) + FdtNode::new(self, self.header().off_dt_struct()) } } @@ -537,11 +536,12 @@ impl<'a> Fdt<'a> { self.validate_mem_reservations()?; // Validate structure block - let offset = header.off_dt_struct() as usize; + let off_dt_struct = header.off_dt_struct(); + let offset = off_dt_struct as usize; // Check root node self.expect_token(offset, FdtToken::BeginNode)?; - let end_offset = self.validate_structure(offset, options)?; + let end_offset = self.validate_structure(off_dt_struct, options)?; // Check FDT_END self.expect_token(end_offset, FdtToken::End)?; @@ -582,7 +582,7 @@ impl<'a> Fdt<'a> { } fn validate_structure( self, - start_offset: usize, + start_offset: u32, options: &FdtOptions, ) -> Result { let mut cursor = RawSubtreeCursor::new(start_offset); @@ -891,23 +891,6 @@ impl<'a> Fdt<'a> { } } - pub(crate) fn next_sibling_offset(self, offset: usize) -> Result { - RawSubtreeCursor::new(offset).end_offset(self) - } - - pub(crate) fn next_property_offset(self, offset: usize) -> Result { - let (header, _) = FdtPropertyHeader::ref_from_prefix(self.data_at_offset(offset)?) - .map_err(|_e| FdtParseError::new(FdtErrorKind::InvalidLength, offset))?; - - let len = header.len() as usize; - let prop_offset = offset + size_of::(); - if len > self.data.len() - prop_offset { - return Err(FdtParseError::new(FdtErrorKind::InvalidLength, prop_offset)); - } - - Ok(Self::align_tag_offset(prop_offset + len)) - } - pub(crate) fn data_at_offset(&self, offset: usize) -> Result<&[u8], FdtParseError> { self.data .get(offset..) diff --git a/src/fdt/node.rs b/src/fdt/node.rs index 05efc49..70d05f1 100644 --- a/src/fdt/node.rs +++ b/src/fdt/node.rs @@ -10,7 +10,7 @@ use core::fmt::{self, Display, Formatter}; -use super::{FDT_TAGSIZE, Fdt, FdtToken}; +use super::Fdt; use crate::Node; use crate::fdt::event::FdtEventIter; use crate::fdt::property::{FdtPropIter, FdtProperty}; @@ -22,7 +22,7 @@ use crate::util::write_indent; #[derive(Debug, Clone, Copy)] pub struct FdtNode<'a> { pub(crate) fdt: Fdt<'a>, - pub(crate) offset: usize, + pub(crate) offset: u32, /// The `#address-cells` and `#size-cells` properties of this node's parent /// node. pub(crate) parent_address_space: AddressSpaceProperties, @@ -41,7 +41,7 @@ impl<'a> Node<'a> for FdtNode<'a> { /// [`Fdt::new_unchecked`] or [`Fdt::from_raw_unchecked`] and the FDT is not /// valid. fn name(self) -> &'a str { - RawCursor::from_usize(self.offset) + RawCursor::new(self.offset) .enter_node(self.fdt) .expect("Fdt should be valid") .name(self.fdt) @@ -51,12 +51,15 @@ impl<'a> Node<'a> for FdtNode<'a> { FdtPropIter::new(self.fdt, self.offset) } + /// Returns an iterator over the children of this node. + /// + /// # Panics + /// + /// Panics if the [`Fdt`] structure was constructed using + /// [`Fdt::new_unchecked`] or [`Fdt::from_raw_unchecked`] and the FDT is not + /// valid. fn children(self) -> private::FdtChildIter<'a> { - private::FdtChildIter { - fdt: self.fdt, - inner: InnerChildIter::new(self.offset), - parent_address_space: self.address_space(), - } + private::FdtChildIter::new(self.fdt, self.offset, self.address_space()) } fn parent_address_space(self) -> AddressSpaceProperties { @@ -65,7 +68,7 @@ impl<'a> Node<'a> for FdtNode<'a> { } impl<'a> FdtNode<'a> { - pub(crate) fn new(fdt: Fdt<'a>, offset: usize) -> Self { + pub(crate) fn new(fdt: Fdt<'a>, offset: u32) -> Self { Self { fdt, offset, @@ -101,7 +104,7 @@ impl<'a> FdtNode<'a> { /// ``` #[must_use] pub fn offset(self) -> usize { - self.offset - self.fdt.header().off_dt_struct() as usize + self.offset as usize - self.fdt.header().off_dt_struct() as usize } /// Returns an iterator over the events in the structure block of the @@ -203,97 +206,41 @@ impl Display for FdtNode<'_> { } } -#[derive(Debug, Clone)] -pub(crate) enum InnerChildIter { - Start { offset: usize }, - Running { offset: usize }, -} - -impl InnerChildIter { - #[must_use] - pub(crate) fn new(offset: usize) -> Self { - Self::Start { offset } - } - - #[must_use] - pub(crate) fn next(&mut self, fdt: Fdt<'_>) -> Option { - match self { - Self::Start { offset } => { - let mut off = *offset; - off += FDT_TAGSIZE; // Skip FDT_BEGIN_NODE - off = fdt.find_string_end(off).expect("Fdt should be valid"); - off = Fdt::align_tag_offset(off); - - let result = Self::skip_props(fdt, &mut off); - *self = Self::Running { offset: off }; - result - } - Self::Running { offset } => Self::next_child_parsed(fdt, offset), - } - } - - #[must_use] - fn skip_props(fdt: Fdt<'_>, offset: &mut usize) -> Option { - loop { - let token = fdt.read_token(*offset).expect("Fdt should be valid"); - match token { - FdtToken::BeginNode => return Some(*offset), - FdtToken::Prop => { - *offset = fdt - .next_property_offset(*offset) - .expect("Fdt should be valid"); - } - FdtToken::EndNode | FdtToken::End => return None, - FdtToken::Nop => *offset += FDT_TAGSIZE, - } - } - } - - #[must_use] - fn next_child_parsed(fdt: Fdt<'_>, offset: &mut usize) -> Option { - // advance past the child unless it was removed or iteration ended - if fdt.read_token(*offset).expect("Fdt should be valid") == FdtToken::BeginNode { - *offset = fdt - .next_sibling_offset(*offset) - .expect("Fdt should be valid"); - } - loop { - let token = fdt.read_token(*offset).expect("Fdt should be valid"); - match token { - FdtToken::BeginNode => { - return Some(*offset); - } - FdtToken::Prop => { - panic!("Fdt should be valid"); - } - FdtToken::EndNode | FdtToken::End => return None, - FdtToken::Nop => *offset += FDT_TAGSIZE, - } - } - } -} - pub(crate) mod private { - use crate::fdt::node::InnerChildIter; + use crate::fdt::raw::CursorState; use crate::fdt::{Fdt, FdtNode}; use crate::standard::AddressSpaceProperties; /// An iterator over the children of a device tree node. #[derive(Debug, Clone)] pub struct FdtChildIter<'a> { - pub(crate) fdt: Fdt<'a>, - pub(crate) inner: InnerChildIter, - pub(crate) parent_address_space: AddressSpaceProperties, + fdt: Fdt<'a>, + state: CursorState, + parent_address_space: AddressSpaceProperties, + } + + impl<'a> FdtChildIter<'a> { + pub(super) const fn new( + fdt: Fdt<'a>, + parent_offset: u32, + parent_address_space: AddressSpaceProperties, + ) -> Self { + Self { + fdt, + state: CursorState::Start(parent_offset), + parent_address_space, + } + } } impl<'a> Iterator for FdtChildIter<'a> { type Item = FdtNode<'a>; fn next(&mut self) -> Option { - let node_offset = self.inner.next(self.fdt)?; + let offset = self.state.next_child(self.fdt)?; Some(FdtNode { fdt: self.fdt, - offset: node_offset, + offset, parent_address_space: self.parent_address_space, }) } diff --git a/src/fdt/property.rs b/src/fdt/property.rs index 60c40ce..40ea4c9 100644 --- a/src/fdt/property.rs +++ b/src/fdt/property.rs @@ -123,10 +123,10 @@ pub struct FdtPropIter<'a> { } impl<'a> FdtPropIter<'a> { - pub(crate) fn new(fdt: Fdt<'a>, node_offset: usize) -> Self { + pub(crate) const fn new(fdt: Fdt<'a>, node_offset: u32) -> Self { Self { fdt, - state: CursorState::start(node_offset), + state: CursorState::Start(node_offset), } } } diff --git a/src/fdt/raw.rs b/src/fdt/raw.rs index 63678c5..9a48e0a 100644 --- a/src/fdt/raw.rs +++ b/src/fdt/raw.rs @@ -34,25 +34,22 @@ impl RawCursor { Self { offset } } - /// Creates a cursor at `offset`. - /// - /// # Panics - /// - /// Panics if `offset` does not fit in `u32`. - pub(crate) fn from_usize(offset: usize) -> Self { - Self { - offset: u32::try_from(offset).expect("Fdt should be valid"), - } - } - /// Constructs a cursor inside the node body at `node_offset` (after the /// `FDT_BEGIN_NODE` tag and the node name). - pub(crate) fn node_body(fdt: Fdt<'_>, node_offset: usize) -> Result { - let mut cursor = Self::from_usize(node_offset); + pub(crate) fn node_body(fdt: Fdt<'_>, node_offset: u32) -> Result { + let mut cursor = Self::new(node_offset); cursor.enter_node(fdt)?; Ok(cursor) } + /// Constructs a cursor at the first child (or `FDT_END_NODE`) of the node + /// at `parent_offset`. + fn node_children(fdt: Fdt<'_>, parent_offset: u32) -> Result { + let mut cursor = Self::node_body(fdt, parent_offset)?; + cursor.skip_properties(fdt)?; + Ok(cursor) + } + pub(crate) const fn offset(self) -> usize { self.offset as usize } @@ -191,6 +188,33 @@ impl RawCursor { } Ok(prop) } + + /// Peeks the next child node, stopping at it, or returns `None` at + /// `FDT_END_NODE`. + fn peek_child(&mut self, fdt: Fdt<'_>) -> Result, FdtParseError> { + match self.skip_nops_and_read_token(fdt)? { + FdtToken::BeginNode => Ok(Some(self.offset)), + FdtToken::EndNode => Ok(None), + FdtToken::Nop => unreachable!("unbounded NOP skip stops at a non-NOP token"), + other => Err(FdtParseError::new( + FdtErrorKind::BadToken(other.tag()), + self.offset(), + )), + } + } + + /// Skips consecutive `FDT_PROP` (and NOP) tokens. + fn skip_properties(&mut self, fdt: Fdt<'_>) -> Result<(), FdtParseError> { + while self.next_property(fdt)?.is_some() {} + Ok(()) + } + + /// Skips the node subtree at `self.offset`, stopping after its matching + /// `FDT_END_NODE`. + fn skip_node(&mut self, fdt: Fdt<'_>) -> Result<(), FdtParseError> { + let end = RawSubtreeCursor::new(self.offset).end_offset(fdt)?; + self.set_offset(end) + } } fn checked_u32(val: usize, kind: FdtErrorKind, offset: usize) -> Result { @@ -362,41 +386,60 @@ pub(crate) enum CursorState { } impl CursorState { - pub(crate) fn start(offset: usize) -> Self { - Self::Start(u32::try_from(offset).expect("Fdt should be valid")) - } - - pub(crate) fn next_property(&mut self, fdt: Fdt<'_>) -> Option { + fn step( + &mut self, + init: impl FnOnce(u32) -> Result, + advance: impl FnOnce(&mut RawCursor) -> Result<(), FdtParseError>, + read: impl FnOnce(&mut RawCursor) -> Result, FdtParseError>, + ) -> Option { let mut cursor = match core::mem::replace(self, Self::Done) { - Self::Start(off) => { - RawCursor::node_body(fdt, off as usize).expect("Fdt should be valid") + Self::Start(off) => init(off).expect("Fdt should be valid"), + Self::Active(mut c) => { + advance(&mut c).expect("Fdt should be valid"); + c } - Self::Active(c) => c, Self::Done => return None, }; - let prop = cursor.next_property(fdt).expect("Fdt should be valid")?; + let item = read(&mut cursor).expect("Fdt should be valid")?; *self = Self::Active(cursor); - Some(prop) + Some(item) + } + + pub(crate) fn next_property(&mut self, fdt: Fdt<'_>) -> Option { + self.step( + |off| RawCursor::node_body(fdt, off), + |_| Ok(()), + |c| c.next_property(fdt), + ) } pub(crate) fn next_property_mut(&mut self, fdt: Fdt<'_>) -> Option { - let mut cursor = match core::mem::replace(self, Self::Done) { - Self::Start(off) => { - RawCursor::node_body(fdt, off as usize).expect("Fdt should be valid") - } - Self::Active(mut c) => { + self.step( + |off| RawCursor::node_body(fdt, off), + |c| { c.skip_yielded(fdt, |c| { assert!(c.next_property(fdt)?.is_some(), "Fdt should be valid"); Ok(()) }) - .expect("Fdt should be valid"); - c - } - Self::Done => return None, - }; - let prop = cursor.peek_property(fdt).expect("Fdt should be valid")?; - *self = Self::Active(cursor); - Some(prop) + }, + |c| c.peek_property(fdt), + ) + } + + pub(crate) fn next_child(&mut self, fdt: Fdt<'_>) -> Option { + self.step( + |parent| RawCursor::node_children(fdt, parent), + |c| c.skip_node(fdt), + |c| c.peek_child(fdt), + ) + } + + pub(crate) fn next_child_mut(&mut self, fdt: Fdt<'_>) -> Option { + self.step( + |parent| RawCursor::node_children(fdt, parent), + |c| c.skip_yielded(fdt, |c| c.skip_node(fdt)), + |c| c.peek_child(fdt), + ) } } @@ -409,9 +452,9 @@ pub(crate) struct RawSubtreeCursor { } impl RawSubtreeCursor { - pub(crate) fn new(node_offset: usize) -> Self { + pub(crate) const fn new(node_offset: u32) -> Self { Self { - cursor: RawCursor::from_usize(node_offset), + cursor: RawCursor::new(node_offset), depth: 0, state: RawSubtreeCursorState::InsideNodes, } diff --git a/src/fdt_mut/node.rs b/src/fdt_mut/node.rs index e3ecf4f..c5fac51 100644 --- a/src/fdt_mut/node.rs +++ b/src/fdt_mut/node.rs @@ -12,10 +12,9 @@ use core::fmt::{Display, Formatter}; use zerocopy::IntoBytes; use crate::error::FdtMutError; -use crate::fdt::node::InnerChildIter; use crate::fdt::node::private::FdtChildIter; use crate::fdt::property::FdtPropIter; -use crate::fdt::raw::{RawCursor, RawProperty}; +use crate::fdt::raw::{RawCursor, RawProperty, RawSubtreeCursor}; use crate::fdt::{ FDT_BEGIN_NODE, FDT_END_NODE, FDT_TAGSIZE, Fdt, FdtNode, FdtProperty, FdtPropertyHeader, }; @@ -30,7 +29,7 @@ use crate::{Node, ToPropertyValue, Tree}; #[derive(Debug)] pub struct FdtNodeMut<'a, B: FdtBuffer> { pub(crate) data: &'a mut FdtMut, - pub(crate) offset: usize, + pub(crate) offset: u32, pub(crate) parent_address_space: AddressSpaceProperties, } @@ -83,17 +82,15 @@ impl FdtNodeMut<'_, B> { /// assert_eq!(child.name(), "c"); /// ``` pub fn child_mut(&mut self, name: &str) -> Option> { - let mut children = self.children_mut(); - while let Some(child) = children.next() { - if child.name() == name { - return Some(FdtNodeMut { - offset: child.offset, - parent_address_space: child.parent_address_space, - data: self.data, - }); - } - } - None + let child = self + .as_read_only() + .children() + .find(|child| child.name() == name)?; + Some(FdtNodeMut { + offset: child.offset, + parent_address_space: child.parent_address_space, + data: self.data, + }) } /// Adds a new property to this node. @@ -237,11 +234,10 @@ impl FdtNodeMut<'_, B> { let node = self.as_read_only(); let parent_address_space = node.address_space(); - let insert_offset = node - .fdt - .next_sibling_offset(self.offset) - .expect("Fdt should be valid") - - FDT_TAGSIZE; + let end_offset = RawSubtreeCursor::new(self.offset) + .end_offset(node.fdt) + .expect("Fdt should be valid"); + let insert_offset = end_offset - FDT_TAGSIZE; let required_space = (name.len() + 1).next_multiple_of(FDT_TAGSIZE) + 2 * FDT_TAGSIZE; self.data @@ -261,7 +257,7 @@ impl FdtNodeMut<'_, B> { .expect("slot is large enough"); Ok(FdtNodeMut { - offset: insert_offset, + offset: u32::try_from(insert_offset).expect("offset fits in u32"), parent_address_space, data: self.data, }) @@ -337,15 +333,15 @@ impl FdtNodeMut<'_, B> { /// is not valid. pub fn remove(self) -> Result<(), FdtMutError> { let fdt = self.data.as_read_only(); - let start = self.offset; - if start == fdt.root().offset { + if self.offset == fdt.root().offset { return Err(FdtMutError::RemoveRootNode); } - let end = fdt - .next_sibling_offset(self.offset) + let end_offset = RawSubtreeCursor::new(self.offset) + .end_offset(fdt) .expect("Fdt should be valid"); - self.data.replace_with_nops(start, end); + self.data + .replace_with_nops(self.offset as usize, end_offset); Ok(()) } @@ -355,13 +351,14 @@ impl FdtNodeMut<'_, B> { } /// Returns a mutable iterator over the children of this node. + /// + /// # Panics + /// + /// Panics if the [`FdtMut`] structure was constructed using an + /// `*_unchecked` constructor and the FDT is not valid. pub fn children_mut(&mut self) -> private::FdtChildMutIter<'_, B> { let address_space = self.as_read_only().address_space(); - private::FdtChildMutIter { - inner: InnerChildIter::new(self.offset), - parent_address_space: address_space, - data: self.data, - } + private::FdtChildMutIter::new(self.data, self.offset, address_space) } /// Returns a read only view of this node. @@ -402,7 +399,7 @@ impl Display for FdtNodeMut<'_, B> { } pub(crate) mod private { - use crate::fdt::node::InnerChildIter; + use crate::fdt::raw::CursorState; use crate::fdt_mut::buffer::FdtBuffer; use crate::fdt_mut::{FdtMut, FdtNodeMut}; use crate::standard::AddressSpaceProperties; @@ -410,22 +407,33 @@ pub(crate) mod private { /// A mutable iterator over the children of a device tree node. #[derive(Debug)] pub struct FdtChildMutIter<'a, B: FdtBuffer> { - pub(crate) data: &'a mut FdtMut, - pub(crate) parent_address_space: AddressSpaceProperties, - pub(crate) inner: InnerChildIter, + data: &'a mut FdtMut, + parent_address_space: AddressSpaceProperties, + state: CursorState, } - impl FdtChildMutIter<'_, B> { + impl<'a, B: FdtBuffer> FdtChildMutIter<'a, B> { + pub(super) const fn new( + data: &'a mut FdtMut, + parent_offset: u32, + parent_address_space: AddressSpaceProperties, + ) -> Self { + Self { + data, + parent_address_space, + state: CursorState::Start(parent_offset), + } + } + /// Returns the next mutable child. /// /// # Panics /// /// Panics if the underlying device tree data is invalid. pub fn next(&mut self) -> Option> { - let fdt = self.data.as_read_only(); - let node_offset = self.inner.next(fdt)?; + let offset = self.state.next_child_mut(self.data.as_read_only())?; Some(FdtNodeMut { - offset: node_offset, + offset, parent_address_space: self.parent_address_space, data: self.data, }) diff --git a/src/fdt_mut/property.rs b/src/fdt_mut/property.rs index 6e141d8..e12d886 100644 --- a/src/fdt_mut/property.rs +++ b/src/fdt_mut/property.rs @@ -178,10 +178,10 @@ pub struct FdtPropMutIter<'a, B: FdtBuffer> { } impl<'a, B: FdtBuffer> FdtPropMutIter<'a, B> { - pub(super) fn new(data: &'a mut FdtMut, node_offset: usize) -> Self { + pub(super) const fn new(data: &'a mut FdtMut, node_offset: u32) -> Self { Self { data, - state: CursorState::start(node_offset), + state: CursorState::Start(node_offset), } }