Browse Source

Initial commit

Wesley Norris 4 years ago
commit
152f8787d1
14 changed files with 1958 additions and 0 deletions
  1. 2 0
      .gitignore
  2. 16 0
      Cargo.toml
  3. 343 0
      LICENSE
  4. 21 0
      README.md
  5. 22 0
      examples/basic_info.rs
  6. 18 0
      examples/tree_print.rs
  7. 1 0
      rustfmt.toml
  8. 316 0
      src/lib.rs
  9. 492 0
      src/node.rs
  10. 97 0
      src/parsing.rs
  11. 293 0
      src/standard_nodes.rs
  12. 146 0
      src/tests.rs
  13. BIN
      test.dtb
  14. 191 0
      test.dts

+ 2 - 0
.gitignore

@@ -0,0 +1,2 @@
+Cargo.lock
+target/

+ 16 - 0
Cargo.toml

@@ -0,0 +1,16 @@
+[package]
+name = "fdt"
+version = "0.1.0"
+authors = ["Wesley Norris <[email protected]>"]
+edition = "2018"
+
+repository = "https://github.com/repnop/fdt"
+
+license = "MPL-2.0"
+
+description = "A pure-Rust crate for parsing Flattened Devicetrees"
+keywords = ["devicetree", "fdt", "dt"]
+categories = ["embedded", "no-std"]
+readme = "README.md"
+
+[dependencies]

+ 343 - 0
LICENSE

@@ -0,0 +1,343 @@
+Mozilla Public License Version 2.0
+
+1. Definitions
+
+1.1. “Contributor”
+
+    means each individual or legal entity that creates, contributes to the
+    creation of, or owns Covered Software.
+
+1.2. “Contributor Version”
+
+    means the combination of the Contributions of others (if any) used by a
+    Contributor and that particular Contributor’s Contribution.
+
+1.3. “Contribution”
+
+    means Covered Software of a particular Contributor.
+
+1.4. “Covered Software”
+
+    means Source Code Form to which the initial Contributor has attached the
+    notice in Exhibit A, the Executable Form of such Source Code Form, and
+    Modifications of such Source Code Form, in each case including portions
+    thereof.
+
+1.5. “Incompatible With Secondary Licenses”
+
+    means that the initial Contributor has attached the notice described in
+    Exhibit B to the Covered Software; or
+
+    that the Covered Software was made available under the terms of version 1.1
+    or earlier of the License, but not also under the terms of a Secondary
+    License.
+
+1.6. “Executable Form”
+
+    means any form of the work other than Source Code Form.
+
+1.7. “Larger Work”
+
+    means a work that combines Covered Software with other material, in a
+    separate file or files, that is not Covered Software.
+
+1.8. “License”
+
+    means this document.
+
+1.9. “Licensable”
+
+    means having the right to grant, to the maximum extent possible, whether at
+    the time of the initial grant or subsequently, any and all of the rights
+    conveyed by this License.
+
+1.10. “Modifications”
+
+    means any of the following:
+
+        any file in Source Code Form that results from an addition to, deletion
+        from, or modification of the contents of Covered Software; or
+
+        any new file in Source Code Form that contains any Covered Software.
+
+1.11. “Patent Claims” of a Contributor
+
+    means any patent claim(s), including without limitation, method, process,
+    and apparatus claims, in any patent Licensable by such Contributor that
+    would be infringed, but for the grant of the License, by the making, using,
+    selling, offering for sale, having made, import, or transfer of either its
+    Contributions or its Contributor Version.
+
+1.12. “Secondary License”
+
+    means either the GNU General Public License, Version 2.0, the GNU Lesser
+    General Public License, Version 2.1, the GNU Affero General Public License,
+    Version 3.0, or any later versions of those licenses.
+
+1.13. “Source Code Form”
+
+    means the form of the work preferred for making modifications.
+
+1.14. “You” (or “Your”)
+
+    means an individual or a legal entity exercising rights under this License.
+    For legal entities, “You” includes any entity that controls, is controlled
+    by, or is under common control with You. For purposes of this definition,
+    “control” means (a) the power, direct or indirect, to cause the direction or
+    management of such entity, whether by contract or otherwise, or (b)
+    ownership of more than fifty percent (50%) of the outstanding shares or
+    beneficial ownership of such entity.
+
+2. License Grants and Conditions 
+
+    2.1. Grants
+
+        Each Contributor hereby grants You a world-wide, royalty-free, non-exclusive
+        license:
+
+            under intellectual property rights (other than patent or trademark)
+            Licensable by such Contributor to use, reproduce, make available, modify,
+            display, perform, distribute, and otherwise exploit its Contributions,
+            either on an unmodified basis, with Modifications, or as part of a Larger
+            Work; and
+
+            under Patent Claims of such Contributor to make, use, sell, offer for sale,
+            have made, import, and otherwise transfer either its Contributions or its
+            Contributor Version.
+
+    2.2. Effective Date
+
+        The licenses granted in Section 2.1 with respect to any Contribution become
+        effective for each Contribution on the date the Contributor first distributes
+        such Contribution. 
+
+    2.3. Limitations on Grant Scope
+
+        The licenses granted in this Section 2 are the only rights granted under this
+        License. No additional rights or licenses will be implied from the distribution
+        or licensing of Covered Software under this License. Notwithstanding Section
+        2.1(b) above, no patent license is granted by a Contributor:
+
+            for any code that a Contributor has removed from Covered Software; or
+
+            for infringements caused by: (i) Your and any other third party’s
+            modifications of Covered Software, or (ii) the combination of its
+            Contributions with other software (except as part of its Contributor
+            Version); or
+
+            under Patent Claims infringed by Covered Software in the absence of its
+            Contributions.
+
+        This License does not grant any rights in the trademarks, service marks, or
+        logos of any Contributor (except as may be necessary to comply with the notice
+        requirements in Section 3.4). 
+
+    2.4. Subsequent Licenses
+
+        No Contributor makes additional grants as a result of Your choice to distribute
+        the Covered Software under a subsequent version of this License (see Section
+        10.2) or under the terms of a Secondary License (if permitted under the terms of
+        Section 3.3). 
+
+    2.5. Representation
+
+        Each Contributor represents that the Contributor believes its Contributions are
+        its original creation(s) or it has sufficient rights to grant the rights to its
+        Contributions conveyed by this License. 
+
+    2.6. Fair Use
+
+        This License is not intended to limit any rights You have under applicable
+        copyright doctrines of fair use, fair dealing, or other equivalents.
+
+    2.7. Conditions
+
+        Sections 3.1, 3.2, 3.3, and 3.4 are conditions of the licenses granted in
+        Section 2.1.
+
+3. Responsibilities
+
+    3.1. Distribution of Source Form
+
+        All distribution of Covered Software in Source Code Form, including any
+        Modifications that You create or to which You contribute, must be under the
+        terms of this License. You must inform recipients that the Source Code Form of
+        the Covered Software is governed by the terms of this License, and how they can
+        obtain a copy of this License. You may not attempt to alter or restrict the
+        recipients’ rights in the Source Code Form.
+
+    3.2. Distribution of Executable Form
+
+        If You distribute Covered Software in Executable Form then:
+
+            such Covered Software must also be made available in Source Code Form, as
+            described in Section 3.1, and You must inform recipients of the Executable
+            Form how they can obtain a copy of such Source Code Form by reasonable means
+            in a timely manner, at a charge no more than the cost of distribution to the
+            recipient; and
+
+            You may distribute such Executable Form under the terms of this License, or
+            sublicense it under different terms, provided that the license for the
+            Executable Form does not attempt to limit or alter the recipients’ rights in
+            the Source Code Form under this License.
+
+    3.3. Distribution of a Larger Work
+
+        You may create and distribute a Larger Work under terms of Your choice, provided
+        that You also comply with the requirements of this License for the Covered
+        Software. If the Larger Work is a combination of Covered Software with a work
+        governed by one or more Secondary Licenses, and the Covered Software is not
+        Incompatible With Secondary Licenses, this License permits You to additionally
+        distribute such Covered Software under the terms of such Secondary License(s),
+        so that the recipient of the Larger Work may, at their option, further
+        distribute the Covered Software under the terms of either this License or such
+        Secondary License(s). 
+
+    3.4. Notices
+
+        You may not remove or alter the substance of any license notices (including
+        copyright notices, patent notices, disclaimers of warranty, or limitations of
+        liability) contained within the Source Code Form of the Covered Software, except
+        that You may alter any license notices to the extent required to remedy known
+        factual inaccuracies. 
+
+    3.5. Application of Additional Terms
+
+        You may choose to offer, and to charge a fee for, warranty, support, indemnity
+        or liability obligations to one or more recipients of Covered Software. However,
+        You may do so only on Your own behalf, and not on behalf of any Contributor. You
+        must make it absolutely clear that any such warranty, support, indemnity, or
+        liability obligation is offered by You alone, and You hereby agree to indemnify
+        every Contributor for any liability incurred by such Contributor as a result of
+        warranty, support, indemnity or liability terms You offer. You may include
+        additional disclaimers of warranty and limitations of liability specific to any
+        jurisdiction. 
+
+4. Inability to Comply Due to Statute or Regulation
+
+    If it is impossible for You to comply with any of the terms of this License with
+    respect to some or all of the Covered Software due to statute, judicial order,
+    or regulation then You must: (a) comply with the terms of this License to the
+    maximum extent possible; and (b) describe the limitations and the code they
+    affect. Such description must be placed in a text file included with all
+    distributions of the Covered Software under this License. Except to the extent
+    prohibited by statute or regulation, such description must be sufficiently
+    detailed for a recipient of ordinary skill to be able to understand it. 
+
+5. Termination
+
+    5.1. The rights granted under this License will terminate automatically if You
+    fail to comply with any of its terms. However, if You become compliant, then the
+    rights granted under this License from a particular Contributor are reinstated
+    (a) provisionally, unless and until such Contributor explicitly and finally
+    terminates Your grants, and (b) on an ongoing basis, if such Contributor fails
+    to notify You of the non-compliance by some reasonable means prior to 60 days
+    after You have come back into compliance. Moreover, Your grants from a
+    particular Contributor are reinstated on an ongoing basis if such Contributor
+    notifies You of the non-compliance by some reasonable means, this is the first
+    time You have received notice of non-compliance with this License from such
+    Contributor, and You become compliant prior to 30 days after Your receipt of the
+    notice.
+
+    5.2. If You initiate litigation against any entity by asserting a patent
+    infringement claim (excluding declaratory judgment actions, counter-claims, and
+    cross-claims) alleging that a Contributor Version directly or indirectly
+    infringes any patent, then the rights granted to You by any and all Contributors
+    for the Covered Software under Section 2.1 of this License shall terminate.
+
+    5.3. In the event of termination under Sections 5.1 or 5.2 above, all end user
+    license agreements (excluding distributors and resellers) which have been
+    validly granted by You or Your distributors under this License prior to
+    termination shall survive termination.
+
+6. Disclaimer of Warranty
+
+    Covered Software is provided under this License on an “as is” basis, without
+    warranty of any kind, either expressed, implied, or statutory, including,
+    without limitation, warranties that the Covered Software is free of defects,
+    merchantable, fit for a particular purpose or non-infringing. The entire risk as
+    to the quality and performance of the Covered Software is with You. Should any
+    Covered Software prove defective in any respect, You (not any Contributor)
+    assume the cost of any necessary servicing, repair, or correction. This
+    disclaimer of warranty constitutes an essential part of this License. No use of
+    any Covered Software is authorized under this License except under this
+    disclaimer.
+
+7. Limitation of Liability
+
+    Under no circumstances and under no legal theory, whether tort (including
+    negligence), contract, or otherwise, shall any Contributor, or anyone who
+    distributes Covered Software as permitted above, be liable to You for any
+    direct, indirect, special, incidental, or consequential damages of any character
+    including, without limitation, damages for lost profits, loss of goodwill, work
+    stoppage, computer failure or malfunction, or any and all other commercial
+    damages or losses, even if such party shall have been informed of the
+    possibility of such damages. This limitation of liability shall not apply to
+    liability for death or personal injury resulting from such party’s negligence to
+    the extent applicable law prohibits such limitation. Some jurisdictions do not
+    allow the exclusion or limitation of incidental or consequential damages, so
+    this exclusion and limitation may not apply to You.
+
+8. Litigation
+
+    Any litigation relating to this License may be brought only in the courts of a
+    jurisdiction where the defendant maintains its principal place of business and
+    such litigation shall be governed by laws of that jurisdiction, without
+    reference to its conflict-of-law provisions. Nothing in this Section shall
+    prevent a party’s ability to bring cross-claims or counter-claims.
+
+9. Miscellaneous
+
+    This License represents the complete agreement concerning the subject matter
+    hereof. If any provision of this License is held to be unenforceable, such
+    provision shall be reformed only to the extent necessary to make it enforceable.
+    Any law or regulation which provides that the language of a contract shall be
+    construed against the drafter shall not be used to construe this License against
+    a Contributor.
+
+10. Versions of the License
+
+    10.1. New Versions
+
+        Mozilla Foundation is the license steward. Except as provided in Section 10.3,
+        no one other than the license steward has the right to modify or publish new
+        versions of this License. Each version will be given a distinguishing version
+        number.
+
+    10.2. Effect of New Versions
+
+        You may distribute the Covered Software under the terms of the version of the
+        License under which You originally received the Covered Software, or under the
+        terms of any subsequent version published by the license steward. 
+
+    10.3. Modified Versions
+
+        If you create software not governed by this License, and you want to create a
+        new license for such software, you may create and use a modified version of this
+        License if you rename the license and remove any references to the name of the
+        license steward (except to note that such modified license differs from this
+        License).
+
+    10.4. Distributing Source Code Form that is Incompatible With Secondary Licenses
+
+        If You choose to distribute Source Code Form that is Incompatible With Secondary
+        Licenses under the terms of this version of the License, the notice described in
+        Exhibit B of this License must be attached.
+
+        Exhibit A - Source Code Form License Notice
+
+            This Source Code Form is subject to the terms of the Mozilla Public License,
+            v. 2.0. If a copy of the MPL was not distributed with this file, You can
+            obtain one at https://mozilla.org/MPL/2.0/.
+
+        If it is not possible or desirable to put the notice in a particular file, then
+        You may include the notice in a location (such as a LICENSE file in a relevant
+        directory) where a recipient would be likely to look for such a notice.
+
+        You may add additional accurate notices of copyright ownership.
+
+        Exhibit B - “Incompatible With Secondary Licenses” Notice
+
+            This Source Code Form is “Incompatible With Secondary Licenses”, as defined
+            by the Mozilla Public License, v. 2.0.
+

