1 // Copyright 2024, 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 //! Low-level libfdt_bindgen wrapper, easy to integrate safely in higher-level APIs.
16 //!
17 //! These traits decouple the safe libfdt C function calls from the representation of those
18 //! user-friendly higher-level types, allowing the trait to be shared between different ones,
19 //! adapted to their use-cases (e.g. alloc-based userspace or statically allocated no_std).
20 
21 use core::ffi::CStr;
22 use core::mem;
23 use core::ptr;
24 
25 use crate::result::FdtRawResult;
26 use crate::{FdtError, NodeOffset, Phandle, PropOffset, Result, StringOffset};
27 
28 // Function names are the C function names without the `fdt_` prefix.
29 
30 /// Safe wrapper around `fdt_create_empty_tree()` (C function).
create_empty_tree(fdt: &mut [u8]) -> Result<()>31 pub(crate) fn create_empty_tree(fdt: &mut [u8]) -> Result<()> {
32     let len = fdt.len().try_into().unwrap();
33     let fdt = fdt.as_mut_ptr().cast();
34     // SAFETY: fdt_create_empty_tree() only write within the specified length,
35     //          and returns error if buffer was insufficient.
36     //          There will be no memory write outside of the given fdt.
37     let ret = unsafe { libfdt_bindgen::fdt_create_empty_tree(fdt, len) };
38 
39     FdtRawResult::from(ret).try_into()
40 }
41 
42 /// Safe wrapper around `fdt_check_full()` (C function).
check_full(fdt: &[u8]) -> Result<()>43 pub(crate) fn check_full(fdt: &[u8]) -> Result<()> {
44     let len = fdt.len();
45     let fdt = fdt.as_ptr().cast();
46     // SAFETY: Only performs read accesses within the limits of the slice. If successful, this
47     // call guarantees to other unsafe calls that the header contains a valid totalsize (w.r.t.
48     // 'len' i.e. the self.fdt slice) that those C functions can use to perform bounds
49     // checking. The library doesn't maintain an internal state (such as pointers) between
50     // calls as it expects the client code to keep track of the objects (DT, nodes, ...).
51     let ret = unsafe { libfdt_bindgen::fdt_check_full(fdt, len) };
52 
53     FdtRawResult::from(ret).try_into()
54 }
55 
56 /// Wrapper for the read-only libfdt.h functions.
57 ///
58 /// # Safety
59 ///
60 /// Implementors must ensure that at any point where a method of this trait is called, the
61 /// underlying type returns the bytes of a valid device tree (as validated by `check_full`)
62 /// through its `.as_fdt_slice` method.
63 pub(crate) unsafe trait Libfdt {
64     /// Provides an immutable slice containing the device tree.
65     ///
66     /// The implementation must ensure that the size of the returned slice and
67     /// `fdt_header::totalsize` match.
as_fdt_slice(&self) -> &[u8]68     fn as_fdt_slice(&self) -> &[u8];
69 
70     /// Safe wrapper around `fdt_path_offset_namelen()` (C function).
path_offset_namelen(&self, path: &[u8]) -> Result<Option<NodeOffset>>71     fn path_offset_namelen(&self, path: &[u8]) -> Result<Option<NodeOffset>> {
72         let fdt = self.as_fdt_slice().as_ptr().cast();
73         // *_namelen functions don't include the trailing nul terminator in 'len'.
74         let len = path.len().try_into().map_err(|_| FdtError::BadPath)?;
75         let path = path.as_ptr().cast();
76         // SAFETY: Accesses are constrained to the DT totalsize (validated by ctor) and the
77         // function respects the passed number of characters.
78         let ret = unsafe { libfdt_bindgen::fdt_path_offset_namelen(fdt, path, len) };
79 
80         FdtRawResult::from(ret).try_into()
81     }
82 
83     /// Safe wrapper around `fdt_node_offset_by_phandle()` (C function).
node_offset_by_phandle(&self, phandle: Phandle) -> Result<Option<NodeOffset>>84     fn node_offset_by_phandle(&self, phandle: Phandle) -> Result<Option<NodeOffset>> {
85         let fdt = self.as_fdt_slice().as_ptr().cast();
86         let phandle = phandle.into();
87         // SAFETY: Accesses are constrained to the DT totalsize.
88         let ret = unsafe { libfdt_bindgen::fdt_node_offset_by_phandle(fdt, phandle) };
89 
90         FdtRawResult::from(ret).try_into()
91     }
92 
93     /// Safe wrapper around `fdt_node_offset_by_compatible()` (C function).
node_offset_by_compatible( &self, prev: NodeOffset, compatible: &CStr, ) -> Result<Option<NodeOffset>>94     fn node_offset_by_compatible(
95         &self,
96         prev: NodeOffset,
97         compatible: &CStr,
98     ) -> Result<Option<NodeOffset>> {
99         let fdt = self.as_fdt_slice().as_ptr().cast();
100         let prev = prev.into();
101         let compatible = compatible.as_ptr();
102         // SAFETY: Accesses (read-only) are constrained to the DT totalsize.
103         let ret = unsafe { libfdt_bindgen::fdt_node_offset_by_compatible(fdt, prev, compatible) };
104 
105         FdtRawResult::from(ret).try_into()
106     }
107 
108     /// Safe wrapper around `fdt_next_node()` (C function).
next_node(&self, node: NodeOffset, depth: usize) -> Result<Option<(NodeOffset, usize)>>109     fn next_node(&self, node: NodeOffset, depth: usize) -> Result<Option<(NodeOffset, usize)>> {
110         let fdt = self.as_fdt_slice().as_ptr().cast();
111         let node = node.into();
112         let mut depth = depth.try_into().unwrap();
113         // SAFETY: Accesses (read-only) are constrained to the DT totalsize.
114         let ret = unsafe { libfdt_bindgen::fdt_next_node(fdt, node, &mut depth) };
115 
116         match FdtRawResult::from(ret).try_into()? {
117             Some(offset) if depth >= 0 => {
118                 let depth = depth.try_into().unwrap();
119                 Ok(Some((offset, depth)))
120             }
121             _ => Ok(None),
122         }
123     }
124 
125     /// Safe wrapper around `fdt_parent_offset()` (C function).
126     ///
127     /// Note that this function returns a `Err` when called on a root.
parent_offset(&self, node: NodeOffset) -> Result<NodeOffset>128     fn parent_offset(&self, node: NodeOffset) -> Result<NodeOffset> {
129         let fdt = self.as_fdt_slice().as_ptr().cast();
130         let node = node.into();
131         // SAFETY: Accesses (read-only) are constrained to the DT totalsize.
132         let ret = unsafe { libfdt_bindgen::fdt_parent_offset(fdt, node) };
133 
134         FdtRawResult::from(ret).try_into()
135     }
136 
137     /// Safe wrapper around `fdt_supernode_atdepth_offset()` (C function).
138     ///
139     /// Note that this function returns a `Err` when called on a node at a depth shallower than
140     /// the provided `depth`.
supernode_atdepth_offset(&self, node: NodeOffset, depth: usize) -> Result<NodeOffset>141     fn supernode_atdepth_offset(&self, node: NodeOffset, depth: usize) -> Result<NodeOffset> {
142         let fdt = self.as_fdt_slice().as_ptr().cast();
143         let node = node.into();
144         let depth = depth.try_into().unwrap();
145         let nodedepth = ptr::null_mut();
146         let ret =
147             // SAFETY: Accesses (read-only) are constrained to the DT totalsize.
148             unsafe { libfdt_bindgen::fdt_supernode_atdepth_offset(fdt, node, depth, nodedepth) };
149 
150         FdtRawResult::from(ret).try_into()
151     }
152 
153     /// Safe wrapper around `fdt_subnode_offset_namelen()` (C function).
subnode_offset_namelen( &self, parent: NodeOffset, name: &[u8], ) -> Result<Option<NodeOffset>>154     fn subnode_offset_namelen(
155         &self,
156         parent: NodeOffset,
157         name: &[u8],
158     ) -> Result<Option<NodeOffset>> {
159         let fdt = self.as_fdt_slice().as_ptr().cast();
160         let parent = parent.into();
161         let namelen = name.len().try_into().unwrap();
162         let name = name.as_ptr().cast();
163         // SAFETY: Accesses are constrained to the DT totalsize (validated by ctor).
164         let ret = unsafe { libfdt_bindgen::fdt_subnode_offset_namelen(fdt, parent, name, namelen) };
165 
166         FdtRawResult::from(ret).try_into()
167     }
168     /// Safe wrapper around `fdt_first_subnode()` (C function).
first_subnode(&self, node: NodeOffset) -> Result<Option<NodeOffset>>169     fn first_subnode(&self, node: NodeOffset) -> Result<Option<NodeOffset>> {
170         let fdt = self.as_fdt_slice().as_ptr().cast();
171         let node = node.into();
172         // SAFETY: Accesses (read-only) are constrained to the DT totalsize.
173         let ret = unsafe { libfdt_bindgen::fdt_first_subnode(fdt, node) };
174 
175         FdtRawResult::from(ret).try_into()
176     }
177 
178     /// Safe wrapper around `fdt_next_subnode()` (C function).
next_subnode(&self, node: NodeOffset) -> Result<Option<NodeOffset>>179     fn next_subnode(&self, node: NodeOffset) -> Result<Option<NodeOffset>> {
180         let fdt = self.as_fdt_slice().as_ptr().cast();
181         let node = node.into();
182         // SAFETY: Accesses (read-only) are constrained to the DT totalsize.
183         let ret = unsafe { libfdt_bindgen::fdt_next_subnode(fdt, node) };
184 
185         FdtRawResult::from(ret).try_into()
186     }
187 
188     /// Safe wrapper around `fdt_address_cells()` (C function).
address_cells(&self, node: NodeOffset) -> Result<usize>189     fn address_cells(&self, node: NodeOffset) -> Result<usize> {
190         let fdt = self.as_fdt_slice().as_ptr().cast();
191         let node = node.into();
192         // SAFETY: Accesses are constrained to the DT totalsize (validated by ctor).
193         let ret = unsafe { libfdt_bindgen::fdt_address_cells(fdt, node) };
194 
195         FdtRawResult::from(ret).try_into()
196     }
197 
198     /// Safe wrapper around `fdt_size_cells()` (C function).
size_cells(&self, node: NodeOffset) -> Result<usize>199     fn size_cells(&self, node: NodeOffset) -> Result<usize> {
200         let fdt = self.as_fdt_slice().as_ptr().cast();
201         let node = node.into();
202         // SAFETY: Accesses are constrained to the DT totalsize (validated by ctor).
203         let ret = unsafe { libfdt_bindgen::fdt_size_cells(fdt, node) };
204 
205         FdtRawResult::from(ret).try_into()
206     }
207 
208     /// Safe wrapper around `fdt_get_name()` (C function).
get_name(&self, node: NodeOffset) -> Result<&[u8]>209     fn get_name(&self, node: NodeOffset) -> Result<&[u8]> {
210         let fdt = self.as_fdt_slice().as_ptr().cast();
211         let node = node.into();
212         let mut len = 0;
213         // SAFETY: Accesses are constrained to the DT totalsize (validated by ctor). On success, the
214         // function returns valid null terminating string and otherwise returned values are dropped.
215         let name = unsafe { libfdt_bindgen::fdt_get_name(fdt, node, &mut len) };
216         let len = usize::try_from(FdtRawResult::from(len))?.checked_add(1).unwrap();
217 
218         get_slice_at_ptr(self.as_fdt_slice(), name.cast(), len).ok_or(FdtError::Internal)
219     }
220 
221     /// Safe wrapper around `fdt_getprop_namelen()` (C function).
getprop_namelen(&self, node: NodeOffset, name: &[u8]) -> Result<Option<&[u8]>>222     fn getprop_namelen(&self, node: NodeOffset, name: &[u8]) -> Result<Option<&[u8]>> {
223         let fdt = self.as_fdt_slice().as_ptr().cast();
224         let node = node.into();
225         let namelen = name.len().try_into().map_err(|_| FdtError::BadPath)?;
226         let name = name.as_ptr().cast();
227         let mut len = 0;
228         let prop =
229             // SAFETY: Accesses are constrained to the DT totalsize (validated by ctor) and the
230             // function respects the passed number of characters.
231             unsafe { libfdt_bindgen::fdt_getprop_namelen(fdt, node, name, namelen, &mut len) };
232 
233         if let Some(len) = FdtRawResult::from(len).try_into()? {
234             let bytes = get_slice_at_ptr(self.as_fdt_slice(), prop.cast(), len);
235 
236             Ok(Some(bytes.ok_or(FdtError::Internal)?))
237         } else {
238             Ok(None)
239         }
240     }
241 
242     /// Safe wrapper around `fdt_get_property_by_offset()` (C function).
get_property_by_offset(&self, offset: PropOffset) -> Result<&libfdt_bindgen::fdt_property>243     fn get_property_by_offset(&self, offset: PropOffset) -> Result<&libfdt_bindgen::fdt_property> {
244         let mut len = 0;
245         let fdt = self.as_fdt_slice().as_ptr().cast();
246         let offset = offset.into();
247         // SAFETY: Accesses (read-only) are constrained to the DT totalsize.
248         let prop = unsafe { libfdt_bindgen::fdt_get_property_by_offset(fdt, offset, &mut len) };
249 
250         let data_len = FdtRawResult::from(len).try_into()?;
251         let data_offset = mem::offset_of!(libfdt_bindgen::fdt_property, data);
252         let len = data_offset.checked_add(data_len).ok_or(FdtError::Internal)?;
253 
254         if !is_aligned(prop) || get_slice_at_ptr(self.as_fdt_slice(), prop.cast(), len).is_none() {
255             return Err(FdtError::Internal);
256         }
257 
258         // SAFETY: The pointer is properly aligned, struct is fully contained in the DT slice.
259         let prop = unsafe { &*prop };
260 
261         if data_len != u32::from_be(prop.len).try_into().unwrap() {
262             return Err(FdtError::BadLayout);
263         }
264 
265         Ok(prop)
266     }
267 
268     /// Safe wrapper around `fdt_first_property_offset()` (C function).
first_property_offset(&self, node: NodeOffset) -> Result<Option<PropOffset>>269     fn first_property_offset(&self, node: NodeOffset) -> Result<Option<PropOffset>> {
270         let fdt = self.as_fdt_slice().as_ptr().cast();
271         let node = node.into();
272         // SAFETY: Accesses (read-only) are constrained to the DT totalsize.
273         let ret = unsafe { libfdt_bindgen::fdt_first_property_offset(fdt, node) };
274 
275         FdtRawResult::from(ret).try_into()
276     }
277 
278     /// Safe wrapper around `fdt_next_property_offset()` (C function).
next_property_offset(&self, prev: PropOffset) -> Result<Option<PropOffset>>279     fn next_property_offset(&self, prev: PropOffset) -> Result<Option<PropOffset>> {
280         let fdt = self.as_fdt_slice().as_ptr().cast();
281         let prev = prev.into();
282         // SAFETY: Accesses (read-only) are constrained to the DT totalsize.
283         let ret = unsafe { libfdt_bindgen::fdt_next_property_offset(fdt, prev) };
284 
285         FdtRawResult::from(ret).try_into()
286     }
287 
288     /// Safe wrapper around `fdt_find_max_phandle()` (C function).
find_max_phandle(&self) -> Result<Phandle>289     fn find_max_phandle(&self) -> Result<Phandle> {
290         let fdt = self.as_fdt_slice().as_ptr().cast();
291         let mut phandle = 0;
292         // SAFETY: Accesses (read-only) are constrained to the DT totalsize.
293         let ret = unsafe { libfdt_bindgen::fdt_find_max_phandle(fdt, &mut phandle) };
294 
295         () = FdtRawResult::from(ret).try_into()?;
296 
297         phandle.try_into()
298     }
299 
300     /// Safe wrapper around `fdt_string()` (C function).
string(&self, offset: StringOffset) -> Result<&CStr>301     fn string(&self, offset: StringOffset) -> Result<&CStr> {
302         let fdt = self.as_fdt_slice().as_ptr().cast();
303         let offset = offset.into();
304         // SAFETY: Accesses (read-only) are constrained to the DT totalsize.
305         let ptr = unsafe { libfdt_bindgen::fdt_string(fdt, offset) };
306         let bytes =
307             get_slice_from_ptr(self.as_fdt_slice(), ptr.cast()).ok_or(FdtError::Internal)?;
308 
309         CStr::from_bytes_until_nul(bytes).map_err(|_| FdtError::Internal)
310     }
311 
312     /// Safe wrapper around `fdt_open_into()` (C function).
313     #[allow(dead_code)]
open_into(&self, dest: &mut [u8]) -> Result<()>314     fn open_into(&self, dest: &mut [u8]) -> Result<()> {
315         let fdt = self.as_fdt_slice().as_ptr().cast();
316 
317         open_into(fdt, dest)
318     }
319 }
320 
321 /// Wrapper for the read-write libfdt.h functions.
322 ///
323 /// # Safety
324 ///
325 /// Implementors must ensure that at any point where a method of this trait is called, the
326 /// underlying type returns the bytes of a valid device tree (as validated by `check_full`)
327 /// through its `.as_fdt_slice_mut` method.
328 ///
329 /// Some methods may make previously returned values such as node or string offsets or phandles
330 /// invalid by modifying the device tree (e.g. by inserting or removing new nodes or properties).
331 /// As most methods take or return such values, instead of marking them all as unsafe, this trait
332 /// is marked as unsafe as implementors must ensure that methods that modify the validity of those
333 /// values are never called while the values are still in use.
334 pub(crate) unsafe trait LibfdtMut {
335     /// Provides a mutable pointer to a buffer containing the device tree.
336     ///
337     /// The implementation must ensure that the size of the returned slice is at least
338     /// `fdt_header::totalsize`, to allow for device tree growth.
as_fdt_slice_mut(&mut self) -> &mut [u8]339     fn as_fdt_slice_mut(&mut self) -> &mut [u8];
340 
341     /// Safe wrapper around `fdt_nop_node()` (C function).
nop_node(&mut self, node: NodeOffset) -> Result<()>342     fn nop_node(&mut self, node: NodeOffset) -> Result<()> {
343         let fdt = self.as_fdt_slice_mut().as_mut_ptr().cast();
344         let node = node.into();
345         // SAFETY: Accesses are constrained to the DT totalsize (validated by ctor).
346         let ret = unsafe { libfdt_bindgen::fdt_nop_node(fdt, node) };
347 
348         FdtRawResult::from(ret).try_into()
349     }
350 
351     /// Safe wrapper around `fdt_add_subnode_namelen()` (C function).
add_subnode_namelen(&mut self, node: NodeOffset, name: &[u8]) -> Result<NodeOffset>352     fn add_subnode_namelen(&mut self, node: NodeOffset, name: &[u8]) -> Result<NodeOffset> {
353         let fdt = self.as_fdt_slice_mut().as_mut_ptr().cast();
354         let node = node.into();
355         let namelen = name.len().try_into().unwrap();
356         let name = name.as_ptr().cast();
357         // SAFETY: Accesses are constrained to the DT totalsize (validated by ctor).
358         let ret = unsafe { libfdt_bindgen::fdt_add_subnode_namelen(fdt, node, name, namelen) };
359 
360         FdtRawResult::from(ret).try_into()
361     }
362 
363     /// Safe wrapper around `fdt_setprop()` (C function).
setprop(&mut self, node: NodeOffset, name: &CStr, value: &[u8]) -> Result<()>364     fn setprop(&mut self, node: NodeOffset, name: &CStr, value: &[u8]) -> Result<()> {
365         let fdt = self.as_fdt_slice_mut().as_mut_ptr().cast();
366         let node = node.into();
367         let name = name.as_ptr();
368         let len = value.len().try_into().map_err(|_| FdtError::BadValue)?;
369         let value = value.as_ptr().cast();
370         // SAFETY: New value size is constrained to the DT totalsize
371         //          (validated by underlying libfdt).
372         let ret = unsafe { libfdt_bindgen::fdt_setprop(fdt, node, name, value, len) };
373 
374         FdtRawResult::from(ret).try_into()
375     }
376 
377     /// Safe wrapper around `fdt_setprop_placeholder()` (C function).
setprop_placeholder( &mut self, node: NodeOffset, name: &CStr, size: usize, ) -> Result<&mut [u8]>378     fn setprop_placeholder(
379         &mut self,
380         node: NodeOffset,
381         name: &CStr,
382         size: usize,
383     ) -> Result<&mut [u8]> {
384         let fdt = self.as_fdt_slice_mut().as_mut_ptr().cast();
385         let node = node.into();
386         let name = name.as_ptr();
387         let len = size.try_into().unwrap();
388         let mut data = ptr::null_mut();
389         let ret =
390             // SAFETY: Accesses are constrained to the DT totalsize (validated by ctor).
391             unsafe { libfdt_bindgen::fdt_setprop_placeholder(fdt, node, name, len, &mut data) };
392 
393         () = FdtRawResult::from(ret).try_into()?;
394 
395         get_mut_slice_at_ptr(self.as_fdt_slice_mut(), data.cast(), size).ok_or(FdtError::Internal)
396     }
397 
398     /// Safe wrapper around `fdt_setprop_inplace()` (C function).
setprop_inplace(&mut self, node: NodeOffset, name: &CStr, value: &[u8]) -> Result<()>399     fn setprop_inplace(&mut self, node: NodeOffset, name: &CStr, value: &[u8]) -> Result<()> {
400         let fdt = self.as_fdt_slice_mut().as_mut_ptr().cast();
401         let node = node.into();
402         let name = name.as_ptr();
403         let len = value.len().try_into().map_err(|_| FdtError::BadValue)?;
404         let value = value.as_ptr().cast();
405         // SAFETY: New value size is constrained to the DT totalsize
406         //          (validated by underlying libfdt).
407         let ret = unsafe { libfdt_bindgen::fdt_setprop_inplace(fdt, node, name, value, len) };
408 
409         FdtRawResult::from(ret).try_into()
410     }
411 
412     /// Safe wrapper around `fdt_appendprop()` (C function).
appendprop(&mut self, node: NodeOffset, name: &CStr, value: &[u8]) -> Result<()>413     fn appendprop(&mut self, node: NodeOffset, name: &CStr, value: &[u8]) -> Result<()> {
414         let fdt = self.as_fdt_slice_mut().as_mut_ptr().cast();
415         let node = node.into();
416         let name = name.as_ptr();
417         let len = value.len().try_into().map_err(|_| FdtError::BadValue)?;
418         let value = value.as_ptr().cast();
419         // SAFETY: Accesses are constrained to the DT totalsize (validated by ctor).
420         let ret = unsafe { libfdt_bindgen::fdt_appendprop(fdt, node, name, value, len) };
421 
422         FdtRawResult::from(ret).try_into()
423     }
424 
425     /// Safe wrapper around `fdt_appendprop_addrrange()` (C function).
appendprop_addrrange( &mut self, parent: NodeOffset, node: NodeOffset, name: &CStr, addr: u64, size: u64, ) -> Result<()>426     fn appendprop_addrrange(
427         &mut self,
428         parent: NodeOffset,
429         node: NodeOffset,
430         name: &CStr,
431         addr: u64,
432         size: u64,
433     ) -> Result<()> {
434         let fdt = self.as_fdt_slice_mut().as_mut_ptr().cast();
435         let parent = parent.into();
436         let node = node.into();
437         let name = name.as_ptr();
438         // SAFETY: Accesses are constrained to the DT totalsize (validated by ctor).
439         let ret = unsafe {
440             libfdt_bindgen::fdt_appendprop_addrrange(fdt, parent, node, name, addr, size)
441         };
442 
443         FdtRawResult::from(ret).try_into()
444     }
445 
446     /// Safe wrapper around `fdt_delprop()` (C function).
delprop(&mut self, node: NodeOffset, name: &CStr) -> Result<()>447     fn delprop(&mut self, node: NodeOffset, name: &CStr) -> Result<()> {
448         let fdt = self.as_fdt_slice_mut().as_mut_ptr().cast();
449         let node = node.into();
450         let name = name.as_ptr();
451         // SAFETY: Accesses are constrained to the DT totalsize (validated by ctor) when the
452         // library locates the node's property. Removing the property may shift the offsets of
453         // other nodes and properties but the borrow checker should prevent this function from
454         // being called when FdtNode instances are in use.
455         let ret = unsafe { libfdt_bindgen::fdt_delprop(fdt, node, name) };
456 
457         FdtRawResult::from(ret).try_into()
458     }
459 
460     /// Safe wrapper around `fdt_nop_property()` (C function).
nop_property(&mut self, node: NodeOffset, name: &CStr) -> Result<()>461     fn nop_property(&mut self, node: NodeOffset, name: &CStr) -> Result<()> {
462         let fdt = self.as_fdt_slice_mut().as_mut_ptr().cast();
463         let node = node.into();
464         let name = name.as_ptr();
465         // SAFETY: Accesses are constrained to the DT totalsize (validated by ctor) when the
466         // library locates the node's property.
467         let ret = unsafe { libfdt_bindgen::fdt_nop_property(fdt, node, name) };
468 
469         FdtRawResult::from(ret).try_into()
470     }
471 
472     /// Safe and aliasing-compatible wrapper around `fdt_open_into()` (C function).
473     ///
474     /// The C API allows both input (`const void*`) and output (`void *`) to point to the same
475     /// memory region but the borrow checker would reject an API such as
476     ///
477     ///     self.open_into(&mut self.buffer)
478     ///
479     /// so this wrapper is provided to implement such a common aliasing case.
open_into_self(&mut self) -> Result<()>480     fn open_into_self(&mut self) -> Result<()> {
481         let fdt = self.as_fdt_slice_mut();
482 
483         open_into(fdt.as_ptr().cast(), fdt)
484     }
485 
486     /// Safe wrapper around `fdt_pack()` (C function).
pack(&mut self) -> Result<()>487     fn pack(&mut self) -> Result<()> {
488         let fdt = self.as_fdt_slice_mut().as_mut_ptr().cast();
489         // SAFETY: Accesses (R/W) are constrained to the DT totalsize (validated by ctor).
490         let ret = unsafe { libfdt_bindgen::fdt_pack(fdt) };
491 
492         FdtRawResult::from(ret).try_into()
493     }
494 
495     /// Wrapper around `fdt_overlay_apply()` (C function).
496     ///
497     /// # Safety
498     ///
499     /// This function safely wraps the C function call but is unsafe because the caller must
500     ///
501     /// - discard `overlay` as a &LibfdtMut because libfdt corrupts its header before returning;
502     /// - on error, discard `self` as a &LibfdtMut for the same reason.
overlay_apply(&mut self, overlay: &mut Self) -> Result<()>503     unsafe fn overlay_apply(&mut self, overlay: &mut Self) -> Result<()> {
504         let fdt = self.as_fdt_slice_mut().as_mut_ptr().cast();
505         let overlay = overlay.as_fdt_slice_mut().as_mut_ptr().cast();
506         // SAFETY: Both pointers are valid because they come from references, and fdt_overlay_apply
507         // doesn't keep them after it returns. It may corrupt their contents if there is an error,
508         // but that's our caller's responsibility.
509         let ret = unsafe { libfdt_bindgen::fdt_overlay_apply(fdt, overlay) };
510 
511         FdtRawResult::from(ret).try_into()
512     }
513 }
514 
get_slice_at_ptr(s: &[u8], p: *const u8, len: usize) -> Option<&[u8]>515 pub(crate) fn get_slice_at_ptr(s: &[u8], p: *const u8, len: usize) -> Option<&[u8]> {
516     let offset = get_slice_ptr_offset(s, p)?;
517 
518     s.get(offset..offset.checked_add(len)?)
519 }
520 
get_mut_slice_at_ptr(s: &mut [u8], p: *mut u8, len: usize) -> Option<&mut [u8]>521 fn get_mut_slice_at_ptr(s: &mut [u8], p: *mut u8, len: usize) -> Option<&mut [u8]> {
522     let offset = get_slice_ptr_offset(s, p)?;
523 
524     s.get_mut(offset..offset.checked_add(len)?)
525 }
526 
get_slice_from_ptr(s: &[u8], p: *const u8) -> Option<&[u8]>527 fn get_slice_from_ptr(s: &[u8], p: *const u8) -> Option<&[u8]> {
528     s.get(get_slice_ptr_offset(s, p)?..)
529 }
530 
get_slice_ptr_offset(s: &[u8], p: *const u8) -> Option<usize>531 fn get_slice_ptr_offset(s: &[u8], p: *const u8) -> Option<usize> {
532     s.as_ptr_range().contains(&p).then(|| {
533         // SAFETY: Both pointers are in bounds, derive from the same object, and size_of::<T>()=1.
534         (unsafe { p.offset_from(s.as_ptr()) }) as usize
535         // TODO(stable_feature(ptr_sub_ptr)): p.sub_ptr()
536     })
537 }
538 
open_into(fdt: *const u8, dest: &mut [u8]) -> Result<()>539 fn open_into(fdt: *const u8, dest: &mut [u8]) -> Result<()> {
540     let fdt = fdt.cast();
541     let len = dest.len().try_into().map_err(|_| FdtError::Internal)?;
542     let dest = dest.as_mut_ptr().cast();
543     // SAFETY: Reads the whole fdt slice (based on the validated totalsize) and, if it fits, copies
544     // it to the (properly mutable) dest buffer of size len. On success, the resulting dest
545     // contains a valid DT with the nodes and properties of the original one but of a different
546     // size, reflected in its fdt_header::totalsize.
547     let ret = unsafe { libfdt_bindgen::fdt_open_into(fdt, dest, len) };
548 
549     FdtRawResult::from(ret).try_into()
550 }
551 
552 // TODO(stable_feature(pointer_is_aligned)): p.is_aligned()
is_aligned<T>(p: *const T) -> bool553 fn is_aligned<T>(p: *const T) -> bool {
554     (p as usize) % mem::align_of::<T>() == 0
555 }
556