blob: 9ddfbaabe689bc3bf1fb96a35ac43b0c96b4150f [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 Tosieabe1f52024-01-23 22:47:43 +0000251 // 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);
Pierre-Clément Tosi410e46a2023-12-24 11:33:11 +0000257 }
258
Pierre-Clément Tosieabe1f52024-01-23 22:47:43 +0000259 // 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)
Pierre-Clément Tosi410e46a2023-12-24 11:33:11 +0000267 }
268
269 /// Safe wrapper around `fdt_first_property_offset()` (C function).
Pierre-Clément Tosi0606f702024-01-19 16:25:16 +0000270 fn first_property_offset(&self, node: NodeOffset) -> Result<Option<PropOffset>> {
Pierre-Clément Tosi410e46a2023-12-24 11:33:11 +0000271 let fdt = self.as_fdt_slice().as_ptr().cast();
Pierre-Clément Tosiee0a1eb2024-01-29 13:14:25 +0000272 let node = node.into();
Pierre-Clément Tosi410e46a2023-12-24 11:33:11 +0000273 // SAFETY: Accesses (read-only) are constrained to the DT totalsize.
274 let ret = unsafe { libfdt_bindgen::fdt_first_property_offset(fdt, node) };
275
Pierre-Clément Tosi91be1902024-01-22 21:15:19 +0000276 FdtRawResult::from(ret).try_into()
Pierre-Clément Tosi410e46a2023-12-24 11:33:11 +0000277 }
278
279 /// Safe wrapper around `fdt_next_property_offset()` (C function).
Pierre-Clément Tosi0606f702024-01-19 16:25:16 +0000280 fn next_property_offset(&self, prev: PropOffset) -> Result<Option<PropOffset>> {
Pierre-Clément Tosi410e46a2023-12-24 11:33:11 +0000281 let fdt = self.as_fdt_slice().as_ptr().cast();
Pierre-Clément Tosi0606f702024-01-19 16:25:16 +0000282 let prev = prev.into();
Pierre-Clément Tosi410e46a2023-12-24 11:33:11 +0000283 // SAFETY: Accesses (read-only) are constrained to the DT totalsize.
284 let ret = unsafe { libfdt_bindgen::fdt_next_property_offset(fdt, prev) };
285
Pierre-Clément Tosi91be1902024-01-22 21:15:19 +0000286 FdtRawResult::from(ret).try_into()
Pierre-Clément Tosi410e46a2023-12-24 11:33:11 +0000287 }
288
Pierre-Clément Tosiecd5bbc2023-12-21 15:12:45 +0000289 /// Safe wrapper around `fdt_find_max_phandle()` (C function).
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
Pierre-Clément Tosi91be1902024-01-22 21:15:19 +0000296 FdtRawResult::from(ret).try_into()?;
Pierre-Clément Tosiecd5bbc2023-12-21 15:12:45 +0000297
298 phandle.try_into()
299 }
Pierre-Clément Tosi60282ae2023-12-21 16:00:02 +0000300
301 /// Safe wrapper around `fdt_string()` (C function).
Pierre-Clément Tosi0606f702024-01-19 16:25:16 +0000302 fn string(&self, offset: StringOffset) -> Result<&CStr> {
Pierre-Clément Tosi60282ae2023-12-21 16:00:02 +0000303 let fdt = self.as_fdt_slice().as_ptr().cast();
Pierre-Clément Tosi0606f702024-01-19 16:25:16 +0000304 let offset = offset.into();
Pierre-Clément Tosi60282ae2023-12-21 16:00:02 +0000305 // SAFETY: Accesses (read-only) are constrained to the DT totalsize.
306 let ptr = unsafe { libfdt_bindgen::fdt_string(fdt, offset) };
Pierre-Clément Tosia4eaba92024-01-23 21:24:37 +0000307 let bytes =
308 get_slice_from_ptr(self.as_fdt_slice(), ptr.cast()).ok_or(FdtError::Internal)?;
Pierre-Clément Tosi60282ae2023-12-21 16:00:02 +0000309
Pierre-Clément Tosia4eaba92024-01-23 21:24:37 +0000310 CStr::from_bytes_until_nul(bytes).map_err(|_| FdtError::Internal)
Pierre-Clément Tosi60282ae2023-12-21 16:00:02 +0000311 }
Pierre-Clément Tosie21ed3f2024-01-23 18:16:13 +0000312
313 /// Safe wrapper around `fdt_open_into()` (C function).
Chris Wailes6177c662024-05-09 14:37:44 -0700314 #[allow(dead_code)]
Pierre-Clément Tosie21ed3f2024-01-23 18:16:13 +0000315 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 }
Pierre-Clément Tosid83741d2024-02-02 10:44:55 +0000320}
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.
335pub(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.
340 fn as_fdt_slice_mut(&mut self) -> &mut [u8];
341
342 /// Safe wrapper around `fdt_nop_node()` (C function).
Pierre-Clément Tosiee0a1eb2024-01-29 13:14:25 +0000343 fn nop_node(&mut self, node: NodeOffset) -> Result<()> {
Pierre-Clément Tosid83741d2024-02-02 10:44:55 +0000344 let fdt = self.as_fdt_slice_mut().as_mut_ptr().cast();
Pierre-Clément Tosiee0a1eb2024-01-29 13:14:25 +0000345 let node = node.into();
Pierre-Clément Tosid83741d2024-02-02 10:44:55 +0000346 // SAFETY: Accesses are constrained to the DT totalsize (validated by ctor).
347 let ret = unsafe { libfdt_bindgen::fdt_nop_node(fdt, node) };
348
Pierre-Clément Tosi91be1902024-01-22 21:15:19 +0000349 FdtRawResult::from(ret).try_into()
Pierre-Clément Tosid83741d2024-02-02 10:44:55 +0000350 }
351
352 /// Safe wrapper around `fdt_add_subnode_namelen()` (C function).
Pierre-Clément Tosiee0a1eb2024-01-29 13:14:25 +0000353 fn add_subnode_namelen(&mut self, node: NodeOffset, name: &[u8]) -> Result<NodeOffset> {
Pierre-Clément Tosid83741d2024-02-02 10:44:55 +0000354 let fdt = self.as_fdt_slice_mut().as_mut_ptr().cast();
Pierre-Clément Tosiee0a1eb2024-01-29 13:14:25 +0000355 let node = node.into();
Pierre-Clément Tosid83741d2024-02-02 10:44:55 +0000356 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
Pierre-Clément Tosi91be1902024-01-22 21:15:19 +0000361 FdtRawResult::from(ret).try_into()
Pierre-Clément Tosid83741d2024-02-02 10:44:55 +0000362 }
Pierre-Clément Tosi843845d2024-01-23 23:35:01 +0000363
Pierre-Clément Tosi410e46a2023-12-24 11:33:11 +0000364 /// Safe wrapper around `fdt_setprop()` (C function).
Pierre-Clément Tosiee0a1eb2024-01-29 13:14:25 +0000365 fn setprop(&mut self, node: NodeOffset, name: &CStr, value: &[u8]) -> Result<()> {
Pierre-Clément Tosi410e46a2023-12-24 11:33:11 +0000366 let fdt = self.as_fdt_slice_mut().as_mut_ptr().cast();
Pierre-Clément Tosiee0a1eb2024-01-29 13:14:25 +0000367 let node = node.into();
Pierre-Clément Tosi410e46a2023-12-24 11:33:11 +0000368 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
Pierre-Clément Tosi91be1902024-01-22 21:15:19 +0000375 FdtRawResult::from(ret).try_into()
Pierre-Clément Tosi410e46a2023-12-24 11:33:11 +0000376 }
377
Pierre-Clément Tosi843845d2024-01-23 23:35:01 +0000378 /// Safe wrapper around `fdt_setprop_placeholder()` (C function).
Pierre-Clément Tosiee0a1eb2024-01-29 13:14:25 +0000379 fn setprop_placeholder(
380 &mut self,
381 node: NodeOffset,
382 name: &CStr,
383 size: usize,
384 ) -> Result<&mut [u8]> {
Pierre-Clément Tosi843845d2024-01-23 23:35:01 +0000385 let fdt = self.as_fdt_slice_mut().as_mut_ptr().cast();
Pierre-Clément Tosiee0a1eb2024-01-29 13:14:25 +0000386 let node = node.into();
Pierre-Clément Tosi843845d2024-01-23 23:35:01 +0000387 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
Pierre-Clément Tosi91be1902024-01-22 21:15:19 +0000394 FdtRawResult::from(ret).try_into()?;
Pierre-Clément Tosi843845d2024-01-23 23:35:01 +0000395
396 get_mut_slice_at_ptr(self.as_fdt_slice_mut(), data.cast(), size).ok_or(FdtError::Internal)
397 }
Pierre-Clément Tosi410e46a2023-12-24 11:33:11 +0000398
399 /// Safe wrapper around `fdt_setprop_inplace()` (C function).
Pierre-Clément Tosiee0a1eb2024-01-29 13:14:25 +0000400 fn setprop_inplace(&mut self, node: NodeOffset, name: &CStr, value: &[u8]) -> Result<()> {
Pierre-Clément Tosi410e46a2023-12-24 11:33:11 +0000401 let fdt = self.as_fdt_slice_mut().as_mut_ptr().cast();
Pierre-Clément Tosiee0a1eb2024-01-29 13:14:25 +0000402 let node = node.into();
Pierre-Clément Tosi410e46a2023-12-24 11:33:11 +0000403 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
Pierre-Clément Tosi91be1902024-01-22 21:15:19 +0000410 FdtRawResult::from(ret).try_into()
Pierre-Clément Tosi410e46a2023-12-24 11:33:11 +0000411 }
412
413 /// Safe wrapper around `fdt_appendprop()` (C function).
Pierre-Clément Tosiee0a1eb2024-01-29 13:14:25 +0000414 fn appendprop(&mut self, node: NodeOffset, name: &CStr, value: &[u8]) -> Result<()> {
Pierre-Clément Tosi410e46a2023-12-24 11:33:11 +0000415 let fdt = self.as_fdt_slice_mut().as_mut_ptr().cast();
Pierre-Clément Tosiee0a1eb2024-01-29 13:14:25 +0000416 let node = node.into();
Pierre-Clément Tosi410e46a2023-12-24 11:33:11 +0000417 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
Pierre-Clément Tosi91be1902024-01-22 21:15:19 +0000423 FdtRawResult::from(ret).try_into()
Pierre-Clément Tosi410e46a2023-12-24 11:33:11 +0000424 }
425
426 /// Safe wrapper around `fdt_appendprop_addrrange()` (C function).
427 fn appendprop_addrrange(
428 &mut self,
Pierre-Clément Tosiee0a1eb2024-01-29 13:14:25 +0000429 parent: NodeOffset,
430 node: NodeOffset,
Pierre-Clément Tosi410e46a2023-12-24 11:33:11 +0000431 name: &CStr,
432 addr: u64,
433 size: u64,
434 ) -> Result<()> {
435 let fdt = self.as_fdt_slice_mut().as_mut_ptr().cast();
Pierre-Clément Tosiee0a1eb2024-01-29 13:14:25 +0000436 let parent = parent.into();
437 let node = node.into();
Pierre-Clément Tosi410e46a2023-12-24 11:33:11 +0000438 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
Pierre-Clément Tosi91be1902024-01-22 21:15:19 +0000444 FdtRawResult::from(ret).try_into()
Pierre-Clément Tosi410e46a2023-12-24 11:33:11 +0000445 }
446
447 /// Safe wrapper around `fdt_delprop()` (C function).
Pierre-Clément Tosiee0a1eb2024-01-29 13:14:25 +0000448 fn delprop(&mut self, node: NodeOffset, name: &CStr) -> Result<()> {
Pierre-Clément Tosi410e46a2023-12-24 11:33:11 +0000449 let fdt = self.as_fdt_slice_mut().as_mut_ptr().cast();
Pierre-Clément Tosiee0a1eb2024-01-29 13:14:25 +0000450 let node = node.into();
Pierre-Clément Tosi410e46a2023-12-24 11:33:11 +0000451 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
Pierre-Clément Tosi91be1902024-01-22 21:15:19 +0000458 FdtRawResult::from(ret).try_into()
Pierre-Clément Tosi410e46a2023-12-24 11:33:11 +0000459 }
460
461 /// Safe wrapper around `fdt_nop_property()` (C function).
Pierre-Clément Tosiee0a1eb2024-01-29 13:14:25 +0000462 fn nop_property(&mut self, node: NodeOffset, name: &CStr) -> Result<()> {
Pierre-Clément Tosi410e46a2023-12-24 11:33:11 +0000463 let fdt = self.as_fdt_slice_mut().as_mut_ptr().cast();
Pierre-Clément Tosiee0a1eb2024-01-29 13:14:25 +0000464 let node = node.into();
Pierre-Clément Tosi410e46a2023-12-24 11:33:11 +0000465 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
Pierre-Clément Tosi91be1902024-01-22 21:15:19 +0000470 FdtRawResult::from(ret).try_into()
Pierre-Clément Tosi410e46a2023-12-24 11:33:11 +0000471 }
Pierre-Clément Tosie21ed3f2024-01-23 18:16:13 +0000472
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.
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).
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
Pierre-Clément Tosi91be1902024-01-22 21:15:19 +0000493 FdtRawResult::from(ret).try_into()
Pierre-Clément Tosie21ed3f2024-01-23 18:16:13 +0000494 }
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.
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
Pierre-Clément Tosi91be1902024-01-22 21:15:19 +0000512 FdtRawResult::from(ret).try_into()
Pierre-Clément Tosie21ed3f2024-01-23 18:16:13 +0000513 }
Pierre-Clément Tosid83741d2024-02-02 10:44:55 +0000514}
Pierre-Clément Tosi60282ae2023-12-21 16:00:02 +0000515
516pub(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
Pierre-Clément Tosi843845d2024-01-23 23:35:01 +0000522fn 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
Pierre-Clément Tosia4eaba92024-01-23 21:24:37 +0000528fn get_slice_from_ptr(s: &[u8], p: *const u8) -> Option<&[u8]> {
529 s.get(get_slice_ptr_offset(s, p)?..)
530}
531
Pierre-Clément Tosi60282ae2023-12-21 16:00:02 +0000532fn 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}
Pierre-Clément Tosieabe1f52024-01-23 22:47:43 +0000539
Pierre-Clément Tosie21ed3f2024-01-23 18:16:13 +0000540fn 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
Pierre-Clément Tosi91be1902024-01-22 21:15:19 +0000550 FdtRawResult::from(ret).try_into()
Pierre-Clément Tosie21ed3f2024-01-23 18:16:13 +0000551}
552
Pierre-Clément Tosieabe1f52024-01-23 22:47:43 +0000553// TODO(stable_feature(pointer_is_aligned)): p.is_aligned()
554fn is_aligned<T>(p: *const T) -> bool {
555 (p as usize) % mem::align_of::<T>() == 0
556}