+ 21 - 0
README.md

@@ -0,0 +1,21 @@
+# `fdt`
+
+A pure-Rust crate for parsing Flattened Devicetrees, with the goal of having a
+very ergonomic and idiomatic API.
+
+## License
+
+This crate is licensed under the Mozilla Public License 2.0 (see the LICENSE file).
+
+## Example
+
+```rust
+static MY_FDT: &[u8] = include_bytes!("my_fdt.dtb");
+
+fn main() {
+    let fdt = fdt::Fdt::new(MY_FDT).unwrap();
+
+    println!("This is a devicetree representation of a {}", fdt.root().model());
+    println!("...Which is compatible with: {}", fdt.root().compatible().join(","));
+}
+```

+ 22 - 0
examples/basic_info.rs

@@ -0,0 +1,22 @@
+static MY_FDT: &[u8] = include_bytes!("../test.dtb");
+
+fn main() {
+    let fdt = fdt::Fdt::new(MY_FDT).unwrap();
+
+    println!("This is a devicetree representation of a {}", fdt.root().model());
+    println!("...which is compatible with at least: {}", fdt.root().compatible().first());
+    println!(
+        "...and has at least one memory location at: {:#X}\n",
+        fdt.memory().regions().next().unwrap().starting_address as usize
+    );
+
+    let chosen = fdt.chosen();
+
+    if let Some(bootargs) = chosen.bootargs() {
+        println!("The bootargs are: {:?}", bootargs);
+    }
+
+    if let Some(stdout) = chosen.stdout() {
+        println!("It would write to: {}", stdout.name);
+    }
+}

+ 18 - 0
examples/tree_print.rs

@@ -0,0 +1,18 @@
+use fdt::node::FdtNode;
+
+static MY_FDT: &[u8] = include_bytes!("../test.dtb");
+
+fn main() {
+    let fdt = fdt::Fdt::new(MY_FDT).unwrap();
+
+    print_node(fdt.find_node("/").unwrap(), 0);
+}
+
+fn print_node(node: FdtNode<'_, '_>, n_spaces: usize) {
+    (0..n_spaces).for_each(|_| print!(" "));
+    println!("{}/", node.name);
+
+    for child in node.children() {
+        print_node(child, n_spaces + 4);
+    }
+}

+ 1 - 0
rustfmt.toml

@@ -0,0 +1 @@
+use_small_heuristics = "Max"

+ 316 - 0
src/lib.rs

