Skip to content

Commit 3a0386f

Browse files
committed
fix: aligned dtb in example
Signed-off-by: Woshiluo Luo <woshiluo.luo@outlook.com>
1 parent 0261071 commit 3a0386f

File tree

2 files changed

+28
-7
lines changed

2 files changed

+28
-7
lines changed

examples/hifive-unmatched-a00.rs

Lines changed: 13 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -4,8 +4,6 @@ use alloc::collections::BTreeMap;
44
use serde_derive::Deserialize;
55
use serde_device_tree::Compatible;
66

7-
static DEVICE_TREE: &'static [u8] = include_bytes!("hifive-unmatched-a00.dtb");
8-
97
#[derive(Debug, Deserialize)]
108
struct Tree<'a> {
119
#[serde(rename = "#address-cells")]
@@ -48,8 +46,20 @@ struct Cpu<'a> {
4846
compatible: Compatible<'a>,
4947
}
5048

49+
const RAW_DEVICE_TREE: &'static [u8] = include_bytes!("hifive-unmatched-a00.dtb");
50+
const BUFFER_SIZE: usize = RAW_DEVICE_TREE.len();
51+
52+
#[repr(align(4))]
53+
struct AlignedBuffer {
54+
pub data: [u8; RAW_DEVICE_TREE.len()],
55+
}
56+
5157
fn main() {
52-
let ptr = DEVICE_TREE.as_ptr();
58+
let mut aligned_data: Box<AlignedBuffer> = Box::new(AlignedBuffer {
59+
data: [0; BUFFER_SIZE],
60+
});
61+
aligned_data.data[..BUFFER_SIZE].clone_from_slice(&RAW_DEVICE_TREE);
62+
let ptr = aligned_data.data.as_ptr();
5363
let t: Tree = unsafe { serde_device_tree::from_raw(ptr) }.unwrap();
5464
println!("#address_cells = {}", t.num_address_cells);
5565
println!("#size_cells = {}", t.num_size_cells);

examples/qemu-virt.rs

Lines changed: 15 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -16,10 +16,21 @@ use serde_device_tree::{
1616
from_raw_mut, Dtb, DtbPtr,
1717
};
1818

19+
const RAW_DEVICE_TREE: &'static [u8] = include_bytes!("qemu-virt.dtb");
20+
const BUFFER_SIZE: usize = RAW_DEVICE_TREE.len();
21+
22+
#[repr(align(4))]
23+
struct AlignedBuffer {
24+
pub data: [u8; RAW_DEVICE_TREE.len()],
25+
}
26+
1927
fn main() -> Result<(), Error> {
2028
// 整个设备树二进制文件需要装载到一块可写的内存区域
21-
static DEVICE_TREE: &[u8] = include_bytes!("qemu-virt.dtb");
22-
let mut slice = DEVICE_TREE.to_vec();
29+
let mut aligned_data: Box<AlignedBuffer> = Box::new(AlignedBuffer {
30+
data: [0; BUFFER_SIZE],
31+
});
32+
aligned_data.data[..BUFFER_SIZE].clone_from_slice(&RAW_DEVICE_TREE);
33+
let mut slice = aligned_data.data.to_vec();
2334
// 这一步验证了设备树首部的正确性,`DtbPtr` 类型可以安全地传递到任何地方,
2435
// 甚至跨地址空间(如果你知道偏移的话)。
2536
let ptr = DtbPtr::from_raw(slice.as_mut_ptr())?;
@@ -127,10 +138,10 @@ fn main() -> Result<(), Error> {
127138

128139
// 解析过程中,设备树的内容被修改了。
129140
// 因此若要以其他方式再次访问设备树,先将这次解析的结果释放。
130-
assert_ne!(slice, DEVICE_TREE);
141+
assert_ne!(slice, RAW_DEVICE_TREE);
131142
}
132143
// 释放后,内存会恢复原状。
133-
assert_eq!(slice, DEVICE_TREE);
144+
assert_eq!(slice, RAW_DEVICE_TREE);
134145

135146
Ok(())
136147
}

0 commit comments

Comments
 (0)