blob: 6869af6c89a7557ae01439458e4f9a79519f1dba [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 Tosi0606f702024-01-19 16:25:16 +000021use core::ffi::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;
Pierre-Clément Tosi0606f702024-01-19 16:25:16 +000026use crate::{FdtError, NodeOffset, Phandle, PropOffset, Result, StringOffset};
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).
Pierre-Clément Tosiee0a1eb2024-01-29 13:14:25 +000071 fn path_offset_namelen(&self, path: &[u8]) -> Result<Option<NodeOffset>> {
Pierre-Clément Tosid83741d2024-02-02 10:44:55 +000072 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).
Pierre-Clément Tosiee0a1eb2024-01-29 13:14:25 +000084 fn node_offset_by_phandle(&self, phandle: Phandle) -> Result<Option<NodeOffset>> {
Pierre-Clément Tosiecd5bbc2023-12-21 15:12:45 +000085 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).
Pierre-Clément Tosiee0a1eb2024-01-29 13:14:25 +000094 fn node_offset_by_compatible(
95 &self,
96 prev: NodeOffset,
97 compatible: &CStr,
98 ) -> Result<Option<NodeOffset>> {
Pierre-Clément Tosid83741d2024-02-02 10:44:55 +000099 let fdt = self.as_fdt_slice().as_ptr().cast();
Pierre-Clément Tosiee0a1eb2024-01-29 13:14:25 +0000100 let prev = prev.into();
Pierre-Clément Tosid83741d2024-02-02 10:44:55 +0000101 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
Pierre-Clément Tosi91be1902024-01-22 21:15:19 +0000105 FdtRawResult::from(ret).try_into()
Pierre-Clément Tosid83741d2024-02-02 10:44:55 +0000106 }
107
108 /// Safe wrapper around `fdt_next_node()` (C function).
Pierre-Clément Tosiee0a1eb2024-01-29 13:14:25 +0000109 fn next_node(&self, node: NodeOffset, depth: usize) -> Result<Option<(NodeOffset, usize)>> {
Pierre-Clément Tosid83741d2024-02-02 10:44:55 +0000110 let fdt = self.as_fdt_slice().as_ptr().cast();
Pierre-Clément Tosiee0a1eb2024-01-29 13:14:25 +0000111 let node = node.into();
Pierre-Clément Tosid83741d2024-02-02 10:44:55 +0000112 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
Pierre-Clément Tosi91be1902024-01-22 21:15:19 +0000116 match FdtRawResult::from(ret).try_into()? {
Pierre-Clément Tosid83741d2024-02-02 10:44:55 +0000117 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.
Pierre-Clément Tosiee0a1eb2024-01-29 13:14:25 +0000128 fn parent_offset(&self, node: NodeOffset) -> Result<NodeOffset> {
Pierre-Clément Tosid83741d2024-02-02 10:44:55 +0000129 let fdt = self.as_fdt_slice().as_ptr().cast();
Pierre-Clément Tosiee0a1eb2024-01-29 13:14:25 +0000130 let node = node.into();
Pierre-Clément Tosid83741d2024-02-02 10:44:55 +0000131 // SAFETY: Accesses (read-only) are constrained to the DT totalsize.
132 let ret = unsafe { libfdt_bindgen::fdt_parent_offset(fdt, node) };
133
Pierre-Clément Tosi91be1902024-01-22 21:15:19 +0000134 FdtRawResult::from(ret).try_into()
Pierre-Clément Tosid83741d2024-02-02 10:44:55 +0000135 }
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`.
Pierre-Clément Tosiee0a1eb2024-01-29 13:14:25 +0000141 fn supernode_atdepth_offset(&self, node: NodeOffset, depth: usize) -> Result<NodeOffset> {
Pierre-Clément Tosid83741d2024-02-02 10:44:55 +0000142 let fdt = self.as_fdt_slice().as_ptr().cast();
Pierre-Clément Tosiee0a1eb2024-01-29 13:14:25 +0000143 let node = node.into();
Pierre-Clément Tosid83741d2024-02-02 10:44:55 +0000144 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
Pierre-Clément Tosi91be1902024-01-22 21:15:19 +0000150 FdtRawResult::from(ret).try_into()
Pierre-Clément Tosid83741d2024-02-02 10:44:55 +0000151 }
152
153 /// Safe wrapper around `fdt_subnode_offset_namelen()` (C function).
Pierre-Clément Tosiee0a1eb2024-01-29 13:14:25 +0000154 fn subnode_offset_namelen(
155 &self,
156 parent: NodeOffset,
157 name: &[u8],
158 ) -> Result<Option<NodeOffset>> {
Pierre-Clément Tosid83741d2024-02-02 10:44:55 +0000159 let fdt = self.as_fdt_slice().as_ptr().cast();
Pierre-Clément Tosiee0a1eb2024-01-29 13:14:25 +0000160 let parent = parent.into();
Pierre-Clément Tosid83741d2024-02-02 10:44:55 +0000161 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
Pierre-Clément Tosi91be1902024-01-22 21:15:19 +0000166 FdtRawResult::from(ret).try_into()
Pierre-Clément Tosid83741d2024-02-02 10:44:55 +0000167 }
168 /// Safe wrapper around `fdt_first_subnode()` (C function).
Pierre-Clément Tosiee0a1eb2024-01-29 13:14:25 +0000169 fn first_subnode(&self, node: NodeOffset) -> Result<Option<NodeOffset>> {
Pierre-Clément Tosid83741d2024-02-02 10:44:55 +0000170 let fdt = self.as_fdt_slice().as_ptr().cast();
Pierre-Clément Tosiee0a1eb2024-01-29 13:14:25 +0000171 let node = node.into();
Pierre-Clément Tosid83741d2024-02-02 10:44:55 +0000172 // SAFETY: Accesses (read-only) are constrained to the DT totalsize.
173 let ret = unsafe { libfdt_bindgen::fdt_first_subnode(fdt, node) };
174
Pierre-Clément Tosi91be1902024-01-22 21:15:19 +0000175 FdtRawResult::from(ret).try_into()
Pierre-Clément Tosid83741d2024-02-02 10:44:55 +0000176 }
177
178 /// Safe wrapper around `fdt_next_subnode()` (C function).
Pierre-Clément Tosiee0a1eb2024-01-29 13:14:25 +0000179 fn next_subnode(&self, node: NodeOffset) -> Result<Option<NodeOffset>> {
Pierre-Clément Tosid83741d2024-02-02 10:44:55 +0000180 let fdt = self.as_fdt_slice().as_ptr().cast();
Pierre-Clément Tosiee0a1eb2024-01-29 13:14:25 +0000181 let node = node.into();
Pierre-Clément Tosid83741d2024-02-02 10:44:55 +0000182 // SAFETY: Accesses (read-only) are constrained to the DT totalsize.
183 let ret = unsafe { libfdt_bindgen::fdt_next_subnode(fdt, node) };
184
Pierre-Clément Tosi91be1902024-01-22 21:15:19 +0000185 FdtRawResult::from(ret).try_into()
Pierre-Clément Tosid83741d2024-02-02 10:44:55 +0000186 }
187
188 /// Safe wrapper around `fdt_address_cells()` (C function).
Pierre-Clément Tosiee0a1eb2024-01-29 13:14:25 +0000189 fn address_cells(&self, node: NodeOffset) -> Result<usize> {
Pierre-Clément Tosid83741d2024-02-02 10:44:55 +0000190 let fdt = self.as_fdt_slice().as_ptr().cast();
Pierre-Clément Tosiee0a1eb2024-01-29 13:14:25 +0000191 let node = node.into();
Pierre-Clément Tosid83741d2024-02-02 10:44:55 +0000192 // SAFETY: Accesses are constrained to the DT totalsize (validated by ctor).
193 let ret = unsafe { libfdt_bindgen::fdt_address_cells(fdt, node) };
194
Pierre-Clément Tosi91be1902024-01-22 21:15:19 +0000195 FdtRawResult::from(ret).try_into()
Pierre-Clément Tosid83741d2024-02-02 10:44:55 +0000196 }
197
198 /// Safe wrapper around `fdt_size_cells()` (C function).
Pierre-Clément Tosiee0a1eb2024-01-29 13:14:25 +0000199 fn size_cells(&self, node: NodeOffset) -> Result<usize> {
Pierre-Clément Tosid83741d2024-02-02 10:44:55 +0000200 let fdt = self.as_fdt_slice().as_ptr().cast();
Pierre-Clément Tosiee0a1eb2024-01-29 13:14:25 +0000201 let node = node.into();
Pierre-Clément Tosid83741d2024-02-02 10:44:55 +0000202 // SAFETY: Accesses are constrained to the DT totalsize (validated by ctor).
203 let ret = unsafe { libfdt_bindgen::fdt_size_cells(fdt, node) };
204
Pierre-Clément Tosi91be1902024-01-22 21:15:19 +0000205 FdtRawResult::from(ret).try_into()
Pierre-Clément Tosid83741d2024-02-02 10:44:55 +0000206 }
Pierre-Clément Tosiecd5bbc2023-12-21 15:12:45 +0000207
Pierre-Clément Tosi60282ae2023-12-21 16:00:02 +0000208 /// Safe wrapper around `fdt_get_name()` (C function).
Pierre-Clément Tosiee0a1eb2024-01-29 13:14:25 +0000209 fn get_name(&self, node: NodeOffset) -> Result<&[u8]> {
Pierre-Clément Tosi60282ae2023-12-21 16:00:02 +0000210 let fdt = self.as_fdt_slice().as_ptr().cast();
Pierre-Clément Tosiee0a1eb2024-01-29 13:14:25 +0000211 let node = node.into();
Pierre-Clément Tosi60282ae2023-12-21 16:00:02 +0000212 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) };
Pierre-Clément Tosi91be1902024-01-22 21:15:19 +0000216 let len = usize::try_from(FdtRawResult::from(len))?.checked_add(1).unwrap();
Pierre-Clément Tosi60282ae2023-12-21 16:00:02 +0000217
218 get_slice_at_ptr(self.as_fdt_slice(), name.cast(), len).ok_or(FdtError::Internal)
219 }
220
Pierre-Clément Tosi410e46a2023-12-24 11:33:11 +0000221 /// Safe wrapper around `fdt_getprop_namelen()` (C function).
Pierre-Clément Tosiee0a1eb2024-01-29 13:14:25 +0000222 fn getprop_namelen(&self, node: NodeOffset, name: &[u8]) -> Result<Option<&[u8]>> {
Pierre-Clément Tosi410e46a2023-12-24 11:33:11 +0000223 let fdt = self.as_fdt_slice().as_ptr().cast();
Pierre-Clément Tosiee0a1eb2024-01-29 13:14:25 +0000224 let node = node.into();
Pierre-Clément Tosi410e46a2023-12-24 11:33:11 +0000225 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
Pierre-Clément Tosi91be1902024-01-22 21:15:19 +0000233 if let Some(len) = FdtRawResult::from(len).try_into()? {
Pierre-Clément Tosi410e46a2023-12-24 11:33:11 +0000234 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).
Pierre-Clément Tosi0606f702024-01-19 16:25:16 +0000243 fn get_property_by_offset(&self, offset: PropOffset) -> Result<&libfdt_bindgen::fdt_property> {
Pierre-Clément Tosi410e46a2023-12-24 11:33:11 +0000244 let mut len = 0;
245 let fdt = self.as_fdt_slice().as_ptr().cast();
Pierre-Clément Tosi0606f702024-01-19 16:25:16 +0000246 let offset = offset.into();
Pierre-Clément Tosi410e46a2023-12-24 11:33:11 +0000247 // 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) };
Pierre-Clément Tosieabe1f52024-01-23 22:47:43 +0000249
Pierre-Clément Tosi91be1902024-01-22 21:15:19 +0000250 let data_len = FdtRawResult::from(len).try_into()?;
Pierre-Clément Tosia6997512024-06-28 13:54:31 +0100251 let data_offset = mem::offset_of!(libfdt_bindgen::fdt_property, data);
Pierre-Clément Tosieabe1f52024-01-23 22:47:43 +0000252 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);
Pierre-Clément Tosi410e46a2023-12-24 11:33:11 +0000256 }
257
Pierre-Clément Tosieabe1f52024-01-23 22:47:43 +0000258 // 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)
Pierre-Clément Tosi410e46a2023-12-24 11:33:11 +0000266 }
267
268 /// Safe wrapper around `fdt_first_property_offset()` (C function).
Pierre-Clément Tosi0606f702024-01-19 16:25:16 +0000269 fn first_property_offset(&self, node: NodeOffset) -> Result<Option<PropOffset>> {
Pierre-Clément Tosi410e46a2023-12-24 11:33:11 +0000270 let fdt = self.as_fdt_slice().as_ptr().cast();
Pierre-Clément Tosiee0a1eb2024-01-29 13:14:25 +0000271 let node = node.into();
Pierre-Clément Tosi410e46a2023-12-24 11:33:11 +0000272 // SAFETY: Accesses (read-only) are constrained to the DT totalsize.
273 let ret = unsafe { libfdt_bindgen::fdt_first_property_offset(fdt, node) };
274
Pierre-Clément Tosi91be1902024-01-22 21:15:19 +0000275 FdtRawResult::from(ret).try_into()
Pierre-Clément Tosi410e46a2023-12-24 11:33:11 +0000276 }
277
278 /// Safe wrapper around `fdt_next_property_offset()` (C function).
Pierre-Clément Tosi0606f702024-01-19 16:25:16 +0000279 fn next_property_offset(&self, prev: PropOffset) -> Result<Option<PropOffset>> {
Pierre-Clément Tosi410e46a2023-12-24 11:33:11 +0000280 let fdt = self.as_fdt_slice().as_ptr().cast();
Pierre-Clément Tosi0606f702024-01-19 16:25:16 +0000281 let prev = prev.into();
Pierre-Clément Tosi410e46a2023-12-24 11:33:11 +0000282 // SAFETY: Accesses (read-only) are constrained to the DT totalsize.
283 let ret = unsafe { libfdt_bindgen::fdt_next_property_offset(fdt, prev) };
284
Pierre-Clément Tosi91be1902024-01-22 21:15:19 +0000285 FdtRawResult::from(ret).try_into()
Pierre-Clément Tosi410e46a2023-12-24 11:33:11 +0000286 }
287
Pierre-Clément Tosiecd5bbc2023-12-21 15:12:45 +0000288 /// Safe wrapper around `fdt_find_max_phandle()` (C function).
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
Chris Wailesa7ca8fa2024-09-05 14:49:10 -0700295 () = FdtRawResult::from(ret).try_into()?;
Pierre-Clément Tosiecd5bbc2023-12-21 15:12:45 +0000296
297 phandle.try_into()
298 }
Pierre-Clément Tosi60282ae2023-12-21 16:00:02 +0000299
300 /// Safe wrapper around `fdt_string()` (C function).
Pierre-Clément Tosi0606f702024-01-19 16:25:16 +0000301 fn string(&self, offset: StringOffset) -> Result<&CStr> {
Pierre-Clément Tosi60282ae2023-12-21 16:00:02 +0000302 let fdt = self.as_fdt_slice().as_ptr().cast();
Pierre-Clément Tosi0606f702024-01-19 16:25:16 +0000303 let offset = offset.into();
Pierre-Clément Tosi60282ae2023-12-21 16:00:02 +0000304 // SAFETY: Accesses (read-only) are constrained to the DT totalsize.
305 let ptr = unsafe { libfdt_bindgen::fdt_string(fdt, offset) };
Pierre-Clément Tosia4eaba92024-01-23 21:24:37 +0000306 let bytes =
307 get_slice_from_ptr(self.as_fdt_slice(), ptr.cast()).ok_or(FdtError::Internal)?;
Pierre-Clément Tosi60282ae2023-12-21 16:00:02 +0000308
Pierre-Clément Tosia4eaba92024-01-23 21:24:37 +0000309 CStr::from_bytes_until_nul(bytes).map_err(|_| FdtError::Internal)
Pierre-Clément Tosi60282ae2023-12-21 16:00:02 +0000310 }
Pierre-Clément Tosie21ed3f2024-01-23 18:16:13 +0000311
312 /// Safe wrapper around `fdt_open_into()` (C function).
Chris Wailes6177c662024-05-09 14:37:44 -0700313 #[allow(dead_code)]
Pierre-Clément Tosie21ed3f2024-01-23 18:16:13 +0000314 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 }
Pierre-Clément Tosid83741d2024-02-02 10:44:55 +0000319}
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.
334pub(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.
339 fn as_fdt_slice_mut(&mut self) -> &mut [u8];
340
341 /// Safe wrapper around `fdt_nop_node()` (C function).
Pierre-Clément Tosiee0a1eb2024-01-29 13:14:25 +0000342 fn nop_node(&mut self, node: NodeOffset) -> Result<()> {
Pierre-Clément Tosid83741d2024-02-02 10:44:55 +0000343 let fdt = self.as_fdt_slice_mut().as_mut_ptr().cast();
Pierre-Clément Tosiee0a1eb2024-01-29 13:14:25 +0000344 let node = node.into();
Pierre-Clément Tosid83741d2024-02-02 10:44:55 +0000345 // SAFETY: Accesses are constrained to the DT totalsize (validated by ctor).
346 let ret = unsafe { libfdt_bindgen::fdt_nop_node(fdt, node) };
347
Pierre-Clément Tosi91be1902024-01-22 21:15:19 +0000348 FdtRawResult::from(ret).try_into()
Pierre-Clément Tosid83741d2024-02-02 10:44:55 +0000349 }
350
351 /// Safe wrapper around `fdt_add_subnode_namelen()` (C function).
Pierre-Clément Tosiee0a1eb2024-01-29 13:14:25 +0000352 fn add_subnode_namelen(&mut self, node: NodeOffset, name: &[u8]) -> Result<NodeOffset> {
Pierre-Clément Tosid83741d2024-02-02 10:44:55 +0000353 let fdt = self.as_fdt_slice_mut().as_mut_ptr().cast();
Pierre-Clément Tosiee0a1eb2024-01-29 13:14:25 +0000354 let node = node.into();
Pierre-Clément Tosid83741d2024-02-02 10:44:55 +0000355 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
Pierre-Clément Tosi91be1902024-01-22 21:15:19 +0000360 FdtRawResult::from(ret).try_into()
Pierre-Clément Tosid83741d2024-02-02 10:44:55 +0000361 }
Pierre-Clément Tosi843845d2024-01-23 23:35:01 +0000362
Pierre-Clément Tosi410e46a2023-12-24 11:33:11 +0000363 /// Safe wrapper around `fdt_setprop()` (C function).
Pierre-Clément Tosiee0a1eb2024-01-29 13:14:25 +0000364 fn setprop(&mut self, node: NodeOffset, name: &CStr, value: &[u8]) -> Result<()> {
Pierre-Clément Tosi410e46a2023-12-24 11:33:11 +0000365 let fdt = self.as_fdt_slice_mut().as_mut_ptr().cast();
Pierre-Clément Tosiee0a1eb2024-01-29 13:14:25 +0000366 let node = node.into();
Pierre-Clément Tosi410e46a2023-12-24 11:33:11 +0000367 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
Pierre-Clément Tosi91be1902024-01-22 21:15:19 +0000374 FdtRawResult::from(ret).try_into()
Pierre-Clément Tosi410e46a2023-12-24 11:33:11 +0000375 }
376
Pierre-Clément Tosi843845d2024-01-23 23:35:01 +0000377 /// Safe wrapper around `fdt_setprop_placeholder()` (C function).
Pierre-Clément Tosiee0a1eb2024-01-29 13:14:25 +0000378 fn setprop_placeholder(
379 &mut self,
380 node: NodeOffset,
381 name: &CStr,
382 size: usize,
383 ) -> Result<&mut [u8]> {
Pierre-Clément Tosi843845d2024-01-23 23:35:01 +0000384 let fdt = self.as_fdt_slice_mut().as_mut_ptr().cast();
Pierre-Clément Tosiee0a1eb2024-01-29 13:14:25 +0000385 let node = node.into();
Pierre-Clément Tosi843845d2024-01-23 23:35:01 +0000386 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
Chris Wailesa7ca8fa2024-09-05 14:49:10 -0700393 () = FdtRawResult::from(ret).try_into()?;
Pierre-Clément Tosi843845d2024-01-23 23:35:01 +0000394
395 get_mut_slice_at_ptr(self.as_fdt_slice_mut(), data.cast(), size).ok_or(FdtError::Internal)
396 }
Pierre-Clément Tosi410e46a2023-12-24 11:33:11 +0000397
398 /// Safe wrapper around `fdt_setprop_inplace()` (C function).
Pierre-Clément Tosiee0a1eb2024-01-29 13:14:25 +0000399 fn setprop_inplace(&mut self, node: NodeOffset, name: &CStr, value: &[u8]) -> Result<()> {
Pierre-Clément Tosi410e46a2023-12-24 11:33:11 +0000400 let fdt = self.as_fdt_slice_mut().as_mut_ptr().cast();
Pierre-Clément Tosiee0a1eb2024-01-29 13:14:25 +0000401 let node = node.into();
Pierre-Clément Tosi410e46a2023-12-24 11:33:11 +0000402 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
Pierre-Clément Tosi91be1902024-01-22 21:15:19 +0000409 FdtRawResult::from(ret).try_into()
Pierre-Clément Tosi410e46a2023-12-24 11:33:11 +0000410 }
411
412 /// Safe wrapper around `fdt_appendprop()` (C function).
Pierre-Clément Tosiee0a1eb2024-01-29 13:14:25 +0000413 fn appendprop(&mut self, node: NodeOffset, name: &CStr, value: &[u8]) -> Result<()> {
Pierre-Clément Tosi410e46a2023-12-24 11:33:11 +0000414 let fdt = self.as_fdt_slice_mut().as_mut_ptr().cast();
Pierre-Clément Tosiee0a1eb2024-01-29 13:14:25 +0000415 let node = node.into();
Pierre-Clément Tosi410e46a2023-12-24 11:33:11 +0000416 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
Pierre-Clément Tosi91be1902024-01-22 21:15:19 +0000422 FdtRawResult::from(ret).try_into()
Pierre-Clément Tosi410e46a2023-12-24 11:33:11 +0000423 }
424
425 /// Safe wrapper around `fdt_appendprop_addrrange()` (C function).
426 fn appendprop_addrrange(
427 &mut self,
Pierre-Clément Tosiee0a1eb2024-01-29 13:14:25 +0000428 parent: NodeOffset,
429 node: NodeOffset,
Pierre-Clément Tosi410e46a2023-12-24 11:33:11 +0000430 name: &CStr,
431 addr: u64,
432 size: u64,
433 ) -> Result<()> {
434 let fdt = self.as_fdt_slice_mut().as_mut_ptr().cast();
Pierre-Clément Tosiee0a1eb2024-01-29 13:14:25 +0000435 let parent = parent.into();
436 let node = node.into();
Pierre-Clément Tosi410e46a2023-12-24 11:33:11 +0000437 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
Pierre-Clément Tosi91be1902024-01-22 21:15:19 +0000443 FdtRawResult::from(ret).try_into()
Pierre-Clément Tosi410e46a2023-12-24 11:33:11 +0000444 }
445
446 /// Safe wrapper around `fdt_delprop()` (C function).
Pierre-Clément Tosiee0a1eb2024-01-29 13:14:25 +0000447 fn delprop(&mut self, node: NodeOffset, name: &CStr) -> Result<()> {
Pierre-Clément Tosi410e46a2023-12-24 11:33:11 +0000448 let fdt = self.as_fdt_slice_mut().as_mut_ptr().cast();
Pierre-Clément Tosiee0a1eb2024-01-29 13:14:25 +0000449 let node = node.into();
Pierre-Clément Tosi410e46a2023-12-24 11:33:11 +0000450 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
Pierre-Clément Tosi91be1902024-01-22 21:15:19 +0000457 FdtRawResult::from(ret).try_into()
Pierre-Clément Tosi410e46a2023-12-24 11:33:11 +0000458 }
459
460 /// Safe wrapper around `fdt_nop_property()` (C function).
Pierre-Clément Tosiee0a1eb2024-01-29 13:14:25 +0000461 fn nop_property(&mut self, node: NodeOffset, name: &CStr) -> Result<()> {
Pierre-Clément Tosi410e46a2023-12-24 11:33:11 +0000462 let fdt = self.as_fdt_slice_mut().as_mut_ptr().cast();
Pierre-Clément Tosiee0a1eb2024-01-29 13:14:25 +0000463 let node = node.into();
Pierre-Clément Tosi410e46a2023-12-24 11:33:11 +0000464 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
Pierre-Clément Tosi91be1902024-01-22 21:15:19 +0000469 FdtRawResult::from(ret).try_into()
Pierre-Clément Tosi410e46a2023-12-24 11:33:11 +0000470 }
Pierre-Clément Tosie21ed3f2024-01-23 18:16:13 +0000471
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.
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).
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
Pierre-Clément Tosi91be1902024-01-22 21:15:19 +0000492 FdtRawResult::from(ret).try_into()
Pierre-Clément Tosie21ed3f2024-01-23 18:16:13 +0000493 }
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.
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
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 }
Pierre-Clément Tosid83741d2024-02-02 10:44:55 +0000513}
Pierre-Clément Tosi60282ae2023-12-21 16:00:02 +0000514
515pub(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
Pierre-Clément Tosi843845d2024-01-23 23:35:01 +0000521fn 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
Pierre-Clément Tosia4eaba92024-01-23 21:24:37 +0000527fn get_slice_from_ptr(s: &[u8], p: *const u8) -> Option<&[u8]> {
528 s.get(get_slice_ptr_offset(s, p)?..)
529}
530
Pierre-Clément Tosi60282ae2023-12-21 16:00:02 +0000531fn 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}
Pierre-Clément Tosieabe1f52024-01-23 22:47:43 +0000538
Pierre-Clément Tosie21ed3f2024-01-23 18:16:13 +0000539fn 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
Pierre-Clément Tosi91be1902024-01-22 21:15:19 +0000549 FdtRawResult::from(ret).try_into()
Pierre-Clément Tosie21ed3f2024-01-23 18:16:13 +0000550}
551
Pierre-Clément Tosieabe1f52024-01-23 22:47:43 +0000552// TODO(stable_feature(pointer_is_aligned)): p.is_aligned()
553fn is_aligned<T>(p: *const T) -> bool {
554 (p as usize) % mem::align_of::<T>() == 0
555}