@@ -0,0 +1,316 @@
+// This Source Code Form is subject to the terms of the Mozilla Public License,
+// v. 2.0. If a copy of the MPL was not distributed with this file, You can
+// obtain one at https://mozilla.org/MPL/2.0/.
+
+#![no_std]
+
+#[cfg(test)]
+mod tests;
+
+pub mod node;
+mod parsing;
+pub mod standard_nodes;
+
+use node::MemoryReservation;
+use parsing::{BigEndianU32, CStr, FdtData};
+use standard_nodes::{Aliases, Chosen, Cpu, Memory, MemoryRegion, Root};
+
+/// Possible errors when attempting to create an `Fdt`
+#[derive(Debug, Clone, Copy, PartialEq)]
+pub enum FdtError {
+    /// The FDT had an invalid magic value
+    BadMagic,
+    /// The given pointer was null
+    BadPtr,
+    /// The slice passed in was too small to fit the given total size of the FDT
+    /// structure
+    BufferTooSmall,
+}
+
+impl core::fmt::Display for FdtError {
+    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
+        match self {
+            FdtError::BadMagic => write!(f, "bad FDT magic value"),
+            FdtError::BadPtr => write!(f, "an invalid pointer was passed"),
+            FdtError::BufferTooSmall => {
+                write!(f, "the given buffer was too small to contain a FDT header")
+            }
+        }
+    }
+}
+
+/// A flattened devicetree located somewhere in memory
+#[derive(Debug, Clone, Copy)]
+pub struct Fdt<'a> {
+    data: &'a [u8],
+    header: FdtHeader,
+}
+
+#[derive(Debug, Clone, Copy)]
+#[repr(C)]
+struct FdtHeader {
+    /// FDT header magic
+    magic: BigEndianU32,
+    /// Total size in bytes of the FDT structure
+    totalsize: BigEndianU32,
+    /// Offset in bytes from the start of the header to the structure block
+    off_dt_struct: BigEndianU32,
+    /// Offset in bytes from the start of the header to the strings block
+    off_dt_strings: BigEndianU32,
+    /// Offset in bytes from the start of the header to the memory reservation
+    /// block
+    off_mem_rsvmap: BigEndianU32,
+    /// FDT version
+    version: BigEndianU32,
+    /// Last compatible FDT version
+    last_comp_version: BigEndianU32,
+    /// System boot CPU ID
+    boot_cpuid_phys: BigEndianU32,
+    /// Length in bytes of the strings block
+    size_dt_strings: BigEndianU32,
+    /// Length in bytes of the struct block
+    size_dt_struct: BigEndianU32,
+}
+
+impl FdtHeader {
+    fn valid_magic(&self) -> bool {
+        self.magic.get() == 0xd00dfeed
+    }
+
+    fn struct_range(&self) -> core::ops::Range<usize> {
+        let start = self.off_dt_struct.get() as usize;
+        let end = start + self.size_dt_struct.get() as usize;
+
+        start..end
+    }
+
+    fn strings_range(&self) -> core::ops::Range<usize> {
+        let start = self.off_dt_strings.get() as usize;
+        let end = start + self.size_dt_strings.get() as usize;
+
+        start..end
+    }
+
+    fn from_bytes(bytes: &mut FdtData<'_>) -> Option<Self> {
+        Some(Self {
+            magic: bytes.u32()?,
+            totalsize: bytes.u32()?,
+            off_dt_struct: bytes.u32()?,
+            off_dt_strings: bytes.u32()?,
+            off_mem_rsvmap: bytes.u32()?,
+            version: bytes.u32()?,
+            last_comp_version: bytes.u32()?,
+            boot_cpuid_phys: bytes.u32()?,
+            size_dt_strings: bytes.u32()?,
+            size_dt_struct: bytes.u32()?,
+        })
+    }
+}
+
+impl<'a> Fdt<'a> {
+    /// Construct a new `Fdt` from a byte buffer
+    pub fn new(data: &'a [u8]) -> Result<Self, FdtError> {
+        let mut stream = FdtData::new(data);
+        let header = FdtHeader::from_bytes(&mut stream).ok_or(FdtError::BufferTooSmall)?;
+
+        if !header.valid_magic() {
+            return Err(FdtError::BadMagic);
+        } else if data.len() < header.totalsize.get() as usize {
+            return Err(FdtError::BufferTooSmall);
+        }
+
+        Ok(Self { data, header })
+    }
+
+    /// # Safety
+    /// This function performs a read to verify the magic value. If the pointer
+    /// is invalid this can result in undefined behavior.
+    pub unsafe fn from_ptr(ptr: *const u8) -> Result<Self, FdtError> {
+        if ptr.is_null() {
+            return Err(FdtError::BadPtr);
+        }
+
+        let tmp_header = core::slice::from_raw_parts(ptr, core::mem::size_of::<FdtHeader>());
+        let real_size =
+            FdtHeader::from_bytes(&mut FdtData::new(tmp_header)).unwrap().totalsize.get() as usize;
+
+        Self::new(core::slice::from_raw_parts(ptr, real_size))
+    }
+
+    /// Return the `/aliases` node, if one exists
+    pub fn aliases(&self) -> Option<Aliases<'_, 'a>> {
+        Some(Aliases {
+            node: node::find_node(&mut FdtData::new(self.structs_block()), "/aliases", self, None)?,
+            header: self,
+        })
+    }
+
+    /// Searches for the `/chosen` node, which is always available
+    pub fn chosen(&self) -> Chosen<'_, 'a> {
+        node::find_node(&mut FdtData::new(self.structs_block()), "/chosen", self, None)
+            .map(|node| Chosen { node })
+            .expect("/chosen is required")
+    }
+
+    /// Return the `/cpus` node, which is always available
+    pub fn cpus(&self) -> impl Iterator<Item = Cpu<'_, 'a>> {
+        let parent = self.find_node("/cpus").expect("/cpus is a required node");
+
+        parent
+            .children()
+            .filter(|c| c.name.split('@').next().unwrap() == "cpu")
+            .map(move |cpu| Cpu { parent, node: cpu })
+    }
+
+    /// Returns the memory node, which is always available
+    pub fn memory(&self) -> Memory<'_, 'a> {
+        Memory { node: self.find_node("/memory").expect("requires memory node") }
+    }
+
+    /// Returns an iterator over the memory reservations
+    pub fn memory_reservations(&self) -> impl Iterator<Item = MemoryReservation> + 'a {
+        let mut stream = FdtData::new(&self.data[self.header.off_mem_rsvmap.get() as usize..]);
+        let mut done = false;
+
+        core::iter::from_fn(move || {
+            if stream.is_empty() || done {
+                return None;
+            }
+
+            let res = MemoryReservation::from_bytes(&mut stream)?;
+
+            if res.address() as usize == 0 && res.size() == 0 {
+                done = true;
+                return None;
+            }
+
+            Some(res)
+        })
+    }
+
+    /// Return the root (`/`) node, which is always available
+    pub fn root(&self) -> Root<'_, 'a> {
+        Root { node: self.find_node("/").expect("/ is a required node") }
+    }
+
+    /// Returns the first node that matches the node path, if you want all that
+    /// match the path, use `find_all_nodes`. This will automatically attempt to
+    /// resolve aliases if `path` is not found.
+    ///
+    /// Note: if the address of a node name is left out, the search will find
+    /// the first node that has a matching name, ignoring the address portion if
+    /// it exists.
+    pub fn find_node(&self, path: &str) -> Option<node::FdtNode<'_, 'a>> {
+        let node = node::find_node(&mut FdtData::new(self.structs_block()), path, self, None);
+        node.or_else(|| self.aliases()?.resolve_node(path))
+    }
+
+    /// Searches for a node which contains a `compatible` property and contains
+    /// one of the strings inside of `with`
+    pub fn find_compatible(&self, with: &[&str]) -> Option<node::FdtNode<'_, 'a>> {
+        self.all_nodes().find(|n| {
+            n.compatible().and_then(|compats| compats.all().find(|c| with.contains(&c))).is_some()
+        })
+    }
+
+    /// Searches for the given `phandle`
+    pub fn find_phandle(&self, phandle: u32) -> Option<node::FdtNode<'_, 'a>> {
+        self.all_nodes().find(|n| {
+            n.properties()
+                .find(|p| p.name == "phandle")
+                .and_then(|p| Some(BigEndianU32::from_bytes(p.value)?.get() == phandle))
+                .unwrap_or(false)
+        })
+    }
+
+    /// Returns an iterator over all of the available nodes with the given path.
+    ///
+    /// Note: if the address of a node name is left out, the search will find
+    /// all nodes that have a matching name, ignoring the address portion.
+    pub fn find_all_nodes(&self, path: &'a str) -> impl Iterator<Item = node::FdtNode<'_, 'a>> {
+        let mut done = false;
+        let only_root = path == "/";
+        let valid_path = path.chars().fold(0, |acc, c| acc + if c == '/' { 1 } else { 0 }) >= 1;
+
+        let mut path_split = path.rsplitn(2, '/');
+        let child_name = path_split.next().unwrap();
+        let parent_path = match path_split.next().unwrap() {
+            "" => "/",
+            s => s,
+        };
+        let parent =
+            node::find_node(&mut FdtData::new(self.structs_block()), parent_path, self, None);
+        let (parent, bad_parent) = match parent {
+            Some(parent) => (parent, false),
+            None => (self.find_node("/").unwrap(), true),
+        };
+
+        let mut child_iter = parent.children();
+
+        core::iter::from_fn(move || {
+            if done || !valid_path || bad_parent {
+                return None;
+            }
+
+            if only_root {
+                done = true;
+                return self.find_node("/");
+            }
+
+            let mut ret = None;
+
+            #[allow(clippy::while_let_on_iterator)]
+            while let Some(child) = child_iter.next() {
+                if child.name.split('@').next()? == child_name {
+                    ret = Some(child);
+                    break;
+                }
+            }
+
+            ret
+        })
+    }
+
+    /// Returns an iterator over all of the nodes in the devicetree, depth-first
+    pub fn all_nodes(&self) -> impl Iterator<Item = node::FdtNode<'_, 'a>> {
+        node::all_nodes(self)
+    }
+
+    /// Returns an iterator over all of the strings inside of the strings block
+    pub fn strings(&self) -> impl Iterator<Item = &'a str> {
+        let mut block = self.strings_block();
+
+        core::iter::from_fn(move || {
+            if block.is_empty() {
+                return None;
+            }
+
+            let cstr = CStr::new(block)?;
+
+            block = &block[cstr.len() + 1..];
+
+            cstr.as_str()
+        })
+    }
+
+    /// Total size of the devicetree in bytes
+    pub fn total_size(&self) -> usize {
+        self.header.totalsize.get() as usize
+    }
+
+    fn cstr_at_offset(&self, offset: usize) -> CStr<'a> {
+        CStr::new(&self.strings_block()[offset..]).expect("no null terminating string on C str?")
+    }
+
+    fn str_at_offset(&self, offset: usize) -> &'a str {
+        self.cstr_at_offset(offset).as_str().expect("not utf-8 cstr")
+    }
+
+    fn strings_block(&self) -> &'a [u8] {
+        &self.data[self.header.strings_range()]
+    }
+
+    fn structs_block(&self) -> &'a [u8] {
+        &self.data[self.header.struct_range()]
+    }
+}

