blob: 1e82c9f19d9f7789932871b2142904064d538ada [file] [log] [blame]
Pierre-Clément Tosifbb5ee22023-12-21 13:49:59 +00001// 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.
Pierre-Clément Tosid83741d2024-02-02 10:44:55 +000016//!
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).
Pierre-Clément Tosifbb5ee22023-12-21 13:49:59 +000020
Pierre-Clément Tosid83741d2024-02-02 10:44:55 +000021use core::ffi::{c_int, CStr};
Pierre-Clément Tosieabe1f52024-01-23 22:47:43 +000022use core::mem;
Pierre-Clément Tosid83741d2024-02-02 10:44:55 +000023use core::ptr;
24
Pierre-Clément Tosi91be1902024-01-22 21:15:19 +000025use crate::result::FdtRawResult;
26use crate::{FdtError, Phandle, Result};
Pierre-Clément Tosifbb5ee22023-12-21 13:49:59 +000027
28// Function names are the C function names without the `fdt_` prefix.
29
30/// Safe wrapper around `fdt_create_empty_tree()` (C function).
31pub(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
Pierre-Clément Tosi91be1902024-01-22 21:15:19 +000039 FdtRawResult::from(ret).try_into()
Pierre-Clément Tosifbb5ee22023-12-21 13:49:59 +000040}
41
42/// Safe wrapper around `fdt_check_full()` (C function).
43pub(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
Pierre-Clément Tosi91be1902024-01-22 21:15:19 +000053 FdtRawResult::from(ret).try_into()
Pierre-Clément Tosifbb5ee22023-12-21 13:49:59 +000054}
Pierre-Clément Tosid83741d2024-02-02 10:44:55 +000055
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.
63pub(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.
68 fn as_fdt_slice(&self) -> &[u8];
69
70 /// Safe wrapper around `fdt_path_offset_namelen()` (C function).
71 fn path_offset_namelen(&self, path: &[u8]) -> Result<Option<c_int>> {
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
Pierre-Clément Tosi91be1902024-01-22 21:15:19 +000080 FdtRawResult::from(ret).try_into()
Pierre-Clément Tosid83741d2024-02-02 10:44:55 +000081 }
82
Pierre-Clément Tosiecd5bbc2023-12-21 15:12:45 +000083 /// Safe wrapper around `fdt_node_offset_by_phandle()` (C function).
84 fn node_offset_by_phandle(&self, phandle: Phandle) -> Result<Option<c_int>> {
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
Pierre-Clément Tosi91be1902024-01-22 21:15:19 +000090 FdtRawResult::from(ret).try_into()
Pierre-Clément Tosiecd5bbc2023-12-21 15:12:45 +000091 }
92
Pierre-Clément Tosid83741d2024-02-02 10:44:55 +000093 /// Safe wrapper around `fdt_node_offset_by_compatible()` (C function).
94 fn node_offset_by_compatible(&self, prev: c_int, compatible: &CStr) -> Result<Option<c_int>> {
95 let fdt = self.as_fdt_slice().as_ptr().cast();
96 let compatible = compatible.as_ptr();
97 // SAFETY: Accesses (read-only) are constrained to the DT totalsize.
98 let ret = unsafe { libfdt_bindgen::fdt_node_offset_by_compatible(fdt, prev, compatible) };
99
Pierre-Clément Tosi91be1902024-01-22 21:15:19 +0000100 FdtRawResult::from(ret).try_into()
Pierre-Clément Tosid83741d2024-02-02 10:44:55 +0000101 }
102
103 /// Safe wrapper around `fdt_next_node()` (C function).
104 fn next_node(&self, node: c_int, depth: usize) -> Result<Option<(c_int, usize)>> {
105 let fdt = self.as_fdt_slice().as_ptr().cast();
106 let mut depth = depth.try_into().unwrap();
107 // SAFETY: Accesses (read-only) are constrained to the DT totalsize.
108 let ret = unsafe { libfdt_bindgen::fdt_next_node(fdt, node, &mut depth) };
109
Pierre-Clément Tosi91be1902024-01-22 21:15:19 +0000110 match FdtRawResult::from(ret).try_into()? {
Pierre-Clément Tosid83741d2024-02-02 10:44:55 +0000111 Some(offset) if depth >= 0 => {
112 let depth = depth.try_into().unwrap();
113 Ok(Some((offset, depth)))
114 }
115 _ => Ok(None),
116 }
117 }
118
119 /// Safe wrapper around `fdt_parent_offset()` (C function).
120 ///
121 /// Note that this function returns a `Err` when called on a root.
122 fn parent_offset(&self, node: c_int) -> Result<c_int> {
123 let fdt = self.as_fdt_slice().as_ptr().cast();
124 // SAFETY: Accesses (read-only) are constrained to the DT totalsize.
125 let ret = unsafe { libfdt_bindgen::fdt_parent_offset(fdt, node) };
126
Pierre-Clément Tosi91be1902024-01-22 21:15:19 +0000127 FdtRawResult::from(ret).try_into()
Pierre-Clément Tosid83741d2024-02-02 10:44:55 +0000128 }
129
130 /// Safe wrapper around `fdt_supernode_atdepth_offset()` (C function).
131 ///
132 /// Note that this function returns a `Err` when called on a node at a depth shallower than
133 /// the provided `depth`.
134 fn supernode_atdepth_offset(&self, node: c_int, depth: usize) -> Result<c_int> {
135 let fdt = self.as_fdt_slice().as_ptr().cast();
136 let depth = depth.try_into().unwrap();
137 let nodedepth = ptr::null_mut();
138 let ret =
139 // SAFETY: Accesses (read-only) are constrained to the DT totalsize.
140 unsafe { libfdt_bindgen::fdt_supernode_atdepth_offset(fdt, node, depth, nodedepth) };
141
Pierre-Clément Tosi91be1902024-01-22 21:15:19 +0000142 FdtRawResult::from(ret).try_into()
Pierre-Clément Tosid83741d2024-02-02 10:44:55 +0000143 }
144
145 /// Safe wrapper around `fdt_subnode_offset_namelen()` (C function).
146 fn subnode_offset_namelen(&self, parent: c_int, name: &[u8]) -> Result<Option<c_int>> {
147 let fdt = self.as_fdt_slice().as_ptr().cast();
148 let namelen = name.len().try_into().unwrap();
149 let name = name.as_ptr().cast();
150 // SAFETY: Accesses are constrained to the DT totalsize (validated by ctor).
151 let ret = unsafe { libfdt_bindgen::fdt_subnode_offset_namelen(fdt, parent, name, namelen) };
152
Pierre-Clément Tosi91be1902024-01-22 21:15:19 +0000153 FdtRawResult::from(ret).try_into()
Pierre-Clément Tosid83741d2024-02-02 10:44:55 +0000154 }
155 /// Safe wrapper around `fdt_first_subnode()` (C function).
156 fn first_subnode(&self, node: c_int) -> Result<Option<c_int>> {
157 let fdt = self.as_fdt_slice().as_ptr().cast();
158 // SAFETY: Accesses (read-only) are constrained to the DT totalsize.
159 let ret = unsafe { libfdt_bindgen::fdt_first_subnode(fdt, node) };
160
Pierre-Clément Tosi91be1902024-01-22 21:15:19 +0000161 FdtRawResult::from(ret).try_into()
Pierre-Clément Tosid83741d2024-02-02 10:44:55 +0000162 }
163
164 /// Safe wrapper around `fdt_next_subnode()` (C function).
165 fn next_subnode(&self, node: c_int) -> Result<Option<c_int>> {
166 let fdt = self.as_fdt_slice().as_ptr().cast();
167 // SAFETY: Accesses (read-only) are constrained to the DT totalsize.
168 let ret = unsafe { libfdt_bindgen::fdt_next_subnode(fdt, node) };
169
Pierre-Clément Tosi91be1902024-01-22 21:15:19 +0000170 FdtRawResult::from(ret).try_into()
Pierre-Clément Tosid83741d2024-02-02 10:44:55 +0000171 }
172
173 /// Safe wrapper around `fdt_address_cells()` (C function).
174 fn address_cells(&self, node: c_int) -> Result<usize> {
175 let fdt = self.as_fdt_slice().as_ptr().cast();
176 // SAFETY: Accesses are constrained to the DT totalsize (validated by ctor).
177 let ret = unsafe { libfdt_bindgen::fdt_address_cells(fdt, node) };
178
Pierre-Clément Tosi91be1902024-01-22 21:15:19 +0000179 FdtRawResult::from(ret).try_into()
Pierre-Clément Tosid83741d2024-02-02 10:44:55 +0000180 }
181
182 /// Safe wrapper around `fdt_size_cells()` (C function).
183 fn size_cells(&self, node: c_int) -> Result<usize> {
184 let fdt = self.as_fdt_slice().as_ptr().cast();
185 // SAFETY: Accesses are constrained to the DT totalsize (validated by ctor).
186 let ret = unsafe { libfdt_bindgen::fdt_size_cells(fdt, node) };
187
Pierre-Clément Tosi91be1902024-01-22 21:15:19 +0000188 FdtRawResult::from(ret).try_into()
Pierre-Clément Tosid83741d2024-02-02 10:44:55 +0000189 }
Pierre-Clément Tosiecd5bbc2023-12-21 15:12:45 +0000190
Pierre-Clément Tosi60282ae2023-12-21 16:00:02 +0000191 /// Safe wrapper around `fdt_get_name()` (C function).
192 fn get_name(&self, node: c_int) -> Result<&[u8]> {
193 let fdt = self.as_fdt_slice().as_ptr().cast();
194 let mut len = 0;
195 // SAFETY: Accesses are constrained to the DT totalsize (validated by ctor). On success, the
196 // function returns valid null terminating string and otherwise returned values are dropped.
197 let name = unsafe { libfdt_bindgen::fdt_get_name(fdt, node, &mut len) };
Pierre-Clément Tosi91be1902024-01-22 21:15:19 +0000198 let len = usize::try_from(FdtRawResult::from(len))?.checked_add(1).unwrap();
Pierre-Clément Tosi60282ae2023-12-21 16:00:02 +0000199
200 get_slice_at_ptr(self.as_fdt_slice(), name.cast(), len).ok_or(FdtError::Internal)
201 }
202
Pierre-Clément Tosi410e46a2023-12-24 11:33:11 +0000203 /// Safe wrapper around `fdt_getprop_namelen()` (C function).
204 fn getprop_namelen(&self, node: c_int, name: &[u8]) -> Result<Option<&[u8]>> {
205 let fdt = self.as_fdt_slice().as_ptr().cast();
206 let namelen = name.len().try_into().map_err(|_| FdtError::BadPath)?;
207 let name = name.as_ptr().cast();
208 let mut len = 0;
209 let prop =
210 // SAFETY: Accesses are constrained to the DT totalsize (validated by ctor) and the
211 // function respects the passed number of characters.
212 unsafe { libfdt_bindgen::fdt_getprop_namelen(fdt, node, name, namelen, &mut len) };
213
Pierre-Clément Tosi91be1902024-01-22 21:15:19 +0000214 if let Some(len) = FdtRawResult::from(len).try_into()? {
Pierre-Clément Tosi410e46a2023-12-24 11:33:11 +0000215 let bytes = get_slice_at_ptr(self.as_fdt_slice(), prop.cast(), len);
216
217 Ok(Some(bytes.ok_or(FdtError::Internal)?))
218 } else {
219 Ok(None)
220 }
221 }
222
223 /// Safe wrapper around `fdt_get_property_by_offset()` (C function).
224 fn get_property_by_offset(&self, offset: c_int) -> Result<&libfdt_bindgen::fdt_property> {
225 let mut len = 0;
226 let fdt = self.as_fdt_slice().as_ptr().cast();
227 // SAFETY: Accesses (read-only) are constrained to the DT totalsize.
228 let prop = unsafe { libfdt_bindgen::fdt_get_property_by_offset(fdt, offset, &mut len) };
Pierre-Clément Tosieabe1f52024-01-23 22:47:43 +0000229
Pierre-Clément Tosi91be1902024-01-22 21:15:19 +0000230 let data_len = FdtRawResult::from(len).try_into()?;
Pierre-Clément Tosieabe1f52024-01-23 22:47:43 +0000231 // TODO(stable_feature(offset_of)): mem::offset_of!(fdt_property, data).
232 let data_offset = memoffset::offset_of!(libfdt_bindgen::fdt_property, data);
233 let len = data_offset.checked_add(data_len).ok_or(FdtError::Internal)?;
234
235 if !is_aligned(prop) || get_slice_at_ptr(self.as_fdt_slice(), prop.cast(), len).is_none() {
236 return Err(FdtError::Internal);
Pierre-Clément Tosi410e46a2023-12-24 11:33:11 +0000237 }
238
Pierre-Clément Tosieabe1f52024-01-23 22:47:43 +0000239 // SAFETY: The pointer is properly aligned, struct is fully contained in the DT slice.
240 let prop = unsafe { &*prop };
241
242 if data_len != u32::from_be(prop.len).try_into().unwrap() {
243 return Err(FdtError::BadLayout);
244 }
245
246 Ok(prop)
Pierre-Clément Tosi410e46a2023-12-24 11:33:11 +0000247 }
248
249 /// Safe wrapper around `fdt_first_property_offset()` (C function).
250 fn first_property_offset(&self, node: c_int) -> Result<Option<c_int>> {
251 let fdt = self.as_fdt_slice().as_ptr().cast();
252 // SAFETY: Accesses (read-only) are constrained to the DT totalsize.
253 let ret = unsafe { libfdt_bindgen::fdt_first_property_offset(fdt, node) };
254
Pierre-Clément Tosi91be1902024-01-22 21:15:19 +0000255 FdtRawResult::from(ret).try_into()
Pierre-Clément Tosi410e46a2023-12-24 11:33:11 +0000256 }
257
258 /// Safe wrapper around `fdt_next_property_offset()` (C function).
259 fn next_property_offset(&self, prev: c_int) -> Result<Option<c_int>> {
260 let fdt = self.as_fdt_slice().as_ptr().cast();
261 // SAFETY: Accesses (read-only) are constrained to the DT totalsize.
262 let ret = unsafe { libfdt_bindgen::fdt_next_property_offset(fdt, prev) };
263
Pierre-Clément Tosi91be1902024-01-22 21:15:19 +0000264 FdtRawResult::from(ret).try_into()
Pierre-Clément Tosi410e46a2023-12-24 11:33:11 +0000265 }
266
Pierre-Clément Tosiecd5bbc2023-12-21 15:12:45 +0000267 /// Safe wrapper around `fdt_find_max_phandle()` (C function).
268 fn find_max_phandle(&self) -> Result<Phandle> {
269 let fdt = self.as_fdt_slice().as_ptr().cast();
270 let mut phandle = 0;
271 // SAFETY: Accesses (read-only) are constrained to the DT totalsize.
272 let ret = unsafe { libfdt_bindgen::fdt_find_max_phandle(fdt, &mut phandle) };
273
Pierre-Clément Tosi91be1902024-01-22 21:15:19 +0000274 FdtRawResult::from(ret).try_into()?;
Pierre-Clément Tosiecd5bbc2023-12-21 15:12:45 +0000275
276 phandle.try_into()
277 }
Pierre-Clément Tosi60282ae2023-12-21 16:00:02 +0000278
279 /// Safe wrapper around `fdt_string()` (C function).
280 fn string(&self, offset: c_int) -> Result<&CStr> {
281 let fdt = self.as_fdt_slice().as_ptr().cast();
282 // SAFETY: Accesses (read-only) are constrained to the DT totalsize.
283 let ptr = unsafe { libfdt_bindgen::fdt_string(fdt, offset) };
Pierre-Clément Tosia4eaba92024-01-23 21:24:37 +0000284 let bytes =
285 get_slice_from_ptr(self.as_fdt_slice(), ptr.cast()).ok_or(FdtError::Internal)?;
Pierre-Clément Tosi60282ae2023-12-21 16:00:02 +0000286
Pierre-Clément Tosia4eaba92024-01-23 21:24:37 +0000287 CStr::from_bytes_until_nul(bytes).map_err(|_| FdtError::Internal)
Pierre-Clément Tosi60282ae2023-12-21 16:00:02 +0000288 }
Pierre-Clément Tosie21ed3f2024-01-23 18:16:13 +0000289
290 /// Safe wrapper around `fdt_open_into()` (C function).
291 fn open_into(&self, dest: &mut [u8]) -> Result<()> {
292 let fdt = self.as_fdt_slice().as_ptr().cast();
293
294 open_into(fdt, dest)
295 }
Pierre-Clément Tosid83741d2024-02-02 10:44:55 +0000296}
297
298/// Wrapper for the read-write libfdt.h functions.
299///
300/// # Safety
301///
302/// Implementors must ensure that at any point where a method of this trait is called, the
303/// underlying type returns the bytes of a valid device tree (as validated by `check_full`)
304/// through its `.as_fdt_slice_mut` method.
305///
306/// Some methods may make previously returned values such as node or string offsets or phandles
307/// invalid by modifying the device tree (e.g. by inserting or removing new nodes or properties).
308/// As most methods take or return such values, instead of marking them all as unsafe, this trait
309/// is marked as unsafe as implementors must ensure that methods that modify the validity of those
310/// values are never called while the values are still in use.
311pub(crate) unsafe trait LibfdtMut {
312 /// Provides a mutable pointer to a buffer containing the device tree.
313 ///
314 /// The implementation must ensure that the size of the returned slice is at least
315 /// `fdt_header::totalsize`, to allow for device tree growth.
316 fn as_fdt_slice_mut(&mut self) -> &mut [u8];
317
318 /// Safe wrapper around `fdt_nop_node()` (C function).
319 fn nop_node(&mut self, node: c_int) -> Result<()> {
320 let fdt = self.as_fdt_slice_mut().as_mut_ptr().cast();
321 // SAFETY: Accesses are constrained to the DT totalsize (validated by ctor).
322 let ret = unsafe { libfdt_bindgen::fdt_nop_node(fdt, node) };
323
Pierre-Clément Tosi91be1902024-01-22 21:15:19 +0000324 FdtRawResult::from(ret).try_into()
Pierre-Clément Tosid83741d2024-02-02 10:44:55 +0000325 }
326
327 /// Safe wrapper around `fdt_add_subnode_namelen()` (C function).
328 fn add_subnode_namelen(&mut self, node: c_int, name: &[u8]) -> Result<c_int> {
329 let fdt = self.as_fdt_slice_mut().as_mut_ptr().cast();
330 let namelen = name.len().try_into().unwrap();
331 let name = name.as_ptr().cast();
332 // SAFETY: Accesses are constrained to the DT totalsize (validated by ctor).
333 let ret = unsafe { libfdt_bindgen::fdt_add_subnode_namelen(fdt, node, name, namelen) };
334
Pierre-Clément Tosi91be1902024-01-22 21:15:19 +0000335 FdtRawResult::from(ret).try_into()
Pierre-Clément Tosid83741d2024-02-02 10:44:55 +0000336 }
Pierre-Clément Tosi843845d2024-01-23 23:35:01 +0000337
Pierre-Clément Tosi410e46a2023-12-24 11:33:11 +0000338 /// Safe wrapper around `fdt_setprop()` (C function).
339 fn setprop(&mut self, node: c_int, name: &CStr, value: &[u8]) -> Result<()> {
340 let fdt = self.as_fdt_slice_mut().as_mut_ptr().cast();
341 let name = name.as_ptr();
342 let len = value.len().try_into().map_err(|_| FdtError::BadValue)?;
343 let value = value.as_ptr().cast();
344 // SAFETY: New value size is constrained to the DT totalsize
345 // (validated by underlying libfdt).
346 let ret = unsafe { libfdt_bindgen::fdt_setprop(fdt, node, name, value, len) };
347
Pierre-Clément Tosi91be1902024-01-22 21:15:19 +0000348 FdtRawResult::from(ret).try_into()
Pierre-Clément Tosi410e46a2023-12-24 11:33:11 +0000349 }
350
Pierre-Clément Tosi843845d2024-01-23 23:35:01 +0000351 /// Safe wrapper around `fdt_setprop_placeholder()` (C function).
352 fn setprop_placeholder(&mut self, node: c_int, name: &CStr, size: usize) -> Result<&mut [u8]> {
353 let fdt = self.as_fdt_slice_mut().as_mut_ptr().cast();
354 let name = name.as_ptr();
355 let len = size.try_into().unwrap();
356 let mut data = ptr::null_mut();
357 let ret =
358 // SAFETY: Accesses are constrained to the DT totalsize (validated by ctor).
359 unsafe { libfdt_bindgen::fdt_setprop_placeholder(fdt, node, name, len, &mut data) };
360
Pierre-Clément Tosi91be1902024-01-22 21:15:19 +0000361 FdtRawResult::from(ret).try_into()?;
Pierre-Clément Tosi843845d2024-01-23 23:35:01 +0000362
363 get_mut_slice_at_ptr(self.as_fdt_slice_mut(), data.cast(), size).ok_or(FdtError::Internal)
364 }
Pierre-Clément Tosi410e46a2023-12-24 11:33:11 +0000365
366 /// Safe wrapper around `fdt_setprop_inplace()` (C function).
367 fn setprop_inplace(&mut self, node: c_int, name: &CStr, value: &[u8]) -> Result<()> {
368 let fdt = self.as_fdt_slice_mut().as_mut_ptr().cast();
369 let name = name.as_ptr();
370 let len = value.len().try_into().map_err(|_| FdtError::BadValue)?;
371 let value = value.as_ptr().cast();
372 // SAFETY: New value size is constrained to the DT totalsize
373 // (validated by underlying libfdt).
374 let ret = unsafe { libfdt_bindgen::fdt_setprop_inplace(fdt, node, name, value, len) };
375
Pierre-Clément Tosi91be1902024-01-22 21:15:19 +0000376 FdtRawResult::from(ret).try_into()
Pierre-Clément Tosi410e46a2023-12-24 11:33:11 +0000377 }
378
379 /// Safe wrapper around `fdt_appendprop()` (C function).
380 fn appendprop(&mut self, node: c_int, name: &CStr, value: &[u8]) -> Result<()> {
381 let fdt = self.as_fdt_slice_mut().as_mut_ptr().cast();
382 let name = name.as_ptr();
383 let len = value.len().try_into().map_err(|_| FdtError::BadValue)?;
384 let value = value.as_ptr().cast();
385 // SAFETY: Accesses are constrained to the DT totalsize (validated by ctor).
386 let ret = unsafe { libfdt_bindgen::fdt_appendprop(fdt, node, name, value, len) };
387
Pierre-Clément Tosi91be1902024-01-22 21:15:19 +0000388 FdtRawResult::from(ret).try_into()
Pierre-Clément Tosi410e46a2023-12-24 11:33:11 +0000389 }
390
391 /// Safe wrapper around `fdt_appendprop_addrrange()` (C function).
392 fn appendprop_addrrange(
393 &mut self,
394 parent: c_int,
395 node: c_int,
396 name: &CStr,
397 addr: u64,
398 size: u64,
399 ) -> Result<()> {
400 let fdt = self.as_fdt_slice_mut().as_mut_ptr().cast();
401 let name = name.as_ptr();
402 // SAFETY: Accesses are constrained to the DT totalsize (validated by ctor).
403 let ret = unsafe {
404 libfdt_bindgen::fdt_appendprop_addrrange(fdt, parent, node, name, addr, size)
405 };
406
Pierre-Clément Tosi91be1902024-01-22 21:15:19 +0000407 FdtRawResult::from(ret).try_into()
Pierre-Clément Tosi410e46a2023-12-24 11:33:11 +0000408 }
409
410 /// Safe wrapper around `fdt_delprop()` (C function).
411 fn delprop(&mut self, node: c_int, name: &CStr) -> Result<()> {
412 let fdt = self.as_fdt_slice_mut().as_mut_ptr().cast();
413 let name = name.as_ptr();
414 // SAFETY: Accesses are constrained to the DT totalsize (validated by ctor) when the
415 // library locates the node's property. Removing the property may shift the offsets of
416 // other nodes and properties but the borrow checker should prevent this function from
417 // being called when FdtNode instances are in use.
418 let ret = unsafe { libfdt_bindgen::fdt_delprop(fdt, node, name) };
419
Pierre-Clément Tosi91be1902024-01-22 21:15:19 +0000420 FdtRawResult::from(ret).try_into()
Pierre-Clément Tosi410e46a2023-12-24 11:33:11 +0000421 }
422
423 /// Safe wrapper around `fdt_nop_property()` (C function).
424 fn nop_property(&mut self, node: c_int, name: &CStr) -> Result<()> {
425 let fdt = self.as_fdt_slice_mut().as_mut_ptr().cast();
426 let name = name.as_ptr();
427 // SAFETY: Accesses are constrained to the DT totalsize (validated by ctor) when the
428 // library locates the node's property.
429 let ret = unsafe { libfdt_bindgen::fdt_nop_property(fdt, node, name) };
430
Pierre-Clément Tosi91be1902024-01-22 21:15:19 +0000431 FdtRawResult::from(ret).try_into()
Pierre-Clément Tosi410e46a2023-12-24 11:33:11 +0000432 }
Pierre-Clément Tosie21ed3f2024-01-23 18:16:13 +0000433
434 /// Safe and aliasing-compatible wrapper around `fdt_open_into()` (C function).
435 ///
436 /// The C API allows both input (`const void*`) and output (`void *`) to point to the same
437 /// memory region but the borrow checker would reject an API such as
438 ///
439 /// self.open_into(&mut self.buffer)
440 ///
441 /// so this wrapper is provided to implement such a common aliasing case.
442 fn open_into_self(&mut self) -> Result<()> {
443 let fdt = self.as_fdt_slice_mut();
444
445 open_into(fdt.as_ptr().cast(), fdt)
446 }
447
448 /// Safe wrapper around `fdt_pack()` (C function).
449 fn pack(&mut self) -> Result<()> {
450 let fdt = self.as_fdt_slice_mut().as_mut_ptr().cast();
451 // SAFETY: Accesses (R/W) are constrained to the DT totalsize (validated by ctor).
452 let ret = unsafe { libfdt_bindgen::fdt_pack(fdt) };
453
Pierre-Clément Tosi91be1902024-01-22 21:15:19 +0000454 FdtRawResult::from(ret).try_into()
Pierre-Clément Tosie21ed3f2024-01-23 18:16:13 +0000455 }
456
457 /// Wrapper around `fdt_overlay_apply()` (C function).
458 ///
459 /// # Safety
460 ///
461 /// This function safely wraps the C function call but is unsafe because the caller must
462 ///
463 /// - discard `overlay` as a &LibfdtMut because libfdt corrupts its header before returning;
464 /// - on error, discard `self` as a &LibfdtMut for the same reason.
465 unsafe fn overlay_apply(&mut self, overlay: &mut Self) -> Result<()> {
466 let fdt = self.as_fdt_slice_mut().as_mut_ptr().cast();
467 let overlay = overlay.as_fdt_slice_mut().as_mut_ptr().cast();
468 // SAFETY: Both pointers are valid because they come from references, and fdt_overlay_apply
469 // doesn't keep them after it returns. It may corrupt their contents if there is an error,
470 // but that's our caller's responsibility.
471 let ret = unsafe { libfdt_bindgen::fdt_overlay_apply(fdt, overlay) };
472
Pierre-Clément Tosi91be1902024-01-22 21:15:19 +0000473 FdtRawResult::from(ret).try_into()
Pierre-Clément Tosie21ed3f2024-01-23 18:16:13 +0000474 }
Pierre-Clément Tosid83741d2024-02-02 10:44:55 +0000475}
Pierre-Clément Tosi60282ae2023-12-21 16:00:02 +0000476
477pub(crate) fn get_slice_at_ptr(s: &[u8], p: *const u8, len: usize) -> Option<&[u8]> {
478 let offset = get_slice_ptr_offset(s, p)?;
479
480 s.get(offset..offset.checked_add(len)?)
481}
482
Pierre-Clément Tosi843845d2024-01-23 23:35:01 +0000483fn get_mut_slice_at_ptr(s: &mut [u8], p: *mut u8, len: usize) -> Option<&mut [u8]> {
484 let offset = get_slice_ptr_offset(s, p)?;
485
486 s.get_mut(offset..offset.checked_add(len)?)
487}
488
Pierre-Clément Tosia4eaba92024-01-23 21:24:37 +0000489fn get_slice_from_ptr(s: &[u8], p: *const u8) -> Option<&[u8]> {
490 s.get(get_slice_ptr_offset(s, p)?..)
491}
492
Pierre-Clément Tosi60282ae2023-12-21 16:00:02 +0000493fn get_slice_ptr_offset(s: &[u8], p: *const u8) -> Option<usize> {
494 s.as_ptr_range().contains(&p).then(|| {
495 // SAFETY: Both pointers are in bounds, derive from the same object, and size_of::<T>()=1.
496 (unsafe { p.offset_from(s.as_ptr()) }) as usize
497 // TODO(stable_feature(ptr_sub_ptr)): p.sub_ptr()
498 })
499}
Pierre-Clément Tosieabe1f52024-01-23 22:47:43 +0000500
Pierre-Clément Tosie21ed3f2024-01-23 18:16:13 +0000501fn open_into(fdt: *const u8, dest: &mut [u8]) -> Result<()> {
502 let fdt = fdt.cast();
503 let len = dest.len().try_into().map_err(|_| FdtError::Internal)?;
504 let dest = dest.as_mut_ptr().cast();
505 // SAFETY: Reads the whole fdt slice (based on the validated totalsize) and, if it fits, copies
506 // it to the (properly mutable) dest buffer of size len. On success, the resulting dest
507 // contains a valid DT with the nodes and properties of the original one but of a different
508 // size, reflected in its fdt_header::totalsize.
509 let ret = unsafe { libfdt_bindgen::fdt_open_into(fdt, dest, len) };
510
Pierre-Clément Tosi91be1902024-01-22 21:15:19 +0000511 FdtRawResult::from(ret).try_into()
Pierre-Clément Tosie21ed3f2024-01-23 18:16:13 +0000512}
513
Pierre-Clément Tosieabe1f52024-01-23 22:47:43 +0000514// TODO(stable_feature(pointer_is_aligned)): p.is_aligned()
515fn is_aligned<T>(p: *const T) -> bool {
516 (p as usize) % mem::align_of::<T>() == 0
517}