blob: a6d57392887eeae6f3c9f10dbbad70970d92ff51 [file] [log] [blame]
David Brazdil1baa9a92022-06-28 14:47:50 +01001// Copyright 2022, The Android Open Source Project
2//
3// Licensed under the Apache License, Version 2.0 (the "License");
4// you may not use this file except in compliance with the License.
5// You may obtain a copy of the License at
6//
7// http://www.apache.org/licenses/LICENSE-2.0
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS,
11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12// See the License for the specific language governing permissions and
13// limitations under the License.
14
15//! Wrapper around libfdt library. Provides parsing/generating functionality
16//! to a bare-metal environment.
17
18#![no_std]
19
Andrew Walbran55ad01b2022-12-05 17:00:40 +000020mod iterators;
21
Jaewan Kimfe06c852023-10-05 23:40:06 +090022pub use iterators::{
23 AddressRange, CellIterator, CompatibleIterator, MemRegIterator, RangesIterator, Reg,
Jaewan Kimbc828d72023-09-19 15:52:08 +090024 RegIterator, SubnodeIterator,
Jaewan Kimfe06c852023-10-05 23:40:06 +090025};
Andrew Walbran55ad01b2022-12-05 17:00:40 +000026
Jiyong Parke9d87e82023-03-21 19:28:40 +090027use core::cmp::max;
David Brazdil1baa9a92022-06-28 14:47:50 +010028use core::ffi::{c_int, c_void, CStr};
29use core::fmt;
30use core::mem;
Alice Wang2422bdc2023-06-12 08:37:55 +000031use core::ops::Range;
David Brazdil1baa9a92022-06-28 14:47:50 +010032use core::result;
Pierre-Clément Tosic27c4272023-05-19 15:46:26 +000033use zerocopy::AsBytes as _;
David Brazdil1baa9a92022-06-28 14:47:50 +010034
35/// Error type corresponding to libfdt error codes.
36#[derive(Clone, Copy, Debug, Eq, PartialEq)]
37pub enum FdtError {
38 /// FDT_ERR_NOTFOUND
39 NotFound,
40 /// FDT_ERR_EXISTS
41 Exists,
42 /// FDT_ERR_NOSPACE
43 NoSpace,
44 /// FDT_ERR_BADOFFSET
45 BadOffset,
46 /// FDT_ERR_BADPATH
47 BadPath,
48 /// FDT_ERR_BADPHANDLE
49 BadPhandle,
50 /// FDT_ERR_BADSTATE
51 BadState,
52 /// FDT_ERR_TRUNCATED
53 Truncated,
54 /// FDT_ERR_BADMAGIC
55 BadMagic,
56 /// FDT_ERR_BADVERSION
57 BadVersion,
58 /// FDT_ERR_BADSTRUCTURE
59 BadStructure,
60 /// FDT_ERR_BADLAYOUT
61 BadLayout,
62 /// FDT_ERR_INTERNAL
63 Internal,
64 /// FDT_ERR_BADNCELLS
65 BadNCells,
66 /// FDT_ERR_BADVALUE
67 BadValue,
68 /// FDT_ERR_BADOVERLAY
69 BadOverlay,
70 /// FDT_ERR_NOPHANDLES
71 NoPhandles,
72 /// FDT_ERR_BADFLAGS
73 BadFlags,
74 /// FDT_ERR_ALIGNMENT
75 Alignment,
76 /// Unexpected error code
77 Unknown(i32),
78}
79
80impl fmt::Display for FdtError {
81 /// Prints error messages from libfdt.h documentation.
82 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
83 match self {
84 Self::NotFound => write!(f, "The requested node or property does not exist"),
85 Self::Exists => write!(f, "Attempted to create an existing node or property"),
86 Self::NoSpace => write!(f, "Insufficient buffer space to contain the expanded tree"),
87 Self::BadOffset => write!(f, "Structure block offset is out-of-bounds or invalid"),
88 Self::BadPath => write!(f, "Badly formatted path"),
89 Self::BadPhandle => write!(f, "Invalid phandle length or value"),
90 Self::BadState => write!(f, "Received incomplete device tree"),
91 Self::Truncated => write!(f, "Device tree or sub-block is improperly terminated"),
92 Self::BadMagic => write!(f, "Device tree header missing its magic number"),
93 Self::BadVersion => write!(f, "Device tree has a version which can't be handled"),
94 Self::BadStructure => write!(f, "Device tree has a corrupt structure block"),
95 Self::BadLayout => write!(f, "Device tree sub-blocks in unsupported order"),
96 Self::Internal => write!(f, "libfdt has failed an internal assertion"),
97 Self::BadNCells => write!(f, "Bad format or value of #address-cells or #size-cells"),
98 Self::BadValue => write!(f, "Unexpected property value"),
99 Self::BadOverlay => write!(f, "Overlay cannot be applied"),
100 Self::NoPhandles => write!(f, "Device tree doesn't have any phandle available anymore"),
101 Self::BadFlags => write!(f, "Invalid flag or invalid combination of flags"),
102 Self::Alignment => write!(f, "Device tree base address is not 8-byte aligned"),
103 Self::Unknown(e) => write!(f, "Unknown libfdt error '{e}'"),
104 }
105 }
106}
107
108/// Result type with FdtError enum.
109pub type Result<T> = result::Result<T, FdtError>;
110
111fn fdt_err(val: c_int) -> Result<c_int> {
112 if val >= 0 {
113 Ok(val)
114 } else {
115 Err(match -val as _ {
116 libfdt_bindgen::FDT_ERR_NOTFOUND => FdtError::NotFound,
117 libfdt_bindgen::FDT_ERR_EXISTS => FdtError::Exists,
118 libfdt_bindgen::FDT_ERR_NOSPACE => FdtError::NoSpace,
119 libfdt_bindgen::FDT_ERR_BADOFFSET => FdtError::BadOffset,
120 libfdt_bindgen::FDT_ERR_BADPATH => FdtError::BadPath,
121 libfdt_bindgen::FDT_ERR_BADPHANDLE => FdtError::BadPhandle,
122 libfdt_bindgen::FDT_ERR_BADSTATE => FdtError::BadState,
123 libfdt_bindgen::FDT_ERR_TRUNCATED => FdtError::Truncated,
124 libfdt_bindgen::FDT_ERR_BADMAGIC => FdtError::BadMagic,
125 libfdt_bindgen::FDT_ERR_BADVERSION => FdtError::BadVersion,
126 libfdt_bindgen::FDT_ERR_BADSTRUCTURE => FdtError::BadStructure,
127 libfdt_bindgen::FDT_ERR_BADLAYOUT => FdtError::BadLayout,
128 libfdt_bindgen::FDT_ERR_INTERNAL => FdtError::Internal,
129 libfdt_bindgen::FDT_ERR_BADNCELLS => FdtError::BadNCells,
130 libfdt_bindgen::FDT_ERR_BADVALUE => FdtError::BadValue,
131 libfdt_bindgen::FDT_ERR_BADOVERLAY => FdtError::BadOverlay,
132 libfdt_bindgen::FDT_ERR_NOPHANDLES => FdtError::NoPhandles,
133 libfdt_bindgen::FDT_ERR_BADFLAGS => FdtError::BadFlags,
134 libfdt_bindgen::FDT_ERR_ALIGNMENT => FdtError::Alignment,
135 _ => FdtError::Unknown(val),
136 })
137 }
138}
139
140fn fdt_err_expect_zero(val: c_int) -> Result<()> {
141 match fdt_err(val)? {
142 0 => Ok(()),
143 _ => Err(FdtError::Unknown(val)),
144 }
145}
146
Pierre-Clément Tosib244d932022-11-24 16:45:53 +0000147fn fdt_err_or_option(val: c_int) -> Result<Option<c_int>> {
148 match fdt_err(val) {
149 Ok(val) => Ok(Some(val)),
150 Err(FdtError::NotFound) => Ok(None),
151 Err(e) => Err(e),
152 }
153}
154
David Brazdil1baa9a92022-06-28 14:47:50 +0100155/// Value of a #address-cells property.
Andrew Walbranb39e6922022-12-05 17:01:20 +0000156#[derive(Copy, Clone, Debug, Eq, PartialEq)]
David Brazdil1baa9a92022-06-28 14:47:50 +0100157enum AddrCells {
158 Single = 1,
159 Double = 2,
Andrew Walbranb39e6922022-12-05 17:01:20 +0000160 Triple = 3,
David Brazdil1baa9a92022-06-28 14:47:50 +0100161}
162
163impl TryFrom<c_int> for AddrCells {
164 type Error = FdtError;
165
166 fn try_from(res: c_int) -> Result<Self> {
167 match fdt_err(res)? {
168 x if x == Self::Single as c_int => Ok(Self::Single),
169 x if x == Self::Double as c_int => Ok(Self::Double),
Andrew Walbranb39e6922022-12-05 17:01:20 +0000170 x if x == Self::Triple as c_int => Ok(Self::Triple),
David Brazdil1baa9a92022-06-28 14:47:50 +0100171 _ => Err(FdtError::BadNCells),
172 }
173 }
174}
175
176/// Value of a #size-cells property.
Andrew Walbranb39e6922022-12-05 17:01:20 +0000177#[derive(Copy, Clone, Debug, Eq, PartialEq)]
David Brazdil1baa9a92022-06-28 14:47:50 +0100178enum SizeCells {
179 None = 0,
180 Single = 1,
181 Double = 2,
182}
183
184impl TryFrom<c_int> for SizeCells {
185 type Error = FdtError;
186
187 fn try_from(res: c_int) -> Result<Self> {
188 match fdt_err(res)? {
189 x if x == Self::None as c_int => Ok(Self::None),
190 x if x == Self::Single as c_int => Ok(Self::Single),
191 x if x == Self::Double as c_int => Ok(Self::Double),
192 _ => Err(FdtError::BadNCells),
193 }
194 }
195}
196
David Brazdil1baa9a92022-06-28 14:47:50 +0100197/// DT node.
Alice Wang9d4df702023-05-25 14:14:12 +0000198#[derive(Clone, Copy, Debug)]
David Brazdil1baa9a92022-06-28 14:47:50 +0100199pub struct FdtNode<'a> {
200 fdt: &'a Fdt,
201 offset: c_int,
202}
203
204impl<'a> FdtNode<'a> {
Jaewan Kimb3dcfc22023-09-20 10:20:52 +0900205 /// Creates immutable node from a mutable node at the same offset.
Jiyong Park9c63cd12023-03-21 17:53:07 +0900206 pub fn from_mut(other: &'a FdtNodeMut) -> Self {
207 FdtNode { fdt: other.fdt, offset: other.offset }
208 }
Jaewan Kimb3dcfc22023-09-20 10:20:52 +0900209 /// Returns parent node.
David Brazdil1baa9a92022-06-28 14:47:50 +0100210 pub fn parent(&self) -> Result<Self> {
Andrew Walbran84b9a232023-07-05 14:01:40 +0000211 // SAFETY: Accesses (read-only) are constrained to the DT totalsize.
David Brazdil1baa9a92022-06-28 14:47:50 +0100212 let ret = unsafe { libfdt_bindgen::fdt_parent_offset(self.fdt.as_ptr(), self.offset) };
213
214 Ok(Self { fdt: self.fdt, offset: fdt_err(ret)? })
215 }
216
Jaewan Kimb3dcfc22023-09-20 10:20:52 +0900217 /// Returns the standard (deprecated) device_type <string> property.
Pierre-Clément Tosib244d932022-11-24 16:45:53 +0000218 pub fn device_type(&self) -> Result<Option<&CStr>> {
David Brazdil1baa9a92022-06-28 14:47:50 +0100219 self.getprop_str(CStr::from_bytes_with_nul(b"device_type\0").unwrap())
220 }
221
Jaewan Kimb3dcfc22023-09-20 10:20:52 +0900222 /// Returns the standard reg <prop-encoded-array> property.
Pierre-Clément Tosib244d932022-11-24 16:45:53 +0000223 pub fn reg(&self) -> Result<Option<RegIterator<'a>>> {
224 let reg = CStr::from_bytes_with_nul(b"reg\0").unwrap();
David Brazdil1baa9a92022-06-28 14:47:50 +0100225
Pierre-Clément Tosib244d932022-11-24 16:45:53 +0000226 if let Some(cells) = self.getprop_cells(reg)? {
227 let parent = self.parent()?;
David Brazdil1baa9a92022-06-28 14:47:50 +0100228
Pierre-Clément Tosib244d932022-11-24 16:45:53 +0000229 let addr_cells = parent.address_cells()?;
230 let size_cells = parent.size_cells()?;
231
232 Ok(Some(RegIterator::new(cells, addr_cells, size_cells)))
233 } else {
234 Ok(None)
235 }
David Brazdil1baa9a92022-06-28 14:47:50 +0100236 }
237
Jaewan Kimb3dcfc22023-09-20 10:20:52 +0900238 /// Returns the standard ranges property.
Andrew Walbranb39e6922022-12-05 17:01:20 +0000239 pub fn ranges<A, P, S>(&self) -> Result<Option<RangesIterator<'a, A, P, S>>> {
240 let ranges = CStr::from_bytes_with_nul(b"ranges\0").unwrap();
241 if let Some(cells) = self.getprop_cells(ranges)? {
242 let parent = self.parent()?;
243 let addr_cells = self.address_cells()?;
244 let parent_addr_cells = parent.address_cells()?;
245 let size_cells = self.size_cells()?;
246 Ok(Some(RangesIterator::<A, P, S>::new(
247 cells,
248 addr_cells,
249 parent_addr_cells,
250 size_cells,
251 )))
252 } else {
253 Ok(None)
254 }
255 }
256
Jaewan Kimaa638702023-09-19 13:34:01 +0900257 /// Returns the node name.
258 pub fn name(&self) -> Result<&'a CStr> {
259 let mut len: c_int = 0;
260 // SAFETY: Accesses are constrained to the DT totalsize (validated by ctor). On success, the
261 // function returns valid null terminating string and otherwise returned values are dropped.
262 let name = unsafe { libfdt_bindgen::fdt_get_name(self.fdt.as_ptr(), self.offset, &mut len) }
263 as *const c_void;
264 let len = usize::try_from(fdt_err(len)?).unwrap();
265 let name = self.fdt.get_from_ptr(name, len + 1)?;
266 CStr::from_bytes_with_nul(name).map_err(|_| FdtError::Internal)
267 }
268
Jaewan Kimb3dcfc22023-09-20 10:20:52 +0900269 /// Returns the value of a given <string> property.
Pierre-Clément Tosib244d932022-11-24 16:45:53 +0000270 pub fn getprop_str(&self, name: &CStr) -> Result<Option<&CStr>> {
271 let value = if let Some(bytes) = self.getprop(name)? {
272 Some(CStr::from_bytes_with_nul(bytes).map_err(|_| FdtError::BadValue)?)
273 } else {
274 None
275 };
276 Ok(value)
David Brazdil1baa9a92022-06-28 14:47:50 +0100277 }
278
Jaewan Kimb3dcfc22023-09-20 10:20:52 +0900279 /// Returns the value of a given property as an array of cells.
Pierre-Clément Tosib244d932022-11-24 16:45:53 +0000280 pub fn getprop_cells(&self, name: &CStr) -> Result<Option<CellIterator<'a>>> {
281 if let Some(cells) = self.getprop(name)? {
282 Ok(Some(CellIterator::new(cells)))
283 } else {
284 Ok(None)
285 }
David Brazdil1baa9a92022-06-28 14:47:50 +0100286 }
287
Jaewan Kimb3dcfc22023-09-20 10:20:52 +0900288 /// Returns the value of a given <u32> property.
Pierre-Clément Tosib244d932022-11-24 16:45:53 +0000289 pub fn getprop_u32(&self, name: &CStr) -> Result<Option<u32>> {
290 let value = if let Some(bytes) = self.getprop(name)? {
291 Some(u32::from_be_bytes(bytes.try_into().map_err(|_| FdtError::BadValue)?))
292 } else {
293 None
294 };
295 Ok(value)
David Brazdil1baa9a92022-06-28 14:47:50 +0100296 }
297
Jaewan Kimb3dcfc22023-09-20 10:20:52 +0900298 /// Returns the value of a given <u64> property.
Pierre-Clément Tosib244d932022-11-24 16:45:53 +0000299 pub fn getprop_u64(&self, name: &CStr) -> Result<Option<u64>> {
300 let value = if let Some(bytes) = self.getprop(name)? {
301 Some(u64::from_be_bytes(bytes.try_into().map_err(|_| FdtError::BadValue)?))
302 } else {
303 None
304 };
305 Ok(value)
David Brazdil1baa9a92022-06-28 14:47:50 +0100306 }
307
Jaewan Kimb3dcfc22023-09-20 10:20:52 +0900308 /// Returns the value of a given property.
Pierre-Clément Tosib244d932022-11-24 16:45:53 +0000309 pub fn getprop(&self, name: &CStr) -> Result<Option<&'a [u8]>> {
Jiyong Park9c63cd12023-03-21 17:53:07 +0900310 if let Some((prop, len)) = Self::getprop_internal(self.fdt, self.offset, name)? {
Jaewan Kimaa638702023-09-19 13:34:01 +0900311 Ok(Some(self.fdt.get_from_ptr(prop, len)?))
Jiyong Park9c63cd12023-03-21 17:53:07 +0900312 } else {
313 Ok(None) // property was not found
314 }
315 }
316
Jaewan Kimb3dcfc22023-09-20 10:20:52 +0900317 /// Returns the pointer and size of the property named `name`, in a node at offset `offset`, in
Jiyong Park9c63cd12023-03-21 17:53:07 +0900318 /// a device tree `fdt`. The pointer is guaranteed to be non-null, in which case error returns.
319 fn getprop_internal(
320 fdt: &'a Fdt,
321 offset: c_int,
322 name: &CStr,
323 ) -> Result<Option<(*const c_void, usize)>> {
David Brazdil1baa9a92022-06-28 14:47:50 +0100324 let mut len: i32 = 0;
Andrew Walbran84b9a232023-07-05 14:01:40 +0000325 // SAFETY: Accesses are constrained to the DT totalsize (validated by ctor) and the
David Brazdil1baa9a92022-06-28 14:47:50 +0100326 // function respects the passed number of characters.
327 let prop = unsafe {
328 libfdt_bindgen::fdt_getprop_namelen(
Jiyong Park9c63cd12023-03-21 17:53:07 +0900329 fdt.as_ptr(),
330 offset,
David Brazdil1baa9a92022-06-28 14:47:50 +0100331 name.as_ptr(),
332 // *_namelen functions don't include the trailing nul terminator in 'len'.
333 name.to_bytes().len().try_into().map_err(|_| FdtError::BadPath)?,
334 &mut len as *mut i32,
335 )
336 } as *const u8;
Pierre-Clément Tosib244d932022-11-24 16:45:53 +0000337
338 let Some(len) = fdt_err_or_option(len)? else {
339 return Ok(None); // Property was not found.
340 };
Jaewan Kimaa638702023-09-19 13:34:01 +0900341 let len = usize::try_from(len).unwrap();
Pierre-Clément Tosib244d932022-11-24 16:45:53 +0000342
David Brazdil1baa9a92022-06-28 14:47:50 +0100343 if prop.is_null() {
Pierre-Clément Tosib244d932022-11-24 16:45:53 +0000344 // We expected an error code in len but still received a valid value?!
345 return Err(FdtError::Internal);
David Brazdil1baa9a92022-06-28 14:47:50 +0100346 }
Jiyong Park9c63cd12023-03-21 17:53:07 +0900347 Ok(Some((prop.cast::<c_void>(), len)))
David Brazdil1baa9a92022-06-28 14:47:50 +0100348 }
349
Jaewan Kimb3dcfc22023-09-20 10:20:52 +0900350 /// Returns reference to the containing device tree.
David Brazdil1baa9a92022-06-28 14:47:50 +0100351 pub fn fdt(&self) -> &Fdt {
352 self.fdt
353 }
354
Alice Wang474c0ee2023-09-14 12:52:33 +0000355 /// Returns the compatible node of the given name that is next after this node.
356 pub fn next_compatible(self, compatible: &CStr) -> Result<Option<Self>> {
Andrew Walbran84b9a232023-07-05 14:01:40 +0000357 // SAFETY: Accesses (read-only) are constrained to the DT totalsize.
Pierre-Clément Tosi41c158e2022-11-21 19:16:25 +0000358 let ret = unsafe {
359 libfdt_bindgen::fdt_node_offset_by_compatible(
360 self.fdt.as_ptr(),
361 self.offset,
362 compatible.as_ptr(),
363 )
364 };
365
Pierre-Clément Tosib244d932022-11-24 16:45:53 +0000366 Ok(fdt_err_or_option(ret)?.map(|offset| Self { fdt: self.fdt, offset }))
Pierre-Clément Tosi41c158e2022-11-21 19:16:25 +0000367 }
368
Alice Wang474c0ee2023-09-14 12:52:33 +0000369 /// Returns the first range of `reg` in this node.
370 pub fn first_reg(&self) -> Result<Reg<u64>> {
371 self.reg()?.ok_or(FdtError::NotFound)?.next().ok_or(FdtError::NotFound)
372 }
373
David Brazdil1baa9a92022-06-28 14:47:50 +0100374 fn address_cells(&self) -> Result<AddrCells> {
Andrew Walbran84b9a232023-07-05 14:01:40 +0000375 // SAFETY: Accesses are constrained to the DT totalsize (validated by ctor).
David Brazdil1baa9a92022-06-28 14:47:50 +0100376 unsafe { libfdt_bindgen::fdt_address_cells(self.fdt.as_ptr(), self.offset) }
377 .try_into()
378 .map_err(|_| FdtError::Internal)
379 }
380
381 fn size_cells(&self) -> Result<SizeCells> {
Andrew Walbran84b9a232023-07-05 14:01:40 +0000382 // SAFETY: Accesses are constrained to the DT totalsize (validated by ctor).
David Brazdil1baa9a92022-06-28 14:47:50 +0100383 unsafe { libfdt_bindgen::fdt_size_cells(self.fdt.as_ptr(), self.offset) }
384 .try_into()
385 .map_err(|_| FdtError::Internal)
386 }
Jaewan Kimbc828d72023-09-19 15:52:08 +0900387
388 /// Returns an iterator of subnodes
389 pub fn subnodes(&'a self) -> Result<SubnodeIterator<'a>> {
390 SubnodeIterator::new(self)
391 }
392
393 fn first_subnode(&self) -> Result<Option<Self>> {
394 // SAFETY: Accesses (read-only) are constrained to the DT totalsize.
395 let ret = unsafe { libfdt_bindgen::fdt_first_subnode(self.fdt.as_ptr(), self.offset) };
396
397 Ok(fdt_err_or_option(ret)?.map(|offset| FdtNode { fdt: self.fdt, offset }))
398 }
399
400 fn next_subnode(&self) -> Result<Option<Self>> {
401 // SAFETY: Accesses (read-only) are constrained to the DT totalsize.
402 let ret = unsafe { libfdt_bindgen::fdt_next_subnode(self.fdt.as_ptr(), self.offset) };
403
404 Ok(fdt_err_or_option(ret)?.map(|offset| FdtNode { fdt: self.fdt, offset }))
405 }
David Brazdil1baa9a92022-06-28 14:47:50 +0100406}
407
Pierre-Clément Tosi1b0d8902022-11-21 18:16:59 +0000408/// Mutable FDT node.
409pub struct FdtNodeMut<'a> {
410 fdt: &'a mut Fdt,
411 offset: c_int,
412}
413
414impl<'a> FdtNodeMut<'a> {
Jaewan Kimb3dcfc22023-09-20 10:20:52 +0900415 /// Appends a property name-value (possibly empty) pair to the given node.
Pierre-Clément Tosi1b0d8902022-11-21 18:16:59 +0000416 pub fn appendprop<T: AsRef<[u8]>>(&mut self, name: &CStr, value: &T) -> Result<()> {
Andrew Walbran84b9a232023-07-05 14:01:40 +0000417 // SAFETY: Accesses are constrained to the DT totalsize (validated by ctor).
Pierre-Clément Tosi1b0d8902022-11-21 18:16:59 +0000418 let ret = unsafe {
419 libfdt_bindgen::fdt_appendprop(
420 self.fdt.as_mut_ptr(),
421 self.offset,
422 name.as_ptr(),
423 value.as_ref().as_ptr().cast::<c_void>(),
424 value.as_ref().len().try_into().map_err(|_| FdtError::BadValue)?,
425 )
426 };
427
428 fdt_err_expect_zero(ret)
429 }
430
Jaewan Kimb3dcfc22023-09-20 10:20:52 +0900431 /// Appends a (address, size) pair property to the given node.
Pierre-Clément Tosi1b0d8902022-11-21 18:16:59 +0000432 pub fn appendprop_addrrange(&mut self, name: &CStr, addr: u64, size: u64) -> Result<()> {
Andrew Walbran84b9a232023-07-05 14:01:40 +0000433 // SAFETY: Accesses are constrained to the DT totalsize (validated by ctor).
Pierre-Clément Tosi1b0d8902022-11-21 18:16:59 +0000434 let ret = unsafe {
435 libfdt_bindgen::fdt_appendprop_addrrange(
436 self.fdt.as_mut_ptr(),
437 self.parent()?.offset,
438 self.offset,
439 name.as_ptr(),
440 addr,
441 size,
442 )
443 };
444
445 fdt_err_expect_zero(ret)
446 }
447
Jaewan Kimb3dcfc22023-09-20 10:20:52 +0900448 /// Sets a property name-value pair to the given node.
449 ///
450 /// This may create a new prop or replace existing value.
Jaewan Kimba8929b2023-01-13 11:13:29 +0900451 pub fn setprop(&mut self, name: &CStr, value: &[u8]) -> Result<()> {
Andrew Walbran84b9a232023-07-05 14:01:40 +0000452 // SAFETY: New value size is constrained to the DT totalsize
Jaewan Kimba8929b2023-01-13 11:13:29 +0900453 // (validated by underlying libfdt).
454 let ret = unsafe {
455 libfdt_bindgen::fdt_setprop(
456 self.fdt.as_mut_ptr(),
457 self.offset,
458 name.as_ptr(),
459 value.as_ptr().cast::<c_void>(),
460 value.len().try_into().map_err(|_| FdtError::BadValue)?,
461 )
462 };
463
464 fdt_err_expect_zero(ret)
465 }
466
Jaewan Kimb3dcfc22023-09-20 10:20:52 +0900467 /// Sets the value of the given property with the given value, and ensure that the given
468 /// value has the same length as the current value length.
469 ///
470 /// This can only be used to replace existing value.
Jiyong Park9c63cd12023-03-21 17:53:07 +0900471 pub fn setprop_inplace(&mut self, name: &CStr, value: &[u8]) -> Result<()> {
Andrew Walbran84b9a232023-07-05 14:01:40 +0000472 // SAFETY: fdt size is not altered
Jiyong Park9c63cd12023-03-21 17:53:07 +0900473 let ret = unsafe {
474 libfdt_bindgen::fdt_setprop_inplace(
475 self.fdt.as_mut_ptr(),
476 self.offset,
477 name.as_ptr(),
478 value.as_ptr().cast::<c_void>(),
479 value.len().try_into().map_err(|_| FdtError::BadValue)?,
480 )
481 };
482
483 fdt_err_expect_zero(ret)
484 }
485
Jaewan Kimb3dcfc22023-09-20 10:20:52 +0900486 /// Sets the value of the given (address, size) pair property with the given value, and
487 /// ensure that the given value has the same length as the current value length.
488 ///
489 /// This can only be used to replace existing value.
Pierre-Clément Tosic27c4272023-05-19 15:46:26 +0000490 pub fn setprop_addrrange_inplace(&mut self, name: &CStr, addr: u64, size: u64) -> Result<()> {
491 let pair = [addr.to_be(), size.to_be()];
492 self.setprop_inplace(name, pair.as_bytes())
493 }
494
Jaewan Kimb3dcfc22023-09-20 10:20:52 +0900495 /// Sets a flag-like empty property.
496 ///
497 /// This may create a new prop or replace existing value.
Pierre-Clément Tosi4ba79662023-02-13 11:22:41 +0000498 pub fn setprop_empty(&mut self, name: &CStr) -> Result<()> {
499 self.setprop(name, &[])
500 }
501
Jaewan Kimb3dcfc22023-09-20 10:20:52 +0900502 /// Deletes the given property.
Pierre-Clément Tosi4ba79662023-02-13 11:22:41 +0000503 pub fn delprop(&mut self, name: &CStr) -> Result<()> {
Andrew Walbran84b9a232023-07-05 14:01:40 +0000504 // SAFETY: Accesses are constrained to the DT totalsize (validated by ctor) when the
Pierre-Clément Tosi4ba79662023-02-13 11:22:41 +0000505 // library locates the node's property. Removing the property may shift the offsets of
506 // other nodes and properties but the borrow checker should prevent this function from
507 // being called when FdtNode instances are in use.
508 let ret = unsafe {
509 libfdt_bindgen::fdt_delprop(self.fdt.as_mut_ptr(), self.offset, name.as_ptr())
510 };
511
512 fdt_err_expect_zero(ret)
513 }
514
Jaewan Kimb3dcfc22023-09-20 10:20:52 +0900515 /// Sets the given property with FDT_NOP, effectively removing it from the DT.
Pierre-Clément Tosibe3a97b2023-05-19 14:56:23 +0000516 pub fn nop_property(&mut self, name: &CStr) -> Result<()> {
Andrew Walbran84b9a232023-07-05 14:01:40 +0000517 // SAFETY: Accesses are constrained to the DT totalsize (validated by ctor) when the
Pierre-Clément Tosibe3a97b2023-05-19 14:56:23 +0000518 // library locates the node's property.
519 let ret = unsafe {
520 libfdt_bindgen::fdt_nop_property(self.fdt.as_mut_ptr(), self.offset, name.as_ptr())
521 };
522
523 fdt_err_expect_zero(ret)
524 }
525
Jaewan Kimb3dcfc22023-09-20 10:20:52 +0900526 /// Trims the size of the given property to new_size.
Jiyong Park9c63cd12023-03-21 17:53:07 +0900527 pub fn trimprop(&mut self, name: &CStr, new_size: usize) -> Result<()> {
528 let (prop, len) =
529 FdtNode::getprop_internal(self.fdt, self.offset, name)?.ok_or(FdtError::NotFound)?;
530 if len == new_size {
531 return Ok(());
532 }
533 if new_size > len {
534 return Err(FdtError::NoSpace);
535 }
536
Andrew Walbran84b9a232023-07-05 14:01:40 +0000537 // SAFETY: new_size is smaller than the old size
Jiyong Park9c63cd12023-03-21 17:53:07 +0900538 let ret = unsafe {
539 libfdt_bindgen::fdt_setprop(
540 self.fdt.as_mut_ptr(),
541 self.offset,
542 name.as_ptr(),
543 prop.cast::<c_void>(),
544 new_size.try_into().map_err(|_| FdtError::BadValue)?,
545 )
546 };
547
548 fdt_err_expect_zero(ret)
549 }
550
Jaewan Kimb3dcfc22023-09-20 10:20:52 +0900551 /// Returns reference to the containing device tree.
Pierre-Clément Tosi1b0d8902022-11-21 18:16:59 +0000552 pub fn fdt(&mut self) -> &mut Fdt {
553 self.fdt
554 }
555
Jaewan Kimb3dcfc22023-09-20 10:20:52 +0900556 /// Adds a new subnode to the given node and return it as a FdtNodeMut on success.
Pierre-Clément Tosi1b0d8902022-11-21 18:16:59 +0000557 pub fn add_subnode(&'a mut self, name: &CStr) -> Result<Self> {
Andrew Walbran84b9a232023-07-05 14:01:40 +0000558 // SAFETY: Accesses are constrained to the DT totalsize (validated by ctor).
Pierre-Clément Tosi1b0d8902022-11-21 18:16:59 +0000559 let ret = unsafe {
560 libfdt_bindgen::fdt_add_subnode(self.fdt.as_mut_ptr(), self.offset, name.as_ptr())
561 };
562
563 Ok(Self { fdt: self.fdt, offset: fdt_err(ret)? })
564 }
565
566 fn parent(&'a self) -> Result<FdtNode<'a>> {
Andrew Walbran84b9a232023-07-05 14:01:40 +0000567 // SAFETY: Accesses (read-only) are constrained to the DT totalsize.
Pierre-Clément Tosi1b0d8902022-11-21 18:16:59 +0000568 let ret = unsafe { libfdt_bindgen::fdt_parent_offset(self.fdt.as_ptr(), self.offset) };
569
570 Ok(FdtNode { fdt: &*self.fdt, offset: fdt_err(ret)? })
571 }
Jiyong Park9c63cd12023-03-21 17:53:07 +0900572
Jaewan Kimb3dcfc22023-09-20 10:20:52 +0900573 /// Returns the compatible node of the given name that is next after this node.
Jiyong Park9c63cd12023-03-21 17:53:07 +0900574 pub fn next_compatible(self, compatible: &CStr) -> Result<Option<Self>> {
Andrew Walbran84b9a232023-07-05 14:01:40 +0000575 // SAFETY: Accesses (read-only) are constrained to the DT totalsize.
Jiyong Park9c63cd12023-03-21 17:53:07 +0900576 let ret = unsafe {
577 libfdt_bindgen::fdt_node_offset_by_compatible(
578 self.fdt.as_ptr(),
579 self.offset,
580 compatible.as_ptr(),
581 )
582 };
583
584 Ok(fdt_err_or_option(ret)?.map(|offset| Self { fdt: self.fdt, offset }))
585 }
586
Jaewan Kimb3dcfc22023-09-20 10:20:52 +0900587 /// Deletes the node effectively by overwriting this node and its subtree with nop tags.
588 /// Returns the next compatible node of the given name.
Jiyong Park9c63cd12023-03-21 17:53:07 +0900589 // Side note: without this, filterint out excessive compatible nodes from the DT is impossible.
590 // The reason is that libfdt ensures that the node from where the search for the next
591 // compatible node is started is always a valid one -- except for the special case of offset =
592 // -1 which is to find the first compatible node. So, we can't delete a node and then find the
593 // next compatible node from it.
594 //
595 // We can't do in the opposite direction either. If we call next_compatible to find the next
596 // node, and delete the current node, the Rust borrow checker kicks in. The next node has a
597 // mutable reference to DT, so we can't use current node (which also has a mutable reference to
598 // DT).
599 pub fn delete_and_next_compatible(self, compatible: &CStr) -> Result<Option<Self>> {
Andrew Walbran84b9a232023-07-05 14:01:40 +0000600 // SAFETY: Accesses (read-only) are constrained to the DT totalsize.
Jiyong Park9c63cd12023-03-21 17:53:07 +0900601 let ret = unsafe {
602 libfdt_bindgen::fdt_node_offset_by_compatible(
603 self.fdt.as_ptr(),
604 self.offset,
605 compatible.as_ptr(),
606 )
607 };
608 let next_offset = fdt_err_or_option(ret)?;
609
Andrew Walbran84b9a232023-07-05 14:01:40 +0000610 // SAFETY: fdt_nop_node alter only the bytes in the blob which contain the node and its
Jiyong Park9c63cd12023-03-21 17:53:07 +0900611 // properties and subnodes, and will not alter or move any other part of the tree.
612 let ret = unsafe { libfdt_bindgen::fdt_nop_node(self.fdt.as_mut_ptr(), self.offset) };
613 fdt_err_expect_zero(ret)?;
614
615 Ok(next_offset.map(|offset| Self { fdt: self.fdt, offset }))
616 }
Pierre-Clément Tosi1b0d8902022-11-21 18:16:59 +0000617}
618
Pierre-Clément Tosi1b0d8902022-11-21 18:16:59 +0000619/// Wrapper around low-level libfdt functions.
Alice Wang9d4df702023-05-25 14:14:12 +0000620#[derive(Debug)]
David Brazdil1baa9a92022-06-28 14:47:50 +0100621#[repr(transparent)]
622pub struct Fdt {
Pierre-Clément Tosief2030e2022-11-28 11:21:20 +0000623 buffer: [u8],
David Brazdil1baa9a92022-06-28 14:47:50 +0100624}
625
626impl Fdt {
627 /// Wraps a slice containing a Flattened Device Tree.
628 ///
629 /// Fails if the FDT does not pass validation.
630 pub fn from_slice(fdt: &[u8]) -> Result<&Self> {
Andrew Walbran84b9a232023-07-05 14:01:40 +0000631 // SAFETY: The FDT will be validated before it is returned.
David Brazdil1baa9a92022-06-28 14:47:50 +0100632 let fdt = unsafe { Self::unchecked_from_slice(fdt) };
633 fdt.check_full()?;
634 Ok(fdt)
635 }
636
Pierre-Clément Tosi1b0d8902022-11-21 18:16:59 +0000637 /// Wraps a mutable slice containing a Flattened Device Tree.
638 ///
639 /// Fails if the FDT does not pass validation.
640 pub fn from_mut_slice(fdt: &mut [u8]) -> Result<&mut Self> {
Andrew Walbran84b9a232023-07-05 14:01:40 +0000641 // SAFETY: The FDT will be validated before it is returned.
Pierre-Clément Tosi1b0d8902022-11-21 18:16:59 +0000642 let fdt = unsafe { Self::unchecked_from_mut_slice(fdt) };
643 fdt.check_full()?;
644 Ok(fdt)
645 }
646
Jaewan Kim4cf20aa2023-04-03 10:25:38 +0900647 /// Creates an empty Flattened Device Tree with a mutable slice.
648 pub fn create_empty_tree(fdt: &mut [u8]) -> Result<&mut Self> {
Andrew Walbran84b9a232023-07-05 14:01:40 +0000649 // SAFETY: fdt_create_empty_tree() only write within the specified length,
Jaewan Kim4cf20aa2023-04-03 10:25:38 +0900650 // and returns error if buffer was insufficient.
651 // There will be no memory write outside of the given fdt.
652 let ret = unsafe {
653 libfdt_bindgen::fdt_create_empty_tree(
654 fdt.as_mut_ptr().cast::<c_void>(),
655 fdt.len() as i32,
656 )
657 };
658 fdt_err_expect_zero(ret)?;
659
Andrew Walbran84b9a232023-07-05 14:01:40 +0000660 // SAFETY: The FDT will be validated before it is returned.
Jaewan Kim4cf20aa2023-04-03 10:25:38 +0900661 let fdt = unsafe { Self::unchecked_from_mut_slice(fdt) };
662 fdt.check_full()?;
663
664 Ok(fdt)
665 }
666
David Brazdil1baa9a92022-06-28 14:47:50 +0100667 /// Wraps a slice containing a Flattened Device Tree.
668 ///
669 /// # Safety
670 ///
671 /// The returned FDT might be invalid, only use on slices containing a valid DT.
672 pub unsafe fn unchecked_from_slice(fdt: &[u8]) -> &Self {
Andrew Walbran84b9a232023-07-05 14:01:40 +0000673 // SAFETY: Fdt is a wrapper around a [u8], so the transmute is valid. The caller is
674 // responsible for ensuring that it is actually a valid FDT.
675 unsafe { mem::transmute::<&[u8], &Self>(fdt) }
David Brazdil1baa9a92022-06-28 14:47:50 +0100676 }
677
Pierre-Clément Tosi1b0d8902022-11-21 18:16:59 +0000678 /// Wraps a mutable slice containing a Flattened Device Tree.
679 ///
680 /// # Safety
681 ///
682 /// The returned FDT might be invalid, only use on slices containing a valid DT.
683 pub unsafe fn unchecked_from_mut_slice(fdt: &mut [u8]) -> &mut Self {
Andrew Walbran84b9a232023-07-05 14:01:40 +0000684 // SAFETY: Fdt is a wrapper around a [u8], so the transmute is valid. The caller is
685 // responsible for ensuring that it is actually a valid FDT.
686 unsafe { mem::transmute::<&mut [u8], &mut Self>(fdt) }
Pierre-Clément Tosi1b0d8902022-11-21 18:16:59 +0000687 }
688
Jaewan Kimb3dcfc22023-09-20 10:20:52 +0900689 /// Updates this FDT from a slice containing another FDT.
Jiyong Parke9d87e82023-03-21 19:28:40 +0900690 pub fn copy_from_slice(&mut self, new_fdt: &[u8]) -> Result<()> {
691 if self.buffer.len() < new_fdt.len() {
692 Err(FdtError::NoSpace)
693 } else {
694 let totalsize = self.totalsize();
695 self.buffer[..new_fdt.len()].clone_from_slice(new_fdt);
696 // Zeroize the remaining part. We zeroize up to the size of the original DT because
697 // zeroizing the entire buffer (max 2MB) is not necessary and may increase the VM boot
698 // time.
699 self.buffer[new_fdt.len()..max(new_fdt.len(), totalsize)].fill(0_u8);
700 Ok(())
701 }
702 }
703
Jaewan Kimb3dcfc22023-09-20 10:20:52 +0900704 /// Unpacks the DT to cover the whole slice it is contained in.
Pierre-Clément Tosi1b0d8902022-11-21 18:16:59 +0000705 pub fn unpack(&mut self) -> Result<()> {
Andrew Walbran84b9a232023-07-05 14:01:40 +0000706 // SAFETY: "Opens" the DT in-place (supported use-case) by updating its header and
Pierre-Clément Tosi1b0d8902022-11-21 18:16:59 +0000707 // internal structures to make use of the whole self.fdt slice but performs no accesses
708 // outside of it and leaves the DT in a state that will be detected by other functions.
709 let ret = unsafe {
710 libfdt_bindgen::fdt_open_into(
711 self.as_ptr(),
712 self.as_mut_ptr(),
713 self.capacity().try_into().map_err(|_| FdtError::Internal)?,
714 )
715 };
716 fdt_err_expect_zero(ret)
717 }
718
Jaewan Kimb3dcfc22023-09-20 10:20:52 +0900719 /// Packs the DT to take a minimum amount of memory.
Pierre-Clément Tosi1b0d8902022-11-21 18:16:59 +0000720 ///
721 /// Doesn't shrink the underlying memory slice.
722 pub fn pack(&mut self) -> Result<()> {
Andrew Walbran84b9a232023-07-05 14:01:40 +0000723 // SAFETY: "Closes" the DT in-place by updating its header and relocating its structs.
Pierre-Clément Tosi1b0d8902022-11-21 18:16:59 +0000724 let ret = unsafe { libfdt_bindgen::fdt_pack(self.as_mut_ptr()) };
725 fdt_err_expect_zero(ret)
726 }
727
Pierre-Clément Tosi90e19352022-11-21 17:11:48 +0000728 /// Applies a DT overlay on the base DT.
729 ///
730 /// # Safety
731 ///
732 /// On failure, the library corrupts the DT and overlay so both must be discarded.
733 pub unsafe fn apply_overlay<'a>(&'a mut self, overlay: &'a mut Fdt) -> Result<&'a mut Self> {
Andrew Walbran84b9a232023-07-05 14:01:40 +0000734 let ret =
735 // SAFETY: Both pointers are valid because they come from references, and fdt_overlay_apply
736 // doesn't keep them after it returns. It may corrupt their contents if there is an error,
737 // but that's our caller's responsibility.
738 unsafe { libfdt_bindgen::fdt_overlay_apply(self.as_mut_ptr(), overlay.as_mut_ptr()) };
739 fdt_err_expect_zero(ret)?;
Pierre-Clément Tosi90e19352022-11-21 17:11:48 +0000740 Ok(self)
741 }
742
Alice Wang2422bdc2023-06-12 08:37:55 +0000743 /// Returns an iterator of memory banks specified the "/memory" node.
744 /// Throws an error when the "/memory" is not found in the device tree.
David Brazdil1baa9a92022-06-28 14:47:50 +0100745 ///
746 /// NOTE: This does not support individual "/memory@XXXX" banks.
Alice Wang2422bdc2023-06-12 08:37:55 +0000747 pub fn memory(&self) -> Result<MemRegIterator> {
748 let memory_node_name = CStr::from_bytes_with_nul(b"/memory\0").unwrap();
749 let memory_device_type = CStr::from_bytes_with_nul(b"memory\0").unwrap();
David Brazdil1baa9a92022-06-28 14:47:50 +0100750
Alice Wang2422bdc2023-06-12 08:37:55 +0000751 let node = self.node(memory_node_name)?.ok_or(FdtError::NotFound)?;
752 if node.device_type()? != Some(memory_device_type) {
753 return Err(FdtError::BadValue);
Pierre-Clément Tosib244d932022-11-24 16:45:53 +0000754 }
Alice Wang2422bdc2023-06-12 08:37:55 +0000755 node.reg()?.ok_or(FdtError::BadValue).map(MemRegIterator::new)
756 }
757
758 /// Returns the first memory range in the `/memory` node.
759 pub fn first_memory_range(&self) -> Result<Range<usize>> {
760 self.memory()?.next().ok_or(FdtError::NotFound)
David Brazdil1baa9a92022-06-28 14:47:50 +0100761 }
762
Jaewan Kimb3dcfc22023-09-20 10:20:52 +0900763 /// Returns the standard /chosen node.
Pierre-Clément Tosib244d932022-11-24 16:45:53 +0000764 pub fn chosen(&self) -> Result<Option<FdtNode>> {
David Brazdil1baa9a92022-06-28 14:47:50 +0100765 self.node(CStr::from_bytes_with_nul(b"/chosen\0").unwrap())
766 }
767
Jaewan Kimb3dcfc22023-09-20 10:20:52 +0900768 /// Returns the standard /chosen node as mutable.
Pierre-Clément Tosi4ba79662023-02-13 11:22:41 +0000769 pub fn chosen_mut(&mut self) -> Result<Option<FdtNodeMut>> {
770 self.node_mut(CStr::from_bytes_with_nul(b"/chosen\0").unwrap())
771 }
772
Jaewan Kimb3dcfc22023-09-20 10:20:52 +0900773 /// Returns the root node of the tree.
Pierre-Clément Tosi41c158e2022-11-21 19:16:25 +0000774 pub fn root(&self) -> Result<FdtNode> {
Pierre-Clément Tosib244d932022-11-24 16:45:53 +0000775 self.node(CStr::from_bytes_with_nul(b"/\0").unwrap())?.ok_or(FdtError::Internal)
Pierre-Clément Tosi41c158e2022-11-21 19:16:25 +0000776 }
777
Jaewan Kimb3dcfc22023-09-20 10:20:52 +0900778 /// Returns a tree node by its full path.
Pierre-Clément Tosib244d932022-11-24 16:45:53 +0000779 pub fn node(&self, path: &CStr) -> Result<Option<FdtNode>> {
780 Ok(self.path_offset(path)?.map(|offset| FdtNode { fdt: self, offset }))
David Brazdil1baa9a92022-06-28 14:47:50 +0100781 }
782
Pierre-Clément Tosi41c158e2022-11-21 19:16:25 +0000783 /// Iterate over nodes with a given compatible string.
784 pub fn compatible_nodes<'a>(&'a self, compatible: &'a CStr) -> Result<CompatibleIterator<'a>> {
785 CompatibleIterator::new(self, compatible)
786 }
787
Jaewan Kimb3dcfc22023-09-20 10:20:52 +0900788 /// Returns the mutable root node of the tree.
Pierre-Clément Tosi1b0d8902022-11-21 18:16:59 +0000789 pub fn root_mut(&mut self) -> Result<FdtNodeMut> {
790 self.node_mut(CStr::from_bytes_with_nul(b"/\0").unwrap())?.ok_or(FdtError::Internal)
791 }
792
Jaewan Kimb3dcfc22023-09-20 10:20:52 +0900793 /// Returns a mutable tree node by its full path.
Pierre-Clément Tosib244d932022-11-24 16:45:53 +0000794 pub fn node_mut(&mut self, path: &CStr) -> Result<Option<FdtNodeMut>> {
795 Ok(self.path_offset(path)?.map(|offset| FdtNodeMut { fdt: self, offset }))
Pierre-Clément Tosi1b0d8902022-11-21 18:16:59 +0000796 }
797
Jaewan Kimb3dcfc22023-09-20 10:20:52 +0900798 /// Returns the device tree as a slice (may be smaller than the containing buffer).
Pierre-Clément Tosidb74cb12022-12-08 13:56:25 +0000799 pub fn as_slice(&self) -> &[u8] {
800 &self.buffer[..self.totalsize()]
801 }
802
Pierre-Clément Tosib244d932022-11-24 16:45:53 +0000803 fn path_offset(&self, path: &CStr) -> Result<Option<c_int>> {
David Brazdil1baa9a92022-06-28 14:47:50 +0100804 let len = path.to_bytes().len().try_into().map_err(|_| FdtError::BadPath)?;
Andrew Walbran84b9a232023-07-05 14:01:40 +0000805 // SAFETY: Accesses are constrained to the DT totalsize (validated by ctor) and the
David Brazdil1baa9a92022-06-28 14:47:50 +0100806 // function respects the passed number of characters.
807 let ret = unsafe {
808 // *_namelen functions don't include the trailing nul terminator in 'len'.
809 libfdt_bindgen::fdt_path_offset_namelen(self.as_ptr(), path.as_ptr(), len)
810 };
811
Pierre-Clément Tosib244d932022-11-24 16:45:53 +0000812 fdt_err_or_option(ret)
David Brazdil1baa9a92022-06-28 14:47:50 +0100813 }
814
815 fn check_full(&self) -> Result<()> {
Andrew Walbran84b9a232023-07-05 14:01:40 +0000816 // SAFETY: Only performs read accesses within the limits of the slice. If successful, this
David Brazdil1baa9a92022-06-28 14:47:50 +0100817 // call guarantees to other unsafe calls that the header contains a valid totalsize (w.r.t.
818 // 'len' i.e. the self.fdt slice) that those C functions can use to perform bounds
819 // checking. The library doesn't maintain an internal state (such as pointers) between
820 // calls as it expects the client code to keep track of the objects (DT, nodes, ...).
Pierre-Clément Tosi02017da2023-09-26 17:57:04 +0100821 let ret = unsafe { libfdt_bindgen::fdt_check_full(self.as_ptr(), self.capacity()) };
David Brazdil1baa9a92022-06-28 14:47:50 +0100822 fdt_err_expect_zero(ret)
823 }
824
Jaewan Kimaa638702023-09-19 13:34:01 +0900825 fn get_from_ptr(&self, ptr: *const c_void, len: usize) -> Result<&[u8]> {
826 let ptr = ptr as usize;
827 let offset = ptr.checked_sub(self.as_ptr() as usize).ok_or(FdtError::Internal)?;
828 self.buffer.get(offset..(offset + len)).ok_or(FdtError::Internal)
829 }
830
Jaewan Kimb3dcfc22023-09-20 10:20:52 +0900831 /// Returns a shared pointer to the device tree.
Pierre-Clément Tosi8036b4f2023-02-17 10:31:31 +0000832 pub fn as_ptr(&self) -> *const c_void {
Pierre-Clément Tosi0dcc75e2023-05-02 13:43:55 +0000833 self.buffer.as_ptr().cast::<_>()
David Brazdil1baa9a92022-06-28 14:47:50 +0100834 }
Pierre-Clément Tosi1b0d8902022-11-21 18:16:59 +0000835
836 fn as_mut_ptr(&mut self) -> *mut c_void {
Pierre-Clément Tosi0dcc75e2023-05-02 13:43:55 +0000837 self.buffer.as_mut_ptr().cast::<_>()
Pierre-Clément Tosi1b0d8902022-11-21 18:16:59 +0000838 }
839
840 fn capacity(&self) -> usize {
Pierre-Clément Tosief2030e2022-11-28 11:21:20 +0000841 self.buffer.len()
Pierre-Clément Tosi1b0d8902022-11-21 18:16:59 +0000842 }
Pierre-Clément Tosidb74cb12022-12-08 13:56:25 +0000843
844 fn header(&self) -> &libfdt_bindgen::fdt_header {
Pierre-Clément Tosi0dcc75e2023-05-02 13:43:55 +0000845 let p = self.as_ptr().cast::<_>();
Andrew Walbran84b9a232023-07-05 14:01:40 +0000846 // SAFETY: A valid FDT (verified by constructor) must contain a valid fdt_header.
Pierre-Clément Tosi0dcc75e2023-05-02 13:43:55 +0000847 unsafe { &*p }
Pierre-Clément Tosidb74cb12022-12-08 13:56:25 +0000848 }
849
850 fn totalsize(&self) -> usize {
851 u32::from_be(self.header().totalsize) as usize
852 }
David Brazdil1baa9a92022-06-28 14:47:50 +0100853}