+ 492 - 0
src/node.rs

@@ -0,0 +1,492 @@
+// This Source Code Form is subject to the terms of the Mozilla Public License,
+// v. 2.0. If a copy of the MPL was not distributed with this file, You can
+// obtain one at https://mozilla.org/MPL/2.0/.
+
+use crate::{
+    parsing::{BigEndianU32, BigEndianU64, CStr, FdtData},
+    standard_nodes::{Compatible, MemoryRegion},
+    Fdt,
+};
+
+const FDT_BEGIN_NODE: u32 = 1;
+const FDT_END_NODE: u32 = 2;
+const FDT_PROP: u32 = 3;
+pub(crate) const FDT_NOP: u32 = 4;
+const FDT_END: u32 = 5;
+
+#[derive(Debug, Clone, Copy)]
+#[repr(C)]
+struct FdtProperty {
+    len: BigEndianU32,
+    name_offset: BigEndianU32,
+}
+
+impl FdtProperty {
+    fn from_bytes(bytes: &mut FdtData<'_>) -> Option<Self> {
+        let len = bytes.u32()?;
+        let name_offset = bytes.u32()?;
+
+        Some(Self { len, name_offset })
+    }
+}
+
+/// A devicetree node
+#[derive(Debug, Clone, Copy)]
+pub struct FdtNode<'b, 'a: 'b> {
+    pub name: &'a str,
+    pub(crate) header: &'b Fdt<'a>,
+    props: &'a [u8],
+    parent_props: Option<&'a [u8]>,
+}
+
+impl<'b, 'a: 'b> FdtNode<'b, 'a> {
+    fn new(
+        name: &'a str,
+        header: &'b Fdt<'a>,
+        props: &'a [u8],
+        parent_props: Option<&'a [u8]>,
+    ) -> Self {
+        Self { name, header, props, parent_props }
+    }
+
+    /// Returns an iterator over the available properties of the node
+    pub fn properties(self) -> impl Iterator<Item = NodeProperty<'a>> + 'b {
+        let mut stream = FdtData::new(self.props);
+        let mut done = false;
+
+        core::iter::from_fn(move || {
+            if stream.is_empty() || done {
+                return None;
+            }
+
+            while stream.peek_u32()?.get() == FDT_NOP {
+                stream.skip(4);
+            }
+
+            if stream.peek_u32().unwrap().get() == FDT_PROP {
+                Some(NodeProperty::parse(&mut stream, self.header))
+            } else {
+                done = true;
+                None
+            }
+        })
+    }
+
+    /// Attempts to find the a property by its name
+    pub fn property(self, name: &str) -> Option<NodeProperty<'a>> {
+        self.properties().find(|p| p.name == name)
+    }
+
+    /// Returns an iterator over the children of the current node
+    pub fn children(self) -> impl Iterator<Item = FdtNode<'b, 'a>> {
+        let mut stream = FdtData::new(self.props);
+
+        while stream.peek_u32().unwrap().get() == FDT_NOP {
+            stream.skip(4);
+        }
+
+        while stream.peek_u32().unwrap().get() == FDT_PROP {
+            NodeProperty::parse(&mut stream, self.header);
+        }
+
+        let mut done = false;
+
+        core::iter::from_fn(move || {
+            if stream.is_empty() || done {
+                return None;
+            }
+
+            while stream.peek_u32()?.get() == FDT_NOP {
+                stream.skip(4);
+            }
+
+            if stream.peek_u32()?.get() == FDT_BEGIN_NODE {
+                let origin = stream.remaining();
+                let ret = {
+                    stream.skip(4);
+                    let unit_name = CStr::new(stream.remaining()).expect("unit name").as_str()?;
+                    let full_name_len = unit_name.len() + 1;
+                    stream.skip(full_name_len);
+
+                    if full_name_len % 4 != 0 {
+                        stream.skip(4 - (full_name_len % 4));
+                    }
+
+                    Some(Self::new(unit_name, self.header, stream.remaining(), Some(self.props)))
+                };
+
+                stream = FdtData::new(origin);
+
+                skip_current_node(&mut stream, self.header);
+
+                ret
+            } else {
+                done = true;
+                None
+            }
+        })
+    }
+
+    /// `reg` property
+    pub fn reg(self) -> Option<impl Iterator<Item = crate::MemoryRegion> + 'a> {
+        let sizes = self.cell_sizes();
+        if sizes.address_cells > 2 || sizes.size_cells > 2 {
+            todo!("address-cells and size-cells > 2 u32s not supported yet");
+        }
+
+        let mut reg = None;
+        for prop in self.properties() {
+            if prop.name == "reg" {
+                let mut stream = FdtData::new(prop.value);
+                reg = Some(core::iter::from_fn(move || {
+                    let starting_address = match sizes.address_cells {
+                        1 => stream.u32()?.get() as usize,
+                        2 => stream.u64()?.get() as usize,
+                        _ => return None,
+                    } as *const u8;
+
+                    let size = match sizes.size_cells {
+                        0 => None,
+                        1 => Some(stream.u32()?.get() as usize),
+                        2 => Some(stream.u64()?.get() as usize),
+                        _ => return None,
+                    };
+
+                    Some(MemoryRegion { starting_address, size })
+                }));
+                break;
+            }
+        }
+
+        reg
+    }
+
+    /// `compatible` property
+    pub fn compatible(self) -> Option<Compatible<'a>> {
+        let mut s = None;
+        for prop in self.properties() {
+            if prop.name == "compatible" {
+                s = Some(Compatible { data: prop.value });
+            }
+        }
+
+        s
+    }
+
+    /// Node cell sizes
+    pub fn cell_sizes(self) -> CellSizes {
+        let mut address_cells = None;
+        let mut size_cells = None;
+
+        for property in self.properties() {
+            match property.name {
+                "#address-cells" => {
+                    address_cells =
+                        BigEndianU32::from_bytes(property.value).map(|n| n.get() as usize)
+                }
+                "#size-cells" => {
+                    size_cells = BigEndianU32::from_bytes(property.value).map(|n| n.get() as usize)
+                }
+                _ => {}
+            }
+        }
+
+        if let Some(parent) = self.parent_props {
+            let parent =
+                FdtNode { name: "", props: parent, header: self.header, parent_props: None };
+            let parent_sizes = parent.cell_sizes();
+
+            if address_cells.is_none() {
+                address_cells = Some(parent_sizes.address_cells);
+            }
+
+            if size_cells.is_none() {
+                size_cells = Some(parent_sizes.size_cells);
+            }
+        }
+
+        // FIXME: this works around a bug(?) in the QEMU FDT
+        if address_cells == Some(0) {
+            address_cells = Some(2);
+        }
+
+        CellSizes { address_cells: address_cells.unwrap_or(2), size_cells: size_cells.unwrap_or(1) }
+    }
+
+    /// Searches for the interrupt parent, if the node contains one
+    pub fn interrupt_parent(self) -> Option<FdtNode<'b, 'a>> {
+        self.properties()
+            .find(|p| p.name == "interrupt-parent")
+            .and_then(|p| self.header.find_phandle(BigEndianU32::from_bytes(p.value)?.get()))
+    }
+
+    /// `#interrupt-cells` property
+    pub fn interrupt_cells(self) -> Option<usize> {
+        let mut interrupt_cells = None;
+
+        if let Some(prop) = self.properties().find(|p| p.name == "#interrupt-cells") {
+            interrupt_cells = BigEndianU32::from_bytes(prop.value).map(|n| n.get() as usize)
+        }
+
+        if let (None, Some(parent)) = (interrupt_cells, self.interrupt_parent()) {
+            interrupt_cells = parent.interrupt_cells();
+        }
+
+        interrupt_cells
+    }
+
+    /// `interrupts` property
+    pub fn interrupts(self) -> Option<impl Iterator<Item = usize> + 'a> {
+        let sizes = self.interrupt_cells()?;
+
+        let mut interrupt = None;
+        for prop in self.properties() {
+            if prop.name == "interrupts" {
+                let mut stream = FdtData::new(prop.value);
+                interrupt = Some(core::iter::from_fn(move || {
+                    let interrupt = match sizes {
+                        1 => stream.u32()?.get() as usize,
+                        2 => stream.u64()?.get() as usize,
+                        _ => return None,
+                    };
+
+                    Some(interrupt)
+                }));
+                break;
+            }
+        }
+
+        interrupt
+    }
+}
+
+/// The number of cells (big endian u32s) that addresses and sizes take
+#[derive(Debug, Clone, Copy)]
+pub struct CellSizes {
+    /// Size of values representing an address
+    pub address_cells: usize,
+    /// Size of values representing a size
+    pub size_cells: usize,
+}
+
+impl Default for CellSizes {
+    fn default() -> Self {
+        CellSizes { address_cells: 2, size_cells: 1 }
+    }
+}
+
+pub(crate) fn find_node<'b, 'a: 'b>(
+    stream: &mut FdtData<'a>,
+    name: &str,
+    header: &'b Fdt<'a>,
+    parent_props: Option<&'a [u8]>,
+) -> Option<FdtNode<'b, 'a>> {
+    let mut parts = name.splitn(2, '/');
+    let looking_for = parts.next()?;
+
+    stream.skip_nops();
+
+    let curr_data = stream.remaining();
+
+    match stream.u32()?.get() {
+        FDT_BEGIN_NODE => {}
+        _ => return None,
+    }
+
+    let unit_name = CStr::new(stream.remaining()).expect("unit name C str").as_str()?;
+
+    let full_name_len = unit_name.len() + 1;
+    skip_4_aligned(stream, full_name_len);
+
+    let looking_contains_addr = looking_for.contains('@');
+    let addr_name_same = unit_name == looking_for;
+    let base_name_same = unit_name.split('@').next()? == looking_for;
+
+    if (looking_contains_addr && !addr_name_same) || (!looking_contains_addr && !base_name_same) {
+        *stream = FdtData::new(curr_data);
+        skip_current_node(stream, header);
+
+        return None;
+    }
+
+    let next_part = match parts.next() {
+        None | Some("") => {
+            return Some(FdtNode::new(unit_name, header, stream.remaining(), parent_props))
+        }
+        Some(part) => part,
+    };
+
+    stream.skip_nops();
+
+    let parent_props = Some(stream.remaining());
+
+    while stream.peek_u32()?.get() == FDT_PROP {
+        let _ = NodeProperty::parse(stream, header);
+    }
+
+    while stream.peek_u32()?.get() == FDT_BEGIN_NODE {
+        if let Some(p) = find_node(stream, next_part, header, parent_props) {
+            return Some(p);
+        }
+    }
+
+    stream.skip_nops();
+
+    if stream.u32()?.get() != FDT_END_NODE {
+        return None;
+    }
+
+    None
+}
+
+// FIXME: this probably needs refactored
+pub(crate) fn all_nodes<'b, 'a: 'b>(header: &'b Fdt<'a>) -> impl Iterator<Item = FdtNode<'b, 'a>> {
+    let mut stream = FdtData::new(header.structs_block());
+    let mut done = false;
+    let mut parents: [&[u8]; 64] = [&[]; 64];
+    let mut parent_index = 0;
+
+    core::iter::from_fn(move || {
+        if stream.is_empty() || done {
+            return None;
+        }
+
+        while stream.peek_u32()?.get() == FDT_END_NODE {
+            parent_index -= 1;
+            stream.skip(4);
+        }
+
+        if stream.peek_u32()?.get() == FDT_END {
+            done = true;
+            return None;
+        }
+
+        while stream.peek_u32()?.get() == FDT_NOP {
+            stream.skip(4);
+        }
+
+        match stream.u32()?.get() {
+            FDT_BEGIN_NODE => {}
+            _ => return None,
+        }
+
+        let unit_name = CStr::new(stream.remaining()).expect("unit name C str").as_str().unwrap();
+        let full_name_len = unit_name.len() + 1;
+        skip_4_aligned(&mut stream, full_name_len);
+
+        let curr_node = stream.remaining();
+
+        parent_index += 1;
+        parents[parent_index] = curr_node;
+
+        while stream.peek_u32()?.get() == FDT_NOP {
+            stream.skip(4);
+        }
+
+        while stream.peek_u32()?.get() == FDT_PROP {
+            NodeProperty::parse(&mut stream, header);
+        }
+
+        Some(FdtNode {
+            name: if unit_name.is_empty() { "/" } else { unit_name },
+            header,
+            parent_props: match parent_index {
+                1 => None,
+                _ => Some(parents[parent_index - 1]),
+            },
+            props: curr_node,
+        })
+    })
+}
+
+pub(crate) fn skip_current_node<'a>(stream: &mut FdtData<'a>, header: &Fdt<'a>) {
+    assert_eq!(stream.u32().unwrap().get(), FDT_BEGIN_NODE, "bad node");
+
+    let unit_name = CStr::new(stream.remaining()).expect("unit_name C str").as_str().unwrap();
+    let full_name_len = unit_name.len() + 1;
+    skip_4_aligned(stream, full_name_len);
+
+    while stream.peek_u32().unwrap().get() == FDT_PROP {
+        NodeProperty::parse(stream, header);
+    }
+
+    while stream.peek_u32().unwrap().get() == FDT_BEGIN_NODE {
+        skip_current_node(stream, header);
+    }
+
+    stream.skip_nops();
+
+    assert_eq!(stream.u32().unwrap().get(), FDT_END_NODE, "bad node");
+}
+
+/// A node property
+#[derive(Debug, Clone, Copy)]
+pub struct NodeProperty<'a> {
+    /// Property name
+    pub name: &'a str,
+    /// Property value
+    pub value: &'a [u8],
+}
+
+impl<'a> NodeProperty<'a> {
+    /// Attempt to parse the property value as a `usize`
+    pub fn as_usize(self) -> Option<usize> {
+        match self.value.len() {
+            4 => BigEndianU32::from_bytes(self.value).map(|i| i.get() as usize),
+            8 => BigEndianU64::from_bytes(self.value).map(|i| i.get() as usize),
+            _ => None,
+        }
+    }
+
+    /// Attempt to parse the property value as a `&str`
+    pub fn as_str(self) -> Option<&'a str> {
+        core::str::from_utf8(self.value).ok()
+    }
+
+    fn parse(stream: &mut FdtData<'a>, header: &Fdt<'a>) -> Self {
+        match stream.u32().unwrap().get() {
+            FDT_PROP => {}
+            other => panic!("bad prop, tag: {}", other),
+        }
+
+        let prop = FdtProperty::from_bytes(stream).expect("FDT property");
+        let data_len = prop.len.get() as usize;
+
+        let data = &stream.remaining()[..data_len];
+
+        skip_4_aligned(stream, data_len);
+
+        NodeProperty { name: header.str_at_offset(prop.name_offset.get() as usize), value: data }
+    }
+}
+
+/// A memory reservation
+#[derive(Debug)]
+#[repr(C)]
+pub struct MemoryReservation {
+    pub(crate) address: BigEndianU64,
+    pub(crate) size: BigEndianU64,
+}
+
+impl MemoryReservation {
+    /// Pointer representing the memory reservation address
+    pub fn address(&self) -> *const u8 {
+        self.address.get() as usize as *const u8
+    }
+
+    /// Size of the memory reservation
+    pub fn size(&self) -> usize {
+        self.size.get() as usize
+    }
+
+    pub(crate) fn from_bytes(bytes: &mut FdtData<'_>) -> Option<Self> {
+        let address = bytes.u64()?;
+        let size = bytes.u64()?;
+
+        Some(Self { address, size })
+    }
+}
+
+fn skip_4_aligned(stream: &mut FdtData<'_>, len: usize) {
+    stream.skip((len + 3) & !0x3);
+}

