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         // TODO(stable_feature(offset_of)): mem::offset_of!(fdt_property, data).
252         let data_offset = memoffset::offset_of!(libfdt_bindgen::fdt_property, data);
253         let len = data_offset.checked_add(data_len).ok_or(FdtError::Internal)?;
254 
255         if !is_aligned(prop) || get_slice_at_ptr(self.as_fdt_slice(), prop.cast(), len).is_none() {
256             return Err(FdtError::Internal);
257         }
258 
259         // SAFETY: The pointer is properly aligned, struct is fully contained in the DT slice.
260         let prop = unsafe { &*prop };
261 
262         if data_len != u32::from_be(prop.len).try_into().unwrap() {
263             return Err(FdtError::BadLayout);
264         }
265 
266         Ok(prop)
267     }
268 
269     /// Safe wrapper around `fdt_first_property_offset()` (C function).
first_property_offset(&self, node: NodeOffset) -> Result<Option<PropOffset>>270     fn first_property_offset(&self, node: NodeOffset) -> Result<Option<PropOffset>> {
271         let fdt = self.as_fdt_slice().as_ptr().cast();
272         let node = node.into();
273         // SAFETY: Accesses (read-only) are constrained to the DT totalsize.
274         let ret = unsafe { libfdt_bindgen::fdt_first_property_offset(fdt, node) };
275 
276         FdtRawResult::from(ret).try_into()
277     }
278 
279     /// Safe wrapper around `fdt_next_property_offset()` (C function).
next_property_offset(&self, prev: PropOffset) -> Result<Option<PropOffset>>280     fn next_property_offset(&self, prev: PropOffset) -> Result<Option<PropOffset>> {
281         let fdt = self.as_fdt_slice().as_ptr().cast();
282         let prev = prev.into();
283         // SAFETY: Accesses (read-only) are constrained to the DT totalsize.
284         let ret = unsafe { libfdt_bindgen::fdt_next_property_offset(fdt, prev) };
285 
286         FdtRawResult::from(ret).try_into()
287     }
288 
289     /// Safe wrapper around `fdt_find_max_phandle()` (C function).
find_max_phandle(&self) -> Result<Phandle>290     fn find_max_phandle(&self) -> Result<Phandle> {
291         let fdt = self.as_fdt_slice().as_ptr().cast();
292         let mut phandle = 0;
293         // SAFETY: Accesses (read-only) are constrained to the DT totalsize.
294         let ret = unsafe { libfdt_bindgen::fdt_find_max_phandle(fdt, &mut phandle) };
295 
296         FdtRawResult::from(ret).try_into()?;
297 
298         phandle.try_into()
299     }
300 
301     /// Safe wrapper around `fdt_string()` (C function).
string(&self, offset: StringOffset) -> Result<&CStr>302     fn string(&self, offset: StringOffset) -> Result<&CStr> {
303         let fdt = self.as_fdt_slice().as_ptr().cast();
304         let offset = offset.into();
305         // SAFETY: Accesses (read-only) are constrained to the DT totalsize.
306         let ptr = unsafe { libfdt_bindgen::fdt_string(fdt, offset) };
307         let bytes =
308             get_slice_from_ptr(self.as_fdt_slice(), ptr.cast()).ok_or(FdtError::Internal)?;
309 
310         CStr::from_bytes_until_nul(bytes).map_err(|_| FdtError::Internal)
311     }
312 
313     /// Safe wrapper around `fdt_open_into()` (C function).
314     #[allow(dead_code)]
open_into(&self, dest: &mut [u8]) -> Result<()>315     fn open_into(&self, dest: &mut [u8]) -> Result<()> {
316         let fdt = self.as_fdt_slice().as_ptr().cast();
317 
318         open_into(fdt, dest)
319     }
320 }
321 
322 /// Wrapper for the read-write libfdt.h functions.
323 ///
324 /// # Safety
325 ///
326 /// Implementors must ensure that at any point where a method of this trait is called, the
327 /// underlying type returns the bytes of a valid device tree (as validated by `check_full`)
328 /// through its `.as_fdt_slice_mut` method.
329 ///
330 /// Some methods may make previously returned values such as node or string offsets or phandles
331 /// invalid by modifying the device tree (e.g. by inserting or removing new nodes or properties).
332 /// As most methods take or return such values, instead of marking them all as unsafe, this trait
333 /// is marked as unsafe as implementors must ensure that methods that modify the validity of those
334 /// values are never called while the values are still in use.
335 pub(crate) unsafe trait LibfdtMut {
336     /// Provides a mutable pointer to a buffer containing the device tree.
337     ///
338     /// The implementation must ensure that the size of the returned slice is at least
339     /// `fdt_header::totalsize`, to allow for device tree growth.
as_fdt_slice_mut(&mut self) -> &mut [u8]340     fn as_fdt_slice_mut(&mut self) -> &mut [u8];
341 
342     /// Safe wrapper around `fdt_nop_node()` (C function).
nop_node(&mut self, node: NodeOffset) -> Result<()>343     fn nop_node(&mut self, node: NodeOffset) -> Result<()> {
344         let fdt = self.as_fdt_slice_mut().as_mut_ptr().cast();
345         let node = node.into();
346         // SAFETY: Accesses are constrained to the DT totalsize (validated by ctor).
347         let ret = unsafe { libfdt_bindgen::fdt_nop_node(fdt, node) };
348 
349         FdtRawResult::from(ret).try_into()
350     }
351 
352     /// Safe wrapper around `fdt_add_subnode_namelen()` (C function).
add_subnode_namelen(&mut self, node: NodeOffset, name: &[u8]) -> Result<NodeOffset>353     fn add_subnode_namelen(&mut self, node: NodeOffset, name: &[u8]) -> Result<NodeOffset> {
354         let fdt = self.as_fdt_slice_mut().as_mut_ptr().cast();
355         let node = node.into();
356         let namelen = name.len().try_into().unwrap();
357         let name = name.as_ptr().cast();
358         // SAFETY: Accesses are constrained to the DT totalsize (validated by ctor).
359         let ret = unsafe { libfdt_bindgen::fdt_add_subnode_namelen(fdt, node, name, namelen) };
360 
361         FdtRawResult::from(ret).try_into()
362     }
363 
364     /// Safe wrapper around `fdt_setprop()` (C function).
setprop(&mut self, node: NodeOffset, name: &CStr, value: &[u8]) -> Result<()>365     fn setprop(&mut self, node: NodeOffset, name: &CStr, value: &[u8]) -> Result<()> {
366         let fdt = self.as_fdt_slice_mut().as_mut_ptr().cast();
367         let node = node.into();
368         let name = name.as_ptr();
369         let len = value.len().try_into().map_err(|_| FdtError::BadValue)?;
370         let value = value.as_ptr().cast();
371         // SAFETY: New value size is constrained to the DT totalsize
372         //          (validated by underlying libfdt).
373         let ret = unsafe { libfdt_bindgen::fdt_setprop(fdt, node, name, value, len) };
374 
375         FdtRawResult::from(ret).try_into()
376     }
377 
378     /// Safe wrapper around `fdt_setprop_placeholder()` (C function).
setprop_placeholder( &mut self, node: NodeOffset, name: &CStr, size: usize, ) -> Result<&mut [u8]>379     fn setprop_placeholder(
380         &mut self,
381         node: NodeOffset,
382         name: &CStr,
383         size: usize,
384     ) -> Result<&mut [u8]> {
385         let fdt = self.as_fdt_slice_mut().as_mut_ptr().cast();
386         let node = node.into();
387         let name = name.as_ptr();
388         let len = size.try_into().unwrap();
389         let mut data = ptr::null_mut();
390         let ret =
391             // SAFETY: Accesses are constrained to the DT totalsize (validated by ctor).
392             unsafe { libfdt_bindgen::fdt_setprop_placeholder(fdt, node, name, len, &mut data) };
393 
394         FdtRawResult::from(ret).try_into()?;
395 
396         get_mut_slice_at_ptr(self.as_fdt_slice_mut(), data.cast(), size).ok_or(FdtError::Internal)
397     }
398 
399     /// Safe wrapper around `fdt_setprop_inplace()` (C function).
setprop_inplace(&mut self, node: NodeOffset, name: &CStr, value: &[u8]) -> Result<()>400     fn setprop_inplace(&mut self, node: NodeOffset, name: &CStr, value: &[u8]) -> Result<()> {
401         let fdt = self.as_fdt_slice_mut().as_mut_ptr().cast();
402         let node = node.into();
403         let name = name.as_ptr();
404         let len = value.len().try_into().map_err(|_| FdtError::BadValue)?;
405         let value = value.as_ptr().cast();
406         // SAFETY: New value size is constrained to the DT totalsize
407         //          (validated by underlying libfdt).
408         let ret = unsafe { libfdt_bindgen::fdt_setprop_inplace(fdt, node, name, value, len) };
409 
410         FdtRawResult::from(ret).try_into()
411     }
412 
413     /// Safe wrapper around `fdt_appendprop()` (C function).
appendprop(&mut self, node: NodeOffset, name: &CStr, value: &[u8]) -> Result<()>414     fn appendprop(&mut self, node: NodeOffset, name: &CStr, value: &[u8]) -> Result<()> {
415         let fdt = self.as_fdt_slice_mut().as_mut_ptr().cast();
416         let node = node.into();
417         let name = name.as_ptr();
418         let len = value.len().try_into().map_err(|_| FdtError::BadValue)?;
419         let value = value.as_ptr().cast();
420         // SAFETY: Accesses are constrained to the DT totalsize (validated by ctor).
421         let ret = unsafe { libfdt_bindgen::fdt_appendprop(fdt, node, name, value, len) };
422 
423         FdtRawResult::from(ret).try_into()
424     }
425 
426     /// Safe wrapper around `fdt_appendprop_addrrange()` (C function).
appendprop_addrrange( &mut self, parent: NodeOffset, node: NodeOffset, name: &CStr, addr: u64, size: u64, ) -> Result<()>427     fn appendprop_addrrange(
428         &mut self,
429         parent: NodeOffset,
430         node: NodeOffset,
431         name: &CStr,
432         addr: u64,
433         size: u64,
434     ) -> Result<()> {
435         let fdt = self.as_fdt_slice_mut().as_mut_ptr().cast();
436         let parent = parent.into();
437         let node = node.into();
438         let name = name.as_ptr();
439         // SAFETY: Accesses are constrained to the DT totalsize (validated by ctor).
440         let ret = unsafe {
441             libfdt_bindgen::fdt_appendprop_addrrange(fdt, parent, node, name, addr, size)
442         };
443 
444         FdtRawResult::from(ret).try_into()
445     }
446 
447     /// Safe wrapper around `fdt_delprop()` (C function).
delprop(&mut self, node: NodeOffset, name: &CStr) -> Result<()>448     fn delprop(&mut self, node: NodeOffset, name: &CStr) -> Result<()> {
449         let fdt = self.as_fdt_slice_mut().as_mut_ptr().cast();
450         let node = node.into();
451         let name = name.as_ptr();
452         // SAFETY: Accesses are constrained to the DT totalsize (validated by ctor) when the
453         // library locates the node's property. Removing the property may shift the offsets of
454         // other nodes and properties but the borrow checker should prevent this function from
455         // being called when FdtNode instances are in use.
456         let ret = unsafe { libfdt_bindgen::fdt_delprop(fdt, node, name) };
457 
458         FdtRawResult::from(ret).try_into()
459     }
460 
461     /// Safe wrapper around `fdt_nop_property()` (C function).
nop_property(&mut self, node: NodeOffset, name: &CStr) -> Result<()>462     fn nop_property(&mut self, node: NodeOffset, name: &CStr) -> Result<()> {
463         let fdt = self.as_fdt_slice_mut().as_mut_ptr().cast();
464         let node = node.into();
465         let name = name.as_ptr();
466         // SAFETY: Accesses are constrained to the DT totalsize (validated by ctor) when the
467         // library locates the node's property.
468         let ret = unsafe { libfdt_bindgen::fdt_nop_property(fdt, node, name) };
469 
470         FdtRawResult::from(ret).try_into()
471     }
472 
473     /// Safe and aliasing-compatible wrapper around `fdt_open_into()` (C function).
474     ///
475     /// The C API allows both input (`const void*`) and output (`void *`) to point to the same
476     /// memory region but the borrow checker would reject an API such as
477     ///
478     ///     self.open_into(&mut self.buffer)
479     ///
480     /// so this wrapper is provided to implement such a common aliasing case.
open_into_self(&mut self) -> Result<()>481     fn open_into_self(&mut self) -> Result<()> {
482         let fdt = self.as_fdt_slice_mut();
483 
484         open_into(fdt.as_ptr().cast(), fdt)
485     }
486 
487     /// Safe wrapper around `fdt_pack()` (C function).
pack(&mut self) -> Result<()>488     fn pack(&mut self) -> Result<()> {
489         let fdt = self.as_fdt_slice_mut().as_mut_ptr().cast();
490         // SAFETY: Accesses (R/W) are constrained to the DT totalsize (validated by ctor).
491         let ret = unsafe { libfdt_bindgen::fdt_pack(fdt) };
492 
493         FdtRawResult::from(ret).try_into()
494     }
495 
496     /// Wrapper around `fdt_overlay_apply()` (C function).
497     ///
498     /// # Safety
499     ///
500     /// This function safely wraps the C function call but is unsafe because the caller must
501     ///
502     /// - discard `overlay` as a &LibfdtMut because libfdt corrupts its header before returning;
503     /// - on error, discard `self` as a &LibfdtMut for the same reason.
overlay_apply(&mut self, overlay: &mut Self) -> Result<()>504     unsafe fn overlay_apply(&mut self, overlay: &mut Self) -> Result<()> {
505         let fdt = self.as_fdt_slice_mut().as_mut_ptr().cast();
506         let overlay = overlay.as_fdt_slice_mut().as_mut_ptr().cast();
507         // SAFETY: Both pointers are valid because they come from references, and fdt_overlay_apply
508         // doesn't keep them after it returns. It may corrupt their contents if there is an error,
509         // but that's our caller's responsibility.
510         let ret = unsafe { libfdt_bindgen::fdt_overlay_apply(fdt, overlay) };
511 
512         FdtRawResult::from(ret).try_into()
513     }
514 }
515 
get_slice_at_ptr(s: &[u8], p: *const u8, len: usize) -> Option<&[u8]>516 pub(crate) fn get_slice_at_ptr(s: &[u8], p: *const u8, len: usize) -> Option<&[u8]> {
517     let offset = get_slice_ptr_offset(s, p)?;
518 
519     s.get(offset..offset.checked_add(len)?)
520 }
521 
get_mut_slice_at_ptr(s: &mut [u8], p: *mut u8, len: usize) -> Option<&mut [u8]>522 fn get_mut_slice_at_ptr(s: &mut [u8], p: *mut u8, len: usize) -> Option<&mut [u8]> {
523     let offset = get_slice_ptr_offset(s, p)?;
524 
525     s.get_mut(offset..offset.checked_add(len)?)
526 }
527 
get_slice_from_ptr(s: &[u8], p: *const u8) -> Option<&[u8]>528 fn get_slice_from_ptr(s: &[u8], p: *const u8) -> Option<&[u8]> {
529     s.get(get_slice_ptr_offset(s, p)?..)
530 }
531 
get_slice_ptr_offset(s: &[u8], p: *const u8) -> Option<usize>532 fn get_slice_ptr_offset(s: &[u8], p: *const u8) -> Option<usize> {
533     s.as_ptr_range().contains(&p).then(|| {
534         // SAFETY: Both pointers are in bounds, derive from the same object, and size_of::<T>()=1.
535         (unsafe { p.offset_from(s.as_ptr()) }) as usize
536         // TODO(stable_feature(ptr_sub_ptr)): p.sub_ptr()
537     })
538 }
539 
open_into(fdt: *const u8, dest: &mut [u8]) -> Result<()>540 fn open_into(fdt: *const u8, dest: &mut [u8]) -> Result<()> {
541     let fdt = fdt.cast();
542     let len = dest.len().try_into().map_err(|_| FdtError::Internal)?;
543     let dest = dest.as_mut_ptr().cast();
544     // SAFETY: Reads the whole fdt slice (based on the validated totalsize) and, if it fits, copies
545     // it to the (properly mutable) dest buffer of size len. On success, the resulting dest
546     // contains a valid DT with the nodes and properties of the original one but of a different
547     // size, reflected in its fdt_header::totalsize.
548     let ret = unsafe { libfdt_bindgen::fdt_open_into(fdt, dest, len) };
549 
550     FdtRawResult::from(ret).try_into()
551 }
552 
553 // TODO(stable_feature(pointer_is_aligned)): p.is_aligned()
is_aligned<T>(p: *const T) -> bool554 fn is_aligned<T>(p: *const T) -> bool {
555     (p as usize) % mem::align_of::<T>() == 0
556 }
557