Skip to content
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
11 changes: 10 additions & 1 deletion src/fdt/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,7 @@ mod node;
mod property;
use core::ffi::CStr;
use core::mem::offset_of;
use core::ptr;
use core::{fmt, ptr};

pub use node::FdtNode;
pub use property::FdtProperty;
Expand Down Expand Up @@ -491,6 +491,15 @@ impl<'a> Fdt<'a> {
}
}

impl fmt::Display for Fdt<'_> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
writeln!(f, "/dts-v1/;")?;
writeln!(f)?;
let root = self.root().map_err(|_| fmt::Error)?;
root.fmt_recursive(f, 0)
}
}

#[cfg(test)]
mod tests {
use super::*;
Expand Down
39 changes: 39 additions & 0 deletions src/fdt/node.rs
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,8 @@

//! A read-only API for inspecting a device tree node.

use core::fmt;

use super::{FDT_TAGSIZE, Fdt, FdtToken};
use crate::error::FdtError;
use crate::fdt::property::{FdtPropIter, FdtProperty};
Expand Down Expand Up @@ -149,6 +151,43 @@ impl<'a> FdtNode<'a> {
offset: self.offset,
}
}

pub(crate) fn fmt_recursive(&self, f: &mut fmt::Formatter<'_>, indent: usize) -> fmt::Result {
let name = self.name().map_err(|_| fmt::Error)?;
if name.is_empty() {
writeln!(f, "{:indent$}/ {{", "", indent = indent)?;
} else {
writeln!(f, "{:indent$}{} {{", "", name, indent = indent)?;
}

let mut has_properties = false;
for prop in self.properties() {
has_properties = true;
match prop {
Ok(prop) => prop.fmt(f, indent + 4)?,
Err(_e) => {
writeln!(f, "<Error reading property>")?;
}
}
}

let mut first_child = true;
for child in self.children() {
if !first_child || has_properties {
writeln!(f)?;
}

first_child = false;
match child {
Ok(child) => child.fmt_recursive(f, indent + 4)?,
Err(_e) => {
writeln!(f, "<Error reading child node>")?;
}
}
}

writeln!(f, "{:indent$}}};", "", indent = indent)
}
}

/// An iterator over the children of a device tree node.
Expand Down
54 changes: 54 additions & 0 deletions src/fdt/property.rs
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@
//! A read-only API for inspecting a device tree property.

use core::ffi::CStr;
use core::fmt;

use zerocopy::{FromBytes, big_endian};

Expand Down Expand Up @@ -125,6 +126,59 @@ impl<'a> FdtProperty<'a> {
pub fn as_str_list(&self) -> impl Iterator<Item = &'a str> {
FdtStringListIterator { value: self.value }
}

pub(crate) fn fmt(&self, f: &mut fmt::Formatter<'_>, indent: usize) -> fmt::Result {
write!(f, "{:indent$}{}", "", self.name, indent = indent)?;

if self.value.is_empty() {
writeln!(f, ";")?;
return Ok(());
}

let is_printable = self
.value
.iter()
.all(|&ch| ch.is_ascii_graphic() || ch == b' ' || ch == 0);
let has_empty = self.value.windows(2).any(|window| window == [0, 0]);
if is_printable && self.value.ends_with(&[0]) && !has_empty {
let mut strings = self.as_str_list();
if let Some(first) = strings.next() {
write!(f, " = \"{first}\"")?;
for s in strings {
write!(f, ", \"{s}\"")?;
}
writeln!(f, ";")?;
return Ok(());
}
}

if self.value.len().is_multiple_of(4) {
write!(f, " = <")?;
for (i, chunk) in self.value.chunks_exact(4).enumerate() {
if i > 0 {
write!(f, " ")?;
}
let val = u32::from_be_bytes(
chunk
.try_into()
.expect("u32::from_be_bytes() should always succeed with 4 bytes"),
);
write!(f, "0x{val:02x}")?;
}
writeln!(f, ">;")?;
} else {
write!(f, " = [")?;
for (i, byte) in self.value.iter().enumerate() {
if i > 0 {
write!(f, " ")?;
}
write!(f, "{byte:02x}")?;
}
writeln!(f, "];")?;
}

Ok(())
}
}

/// An iterator over the properties of a device tree node.
Expand Down
Binary file added tests/dtb/test_pretty_print.dtb
Binary file not shown.
27 changes: 27 additions & 0 deletions tests/dts/test_pretty_print.dts
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
/dts-v1/;

/ {
#address-cells = <0x01>;
#size-cells = <0x01>;
compatible = "acme,coyote";
model = "ACME Coyote";
phandle = <0x01>;
str-list = "first", "second";
empty-prop;
byte-array = [01 23 45 67 89 ab cd];

cpus {
#address-cells = <0x01>;
#size-cells = <0x00>;

cpu@0 {
compatible = "arm,cortex-a9";
reg = <0x00>;
};
};

memory@80000000 {
device_type = "memory";
reg = <0x80000000 0x20000000>;
};
};
11 changes: 11 additions & 0 deletions tests/fdt.rs
Original file line number Diff line number Diff line change
Expand Up @@ -140,3 +140,14 @@ fn find_node_by_path() {
assert!(fdt.find_node("/x").is_none());
assert!(fdt.find_node("").is_none());
}

#[test]
fn pretty_print() {
let dtb = include_bytes!("dtb/test_pretty_print.dtb");
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

How about having this test all the DTB/DTS pairs you have in the test directory?

Copy link
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fair. I thought there will be more differences between a human-written DTS and the outputted one (as we use heuristics to get decent DTS formatting for the values), but it seems to be just fine, so I've just added this.

let fdt = Fdt::new(dtb).unwrap();
let s = fdt.to_string();
let expected = include_str!("dts/test_pretty_print.dts")
// account for Windows newlines, if needed
.replace("\r\n", "\n");
assert_eq!(s, expected);
}