+ 97 - 0
src/parsing.rs

@@ -0,0 +1,97 @@
+// This Source Code Form is subject to the terms of the Mozilla Public License,
+// v. 2.0. If a copy of the MPL was not distributed with this file, You can
+// obtain one at https://mozilla.org/MPL/2.0/.
+
+use core::convert::TryInto;
+pub struct CStr<'a>(&'a [u8]);
+
+impl<'a> CStr<'a> {
+    pub fn new(data: &'a [u8]) -> Option<Self> {
+        let end = data.iter().position(|&b| b == 0)?;
+        Some(Self(&data[..end]))
+    }
+
+    /// Does not include the null terminating byte
+    pub fn len(&self) -> usize {
+        self.0.len()
+    }
+
+    pub fn as_str(&self) -> Option<&'a str> {
+        core::str::from_utf8(&self.0).ok()
+    }
+}
+
+#[derive(Debug, Clone, Copy)]
+#[repr(transparent)]
+pub struct BigEndianU32(u32);
+
+impl BigEndianU32 {
+    pub fn get(self) -> u32 {
+        self.0
+    }
+
+    pub(crate) fn from_bytes(bytes: &[u8]) -> Option<Self> {
+        Some(BigEndianU32(u32::from_be_bytes(bytes.get(..4)?.try_into().unwrap())))
+    }
+}
+
+#[derive(Debug, Clone, Copy)]
+#[repr(transparent)]
+pub struct BigEndianU64(u64);
+
+impl BigEndianU64 {
+    pub fn get(&self) -> u64 {
+        self.0
+    }
+
+    pub(crate) fn from_bytes(bytes: &[u8]) -> Option<Self> {
+        Some(BigEndianU64(u64::from_be_bytes(bytes.get(..8)?.try_into().unwrap())))
+    }
+}
+
+#[derive(Debug, Clone, Copy)]
+pub struct FdtData<'a> {
+    bytes: &'a [u8],
+}
+
+impl<'a> FdtData<'a> {
+    pub fn new(bytes: &'a [u8]) -> Self {
+        Self { bytes }
+    }
+
+    pub fn u32(&mut self) -> Option<BigEndianU32> {
+        let ret = BigEndianU32::from_bytes(self.bytes)?;
+        self.skip(4);
+
+        Some(ret)
+    }
+
+    pub fn u64(&mut self) -> Option<BigEndianU64> {
+        let ret = BigEndianU64::from_bytes(self.bytes)?;
+        self.skip(8);
+
+        Some(ret)
+    }
+
+    pub fn skip(&mut self, n_bytes: usize) {
+        self.bytes = self.bytes.get(n_bytes..).unwrap_or_default()
+    }
+
+    pub fn remaining(&self) -> &'a [u8] {
+        self.bytes
+    }
+
+    pub fn peek_u32(&self) -> Option<BigEndianU32> {
+        Self::new(self.remaining()).u32()
+    }
+
+    pub fn is_empty(&self) -> bool {
+        self.remaining().is_empty()
+    }
+
+    pub fn skip_nops(&mut self) {
+        while let Some(crate::node::FDT_NOP) = self.peek_u32().map(|n| n.get()) {
+            let _ = self.u32();
+        }
+    }
+}

+ 293 - 0
src/standard_nodes.rs

@@ -0,0 +1,293 @@
+// This Source Code Form is subject to the terms of the Mozilla Public License,
+// v. 2.0. If a copy of the MPL was not distributed with this file, You can
+// obtain one at https://mozilla.org/MPL/2.0/.
+
+use crate::{
+    node::{CellSizes, FdtNode, NodeProperty},
+    parsing::{BigEndianU32, BigEndianU64, CStr, FdtData},
+    Fdt,
+};
+
+/// Represents the `/chosen` node with specific helper methods
+#[derive(Debug, Clone, Copy)]
+pub struct Chosen<'b, 'a: 'b> {
+    pub(crate) node: FdtNode<'b, 'a>,
+}
+
+impl<'b, 'a: 'b> Chosen<'b, 'a> {
+    /// Contains the bootargs, if they exist
+    pub fn bootargs(self) -> Option<&'a str> {
+        self.node
+            .properties()
+            .find(|n| n.name == "bootargs")
+            .and_then(|n| core::str::from_utf8(&n.value[..n.value.len() - 1]).ok())
+    }
+
+    /// Searches for the node representing `stdout`, if the property exists,
+    /// attempting to resolve aliases if the node name doesn't exist as-is
+    pub fn stdout(self) -> Option<FdtNode<'b, 'a>> {
+        self.node
+            .properties()
+            .find(|n| n.name == "stdout-path")
+            .and_then(|n| core::str::from_utf8(&n.value[..n.value.len() - 1]).ok())
+            .and_then(|name| self.node.header.find_node(name))
+    }
+
+    /// Searches for the node representing `stdout`, if the property exists,
+    /// attempting to resolve aliases if the node name doesn't exist as-is. If
+    /// no `stdin` property exists, but `stdout` is present, it will return the
+    /// node specified by the `stdout` property.
+    pub fn stdin(self) -> Option<FdtNode<'b, 'a>> {
+        self.node
+            .properties()
+            .find(|n| n.name == "stdin-path")
+            .and_then(|n| core::str::from_utf8(&n.value[..n.value.len() - 1]).ok())
+            .and_then(|name| self.node.header.find_node(name))
+            .or_else(|| self.stdout())
+    }
+}
+
+/// Represents the root (`/`) node with specific helper methods
+#[derive(Debug, Clone, Copy)]
+pub struct Root<'b, 'a: 'b> {
+    pub(crate) node: FdtNode<'b, 'a>,
+}
+
+impl<'b, 'a: 'b> Root<'b, 'a> {
+    /// Root node cell sizes
+    pub fn cell_sizes(self) -> CellSizes {
+        self.node.cell_sizes()
+    }
+
+    /// `model` property
+    pub fn model(self) -> &'a str {
+        self.node
+            .properties()
+            .find(|p| p.name == "model")
+            .and_then(|p| core::str::from_utf8(p.value).ok())
+            .unwrap()
+    }
+
+    /// `compatible` property
+    pub fn compatible(self) -> Compatible<'a> {
+        self.node.compatible().unwrap()
+    }
+
+    /// Returns an iterator over all of the available properties
+    pub fn properties(self) -> impl Iterator<Item = NodeProperty<'a>> + 'b {
+        self.node.properties()
+    }
+
+    /// Attempts to find the a property by its name
+    pub fn property(self, name: &str) -> Option<NodeProperty<'a>> {
+        self.node.properties().find(|p| p.name == name)
+    }
+}
+
+/// Represents the `/aliases` node with specific helper methods
+#[derive(Debug, Clone, Copy)]
+pub struct Aliases<'b, 'a: 'b> {
+    pub(crate) header: &'b Fdt<'a>,
+    pub(crate) node: FdtNode<'b, 'a>,
+}
+
+impl<'b, 'a: 'b> Aliases<'b, 'a> {
+    /// Attempt to resolve an alias to a node name
+    pub fn resolve(self, alias: &str) -> Option<&'a str> {
+        self.node
+            .properties()
+            .find(|p| p.name == alias)
+            .and_then(|p| core::str::from_utf8(p.value).ok())
+    }
+
+    /// Attempt to find the node specified by the given alias
+    pub fn resolve_node(self, alias: &str) -> Option<FdtNode<'b, 'a>> {
+        self.resolve(alias).and_then(|name| self.header.find_node(name))
+    }
+
+    /// Returns an iterator over all of the available aliases
+    pub fn all(self) -> impl Iterator<Item = (&'a str, &'a str)> + 'b {
+        self.node.properties().filter_map(|p| Some((p.name, core::str::from_utf8(p.value).ok()?)))
+    }
+}
+
+/// Represents a `/cpus/cpu*` node with specific helper methods
+#[derive(Debug, Clone, Copy)]
+pub struct Cpu<'b, 'a: 'b> {
+    pub(crate) parent: FdtNode<'b, 'a>,
+    pub(crate) node: FdtNode<'b, 'a>,
+}
+
+impl<'b, 'a: 'b> Cpu<'b, 'a> {
+    /// Return the IDs for the given CPU
+    pub fn ids(self) -> CpuIds<'a> {
+        let address_cells = self.node.cell_sizes().address_cells;
+
+        CpuIds { reg: self.node.properties().find(|p| p.name == "reg").unwrap(), address_cells }
+    }
+
+    /// `clock-frequency` property
+    pub fn clock_frequency(self) -> usize {
+        self.node
+            .properties()
+            .find(|p| p.name == "clock-frequency")
+            .or_else(|| self.parent.properties().find(|p| p.name == "clock-frequency"))
+            .map(|p| match p.value.len() {
+                4 => BigEndianU32::from_bytes(p.value).unwrap().get() as usize,
+                8 => BigEndianU64::from_bytes(p.value).unwrap().get() as usize,
+                _ => unreachable!(),
+            })
+            .unwrap()
+    }
+
+    /// `timebase-frequency` property
+    pub fn timebase_frequency(self) -> usize {
+        self.node
+            .properties()
+            .find(|p| p.name == "timebase-frequency")
+            .or_else(|| self.parent.properties().find(|p| p.name == "timebase-frequency"))
+            .map(|p| match p.value.len() {
+                4 => BigEndianU32::from_bytes(p.value).unwrap().get() as usize,
+                8 => BigEndianU64::from_bytes(p.value).unwrap().get() as usize,
+                _ => unreachable!(),
+            })
+            .unwrap()
+    }
+
+    /// Returns an iterator over all of the properties for the CPU node
+    pub fn properties(self) -> impl Iterator<Item = NodeProperty<'a>> + 'b {
+        self.node.properties()
+    }
+
+    /// Attempts to find the a property by its name
+    pub fn property(self, name: &str) -> Option<NodeProperty<'a>> {
+        self.node.properties().find(|p| p.name == name)
+    }
+}
+
+/// Represents the value of the `reg` property of a `/cpus/cpu*` node which may
+/// contain more than one CPU or thread ID
+#[derive(Debug, Clone, Copy)]
+pub struct CpuIds<'a> {
+    pub(crate) reg: NodeProperty<'a>,
+    pub(crate) address_cells: usize,
+}
+
+impl<'a> CpuIds<'a> {
+    /// The first listed CPU ID, which will always exist
+    pub fn first(self) -> usize {
+        match self.address_cells {
+            1 => BigEndianU32::from_bytes(self.reg.value).unwrap().get() as usize,
+            2 => BigEndianU64::from_bytes(self.reg.value).unwrap().get() as usize,
+            n => panic!("address-cells of size {} is currently not supported", n),
+        }
+    }
+
+    /// Returns an iterator over all of the listed CPU IDs
+    pub fn all(self) -> impl Iterator<Item = usize> + 'a {
+        let mut vals = FdtData::new(self.reg.value);
+        core::iter::from_fn(move || match vals.remaining() {
+            [] => None,
+            _ => Some(match self.address_cells {
+                1 => vals.u32()?.get() as usize,
+                2 => vals.u64()?.get() as usize,
+                n => panic!("address-cells of size {} is currently not supported", n),
+            }),
+        })
+    }
+}
+
+/// Represents the `compatible` property of a node
+#[derive(Clone, Copy)]
+pub struct Compatible<'a> {
+    pub(crate) data: &'a [u8],
+}
+
+impl<'a> Compatible<'a> {
+    /// First compatible string
+    pub fn first(self) -> &'a str {
+        CStr::new(self.data).expect("expected C str").as_str().unwrap()
+    }
+
+    /// Returns an iterator over all available compatible strings
+    pub fn all(self) -> impl Iterator<Item = &'a str> {
+        let mut data = self.data;
+        core::iter::from_fn(move || {
+            if data.is_empty() {
+                return None;
+            }
+
+            match data.iter().position(|b| *b == b'\0') {
+                Some(idx) => {
+                    let ret = Some(core::str::from_utf8(&data[..idx]).ok()?);
+                    data = &data[idx + 1..];
+
+                    ret
+                }
+                None => {
+                    let ret = Some(core::str::from_utf8(data).ok()?);
+                    data = &[];
+
+                    ret
+                }
+            }
+        })
+    }
+}
+
+/// Represents the `/memory` node with specific helper methods
+#[derive(Debug, Clone, Copy)]
+pub struct Memory<'b, 'a: 'b> {
+    pub(crate) node: FdtNode<'b, 'a>,
+}
+
+impl Memory<'_, '_> {
+    /// Returns an iterator over all of the available memory regions
+    pub fn regions(&self) -> impl Iterator<Item = MemoryRegion> + '_ {
+        self.node.reg().unwrap()
+    }
+
+    /// Returns the initial mapped area, if it exists
+    pub fn initial_mapped_area(&self) -> Option<MappedArea> {
+        let mut mapped_area = None;
+
+        if let Some(init_mapped_area) =
+            self.node.properties().find(|n| n.name == "initial_mapped_area")
+        {
+            let mut stream = FdtData::new(init_mapped_area.value);
+            let effective_address = stream.u64().expect("effective address");
+            let physical_address = stream.u64().expect("physical address");
+            let size = stream.u32().expect("size");
+
+            mapped_area = Some(MappedArea {
+                effective_address: effective_address.get() as usize,
+                physical_address: physical_address.get() as usize,
+                size: size.get() as usize,
+            });
+        }
+
+        mapped_area
+    }
+}
+
+/// An area described by the `initial-mapped-area` property of the `/memory`
+/// node
+#[derive(Debug, Clone, Copy, PartialEq)]
+#[repr(C)]
+pub struct MappedArea {
+    /// Effective address of the mapped area
+    pub effective_address: usize,
+    /// Physical address of the mapped area
+    pub physical_address: usize,
+    /// Size of the mapped area
+    pub size: usize,
+}
+
+/// A memory region
+#[derive(Debug, Clone, Copy, PartialEq)]
+pub struct MemoryRegion {
+    /// Starting address represented as a pointer
+    pub starting_address: *const u8,
+    /// Size of the memory region
+    pub size: Option<usize>,
+}

+ 146 - 0
src/tests.rs

@@ -0,0 +1,146 @@
+// This Source Code Form is subject to the terms of the Mozilla Public License,
+// v. 2.0. If a copy of the MPL was not distributed with this file, You can
+// obtain one at https://mozilla.org/MPL/2.0/.
+
+extern crate std;
+
+use crate::*;
+
+static TEST: &[u8] = include_bytes!("../test.dtb");
+
+#[test]
+fn returns_fdt() {
+    assert!(Fdt::new(TEST).is_ok());
+}
+
+#[test]
+fn finds_root_node() {
+    let fdt = Fdt::new(TEST).unwrap();
+    assert!(fdt.find_node("/").is_some(), "couldn't find root node");
+}
+
+#[test]
+fn finds_root_node_properties() {
+    let fdt = Fdt::new(TEST).unwrap();
+    let prop = fdt
+        .find_node("/")
+        .unwrap()
+        .properties()
+        .any(|p| p.name == "compatible" && p.value == b"riscv-virtio\0");
+
+    assert!(prop);
+}
+
+#[test]
+fn finds_child_of_root_node() {
+    let fdt = Fdt::new(TEST).unwrap();
+    assert!(fdt.find_node("/cpus").is_some(), "couldn't find cpus node");
+}
+
+#[test]
+fn correct_flash_regions() {
+    let fdt = Fdt::new(TEST).unwrap();
+    let regions = fdt.find_node("/soc/flash").unwrap().reg().unwrap().collect::<std::vec::Vec<_>>();
+
+    assert_eq!(
+        regions,
+        &[
+            MemoryRegion { starting_address: 0x20000000 as *const u8, size: Some(0x2000000) },
+            MemoryRegion { starting_address: 0x22000000 as *const u8, size: Some(0x2000000) }
+        ]
+    );
+}
+
+#[test]
+fn finds_with_addr() {
+    let fdt = Fdt::new(TEST).unwrap();
+    assert_eq!(fdt.find_node("/soc/virtio_mmio@10004000").unwrap().name, "virtio_mmio@10004000");
+}
+
+#[test]
+fn compatibles() {
+    let fdt = Fdt::new(TEST).unwrap();
+    let res = fdt
+        .find_node("/soc/test")
+        .unwrap()
+        .compatible()
+        .unwrap()
+        .all()
+        .all(|s| ["sifive,test1", "sifive,test0", "syscon"].contains(&s));
+
+    assert!(res);
+}
+
+#[test]
+fn parent_cell_sizes() {
+    let fdt = Fdt::new(TEST).unwrap();
+    let regions = fdt.find_node("/memory").unwrap().reg().unwrap().collect::<std::vec::Vec<_>>();
+
+    assert_eq!(
+        regions,
+        &[MemoryRegion { starting_address: 0x80000000 as *const u8, size: Some(0x20000000) }]
+    );
+}
+
+#[test]
+fn no_properties() {
+    let fdt = Fdt::new(TEST).unwrap();
+    let regions = fdt.find_node("/emptyproptest").unwrap();
+    assert_eq!(regions.properties().count(), 0);
+}
+
+#[test]
+fn finds_all_nodes() {
+    let fdt = Fdt::new(TEST).unwrap();
+
+    let mut all_nodes: std::vec::Vec<_> = fdt.all_nodes().map(|n| n.name).collect();
+    all_nodes.sort_unstable();
+
+    assert_eq!(
+        all_nodes,
+        &[
+            "/",
+            "chosen",
+            "clint@2000000",
+            "cluster0",
+            "core0",
+            "cpu-map",
+            "cpu@0",
+            "cpus",
+            "emptyproptest",
+            "flash@20000000",
+            "interrupt-controller",
+            "memory@80000000",
+            "pci@30000000",
+            "plic@c000000",
+            "poweroff",
+            "reboot",
+            "rtc@101000",
+            "soc",
+            "test@100000",
+            "uart@10000000",
+            "virtio_mmio@10001000",
+            "virtio_mmio@10002000",
+            "virtio_mmio@10003000",
+            "virtio_mmio@10004000",
+            "virtio_mmio@10005000",
+            "virtio_mmio@10006000",
+            "virtio_mmio@10007000",
+            "virtio_mmio@10008000"
+        ]
+    )
+}
+
+#[test]
+fn required_nodes() {
+    let fdt = Fdt::new(TEST).unwrap();
+    fdt.cpus().next().unwrap();
+    fdt.memory();
+    fdt.chosen();
+}
+
+#[test]
+fn doesnt_exist() {
+    let fdt = Fdt::new(TEST).unwrap();
+    assert!(fdt.find_node("/this/doesnt/exist").is_none());
+}

BIN
test.dtb


+ 191 - 0
test.dts

@@ -0,0 +1,191 @@
+/dts-v1/;
+
+/ {
+	#address-cells = <0x02>;
+	#size-cells = <0x02>;
+	compatible = "riscv-virtio";
+	model = "riscv-virtio,qemu";
+
+	chosen {
+		bootargs = [00];
+		stdout-path = "/soc/uart@10000000";
+	};
+
+	memory@80000000 {
+		device_type = "memory";
+		reg = <0x00 0x80000000 0x00 0x20000000>;
+	};
+
+	cpus {
+		#address-cells = <0x01>;
+		#size-cells = <0x00>;
+		timebase-frequency = <0x989680>;
+
+		cpu@0 {
+			phandle = <0x01>;
+			device_type = "cpu";
+			reg = <0x00>;
+			status = "okay";
+			compatible = "riscv";
+			riscv,isa = "rv64imafdcsu";
+			mmu-type = "riscv,sv48";
+
+			interrupt-controller {
+				#interrupt-cells = <0x01>;
+				interrupt-controller;
+				compatible = "riscv,cpu-intc";
+				phandle = <0x02>;
+			};
+		};
+
+		cpu-map {
+
+			cluster0 {
+
+				core0 {
+					cpu = <0x01>;
+				};
+			};
+		};
+	};
+
+	emptyproptest {
+
+	};
+
+	soc {
+		#address-cells = <0x02>;
+		#size-cells = <0x02>;
+		compatible = "simple-bus";
+		ranges;
+
+		flash@20000000 {
+			bank-width = <0x04>;
+			reg = <0x00 0x20000000 0x00 0x2000000 0x00 0x22000000 0x00 0x2000000>;
+			compatible = "cfi-flash";
+		};
+
+		rtc@101000 {
+			interrupts = <0x0b>;
+			interrupt-parent = <0x03>;
+			reg = <0x00 0x101000 0x00 0x1000>;
+			compatible = "google,goldfish-rtc";
+		};
+
+		uart@10000000 {
+			interrupts = <0x0a>;
+			interrupt-parent = <0x03>;
+			clock-frequency = <0x384000>;
+			reg = <0x00 0x10000000 0x00 0x100>;
+			compatible = "ns16550a";
+		};
+
+		poweroff {
+			value = <0x5555>;
+			offset = <0x00>;
+			regmap = <0x04>;
+			compatible = "syscon-poweroff";
+		};
+
+		reboot {
+			value = <0x7777>;
+			offset = <0x00>;
+			regmap = <0x04>;
+			compatible = "syscon-reboot";
+		};
+
+		test@100000 {
+			phandle = <0x04>;
+			reg = <0x00 0x100000 0x00 0x1000>;
+			compatible = "sifive,test1\0sifive,test0\0syscon";
+		};
+
+		pci@30000000 {
+			interrupt-map-mask = <0x1800 0x00 0x00 0x07>;
+			interrupt-map = <0x00 0x00 0x00 0x01 0x03 0x20 0x00 0x00 0x00 0x02 0x03 0x21 0x00 0x00 0x00 0x03 0x03 0x22 0x00 0x00 0x00 0x04 0x03 0x23 0x800 0x00 0x00 0x01 0x03 0x21 0x800 0x00 0x00 0x02 0x03 0x22 0x800 0x00 0x00 0x03 0x03 0x23 0x800 0x00 0x00 0x04 0x03 0x20 0x1000 0x00 0x00 0x01 0x03 0x22 0x1000 0x00 0x00 0x02 0x03 0x23 0x1000 0x00 0x00 0x03 0x03 0x20 0x1000 0x00 0x00 0x04 0x03 0x21 0x1800 0x00 0x00 0x01 0x03 0x23 0x1800 0x00 0x00 0x02 0x03 0x20 0x1800 0x00 0x00 0x03 0x03 0x21 0x1800 0x00 0x00 0x04 0x03 0x22>;
+			ranges = <0x1000000 0x00 0x00 0x00 0x3000000 0x00 0x10000 0x2000000 0x00 0x40000000 0x00 0x40000000 0x00 0x40000000>;
+			reg = <0x00 0x30000000 0x00 0x10000000>;
+			dma-coherent;
+			bus-range = <0x00 0xff>;
+			linux,pci-domain = <0x00>;
+			device_type = "pci";
+			compatible = "pci-host-ecam-generic";
+			#size-cells = <0x02>;
+			#interrupt-cells = <0x01>;
+			#address-cells = <0x03>;
+		};
+
+		virtio_mmio@10008000 {
+			interrupts = <0x08>;
+			interrupt-parent = <0x03>;
+			reg = <0x00 0x10008000 0x00 0x1000>;
+			compatible = "virtio,mmio";
+		};
+
+		virtio_mmio@10007000 {
+			interrupts = <0x07>;
+			interrupt-parent = <0x03>;
+			reg = <0x00 0x10007000 0x00 0x1000>;
+			compatible = "virtio,mmio";
+		};
+
+		virtio_mmio@10006000 {
+			interrupts = <0x06>;
+			interrupt-parent = <0x03>;
+			reg = <0x00 0x10006000 0x00 0x1000>;
+			compatible = "virtio,mmio";
+		};
+
+		virtio_mmio@10005000 {
+			interrupts = <0x05>;
+			interrupt-parent = <0x03>;
+			reg = <0x00 0x10005000 0x00 0x1000>;
+			compatible = "virtio,mmio";
+		};
+
+		virtio_mmio@10004000 {
+			interrupts = <0x04>;
+			interrupt-parent = <0x03>;
+			reg = <0x00 0x10004000 0x00 0x1000>;
+			compatible = "virtio,mmio";
+		};
+
+		virtio_mmio@10003000 {
+			interrupts = <0x03>;
+			interrupt-parent = <0x03>;
+			reg = <0x00 0x10003000 0x00 0x1000>;
+			compatible = "virtio,mmio";
+		};
+
+		virtio_mmio@10002000 {
+			interrupts = <0x02>;
+			interrupt-parent = <0x03>;
+			reg = <0x00 0x10002000 0x00 0x1000>;
+			compatible = "virtio,mmio";
+		};
+
+		virtio_mmio@10001000 {
+			interrupts = <0x01>;
+			interrupt-parent = <0x03>;
+			reg = <0x00 0x10001000 0x00 0x1000>;
+			compatible = "virtio,mmio";
+		};
+
+		plic@c000000 {
+			phandle = <0x03>;
+			riscv,ndev = <0x35>;
+			reg = <0x00 0xc000000 0x00 0x210000>;
+			interrupts-extended = <0x02 0x0b 0x02 0x09>;
+			interrupt-controller;
+			compatible = "riscv,plic0";
+			#interrupt-cells = <0x01>;
+			#address-cells = <0x00>;
+		};
+
+		clint@2000000 {
+			interrupts-extended = <0x02 0x03 0x02 0x07>;
+			reg = <0x00 0x2000000 0x00 0x10000>;
+			compatible = "riscv,clint0";
+		};
+	};
+};