blob: bb26e5304efbd8adbb5aad47093d1eac6b701976 [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};
22use core::ptr;
23
Pierre-Clément Tosiecd5bbc2023-12-21 15:12:45 +000024use crate::{fdt_err, fdt_err_expect_zero, fdt_err_or_option, FdtError, Phandle, Result};
Pierre-Clément Tosifbb5ee22023-12-21 13:49:59 +000025
26// Function names are the C function names without the `fdt_` prefix.
27
28/// Safe wrapper around `fdt_create_empty_tree()` (C function).
29pub(crate) fn create_empty_tree(fdt: &mut [u8]) -> Result<()> {
30 let len = fdt.len().try_into().unwrap();
31 let fdt = fdt.as_mut_ptr().cast();
32 // SAFETY: fdt_create_empty_tree() only write within the specified length,
33 // and returns error if buffer was insufficient.
34 // There will be no memory write outside of the given fdt.
35 let ret = unsafe { libfdt_bindgen::fdt_create_empty_tree(fdt, len) };
36
37 fdt_err_expect_zero(ret)
38}
39
40/// Safe wrapper around `fdt_check_full()` (C function).
41pub(crate) fn check_full(fdt: &[u8]) -> Result<()> {
42 let len = fdt.len();
43 let fdt = fdt.as_ptr().cast();
44 // SAFETY: Only performs read accesses within the limits of the slice. If successful, this
45 // call guarantees to other unsafe calls that the header contains a valid totalsize (w.r.t.
46 // 'len' i.e. the self.fdt slice) that those C functions can use to perform bounds
47 // checking. The library doesn't maintain an internal state (such as pointers) between
48 // calls as it expects the client code to keep track of the objects (DT, nodes, ...).
49 let ret = unsafe { libfdt_bindgen::fdt_check_full(fdt, len) };
50
51 fdt_err_expect_zero(ret)
52}
Pierre-Clément Tosid83741d2024-02-02 10:44:55 +000053
54/// Wrapper for the read-only libfdt.h functions.
55///
56/// # Safety
57///
58/// Implementors must ensure that at any point where a method of this trait is called, the
59/// underlying type returns the bytes of a valid device tree (as validated by `check_full`)
60/// through its `.as_fdt_slice` method.
61pub(crate) unsafe trait Libfdt {
62 /// Provides an immutable slice containing the device tree.
63 ///
64 /// The implementation must ensure that the size of the returned slice and
65 /// `fdt_header::totalsize` match.
66 fn as_fdt_slice(&self) -> &[u8];
67
68 /// Safe wrapper around `fdt_path_offset_namelen()` (C function).
69 fn path_offset_namelen(&self, path: &[u8]) -> Result<Option<c_int>> {
70 let fdt = self.as_fdt_slice().as_ptr().cast();
71 // *_namelen functions don't include the trailing nul terminator in 'len'.
72 let len = path.len().try_into().map_err(|_| FdtError::BadPath)?;
73 let path = path.as_ptr().cast();
74 // SAFETY: Accesses are constrained to the DT totalsize (validated by ctor) and the
75 // function respects the passed number of characters.
76 let ret = unsafe { libfdt_bindgen::fdt_path_offset_namelen(fdt, path, len) };
77
78 fdt_err_or_option(ret)
79 }
80
Pierre-Clément Tosiecd5bbc2023-12-21 15:12:45 +000081 /// Safe wrapper around `fdt_node_offset_by_phandle()` (C function).
82 fn node_offset_by_phandle(&self, phandle: Phandle) -> Result<Option<c_int>> {
83 let fdt = self.as_fdt_slice().as_ptr().cast();
84 let phandle = phandle.into();
85 // SAFETY: Accesses are constrained to the DT totalsize.
86 let ret = unsafe { libfdt_bindgen::fdt_node_offset_by_phandle(fdt, phandle) };
87
88 fdt_err_or_option(ret)
89 }
90
Pierre-Clément Tosid83741d2024-02-02 10:44:55 +000091 /// Safe wrapper around `fdt_node_offset_by_compatible()` (C function).
92 fn node_offset_by_compatible(&self, prev: c_int, compatible: &CStr) -> Result<Option<c_int>> {
93 let fdt = self.as_fdt_slice().as_ptr().cast();
94 let compatible = compatible.as_ptr();
95 // SAFETY: Accesses (read-only) are constrained to the DT totalsize.
96 let ret = unsafe { libfdt_bindgen::fdt_node_offset_by_compatible(fdt, prev, compatible) };
97
98 fdt_err_or_option(ret)
99 }
100
101 /// Safe wrapper around `fdt_next_node()` (C function).
102 fn next_node(&self, node: c_int, depth: usize) -> Result<Option<(c_int, usize)>> {
103 let fdt = self.as_fdt_slice().as_ptr().cast();
104 let mut depth = depth.try_into().unwrap();
105 // SAFETY: Accesses (read-only) are constrained to the DT totalsize.
106 let ret = unsafe { libfdt_bindgen::fdt_next_node(fdt, node, &mut depth) };
107
108 match fdt_err_or_option(ret)? {
109 Some(offset) if depth >= 0 => {
110 let depth = depth.try_into().unwrap();
111 Ok(Some((offset, depth)))
112 }
113 _ => Ok(None),
114 }
115 }
116
117 /// Safe wrapper around `fdt_parent_offset()` (C function).
118 ///
119 /// Note that this function returns a `Err` when called on a root.
120 fn parent_offset(&self, node: c_int) -> Result<c_int> {
121 let fdt = self.as_fdt_slice().as_ptr().cast();
122 // SAFETY: Accesses (read-only) are constrained to the DT totalsize.
123 let ret = unsafe { libfdt_bindgen::fdt_parent_offset(fdt, node) };
124
125 fdt_err(ret)
126 }
127
128 /// Safe wrapper around `fdt_supernode_atdepth_offset()` (C function).
129 ///
130 /// Note that this function returns a `Err` when called on a node at a depth shallower than
131 /// the provided `depth`.
132 fn supernode_atdepth_offset(&self, node: c_int, depth: usize) -> Result<c_int> {
133 let fdt = self.as_fdt_slice().as_ptr().cast();
134 let depth = depth.try_into().unwrap();
135 let nodedepth = ptr::null_mut();
136 let ret =
137 // SAFETY: Accesses (read-only) are constrained to the DT totalsize.
138 unsafe { libfdt_bindgen::fdt_supernode_atdepth_offset(fdt, node, depth, nodedepth) };
139
140 fdt_err(ret)
141 }
142
143 /// Safe wrapper around `fdt_subnode_offset_namelen()` (C function).
144 fn subnode_offset_namelen(&self, parent: c_int, name: &[u8]) -> Result<Option<c_int>> {
145 let fdt = self.as_fdt_slice().as_ptr().cast();
146 let namelen = name.len().try_into().unwrap();
147 let name = name.as_ptr().cast();
148 // SAFETY: Accesses are constrained to the DT totalsize (validated by ctor).
149 let ret = unsafe { libfdt_bindgen::fdt_subnode_offset_namelen(fdt, parent, name, namelen) };
150
151 fdt_err_or_option(ret)
152 }
153 /// Safe wrapper around `fdt_first_subnode()` (C function).
154 fn first_subnode(&self, node: c_int) -> Result<Option<c_int>> {
155 let fdt = self.as_fdt_slice().as_ptr().cast();
156 // SAFETY: Accesses (read-only) are constrained to the DT totalsize.
157 let ret = unsafe { libfdt_bindgen::fdt_first_subnode(fdt, node) };
158
159 fdt_err_or_option(ret)
160 }
161
162 /// Safe wrapper around `fdt_next_subnode()` (C function).
163 fn next_subnode(&self, node: c_int) -> Result<Option<c_int>> {
164 let fdt = self.as_fdt_slice().as_ptr().cast();
165 // SAFETY: Accesses (read-only) are constrained to the DT totalsize.
166 let ret = unsafe { libfdt_bindgen::fdt_next_subnode(fdt, node) };
167
168 fdt_err_or_option(ret)
169 }
170
171 /// Safe wrapper around `fdt_address_cells()` (C function).
172 fn address_cells(&self, node: c_int) -> Result<usize> {
173 let fdt = self.as_fdt_slice().as_ptr().cast();
174 // SAFETY: Accesses are constrained to the DT totalsize (validated by ctor).
175 let ret = unsafe { libfdt_bindgen::fdt_address_cells(fdt, node) };
176
177 Ok(fdt_err(ret)?.try_into().unwrap())
178 }
179
180 /// Safe wrapper around `fdt_size_cells()` (C function).
181 fn size_cells(&self, node: c_int) -> Result<usize> {
182 let fdt = self.as_fdt_slice().as_ptr().cast();
183 // SAFETY: Accesses are constrained to the DT totalsize (validated by ctor).
184 let ret = unsafe { libfdt_bindgen::fdt_size_cells(fdt, node) };
185
186 Ok(fdt_err(ret)?.try_into().unwrap())
187 }
Pierre-Clément Tosiecd5bbc2023-12-21 15:12:45 +0000188
Pierre-Clément Tosi60282ae2023-12-21 16:00:02 +0000189 /// Safe wrapper around `fdt_get_name()` (C function).
190 fn get_name(&self, node: c_int) -> Result<&[u8]> {
191 let fdt = self.as_fdt_slice().as_ptr().cast();
192 let mut len = 0;
193 // SAFETY: Accesses are constrained to the DT totalsize (validated by ctor). On success, the
194 // function returns valid null terminating string and otherwise returned values are dropped.
195 let name = unsafe { libfdt_bindgen::fdt_get_name(fdt, node, &mut len) };
196 let len = usize::try_from(fdt_err(len)?).unwrap().checked_add(1).unwrap();
197
198 get_slice_at_ptr(self.as_fdt_slice(), name.cast(), len).ok_or(FdtError::Internal)
199 }
200
Pierre-Clément Tosiecd5bbc2023-12-21 15:12:45 +0000201 /// Safe wrapper around `fdt_find_max_phandle()` (C function).
202 fn find_max_phandle(&self) -> Result<Phandle> {
203 let fdt = self.as_fdt_slice().as_ptr().cast();
204 let mut phandle = 0;
205 // SAFETY: Accesses (read-only) are constrained to the DT totalsize.
206 let ret = unsafe { libfdt_bindgen::fdt_find_max_phandle(fdt, &mut phandle) };
207
208 fdt_err_expect_zero(ret)?;
209
210 phandle.try_into()
211 }
Pierre-Clément Tosi60282ae2023-12-21 16:00:02 +0000212
213 /// Safe wrapper around `fdt_string()` (C function).
214 fn string(&self, offset: c_int) -> Result<&CStr> {
215 let fdt = self.as_fdt_slice().as_ptr().cast();
216 // SAFETY: Accesses (read-only) are constrained to the DT totalsize.
217 let ptr = unsafe { libfdt_bindgen::fdt_string(fdt, offset) };
218 if ptr.is_null() {
219 return Err(FdtError::Internal);
220 }
221
222 // SAFETY: Non-null return from fdt_string() is valid null-terminating string within FDT.
223 Ok(unsafe { CStr::from_ptr(ptr) })
224 }
Pierre-Clément Tosid83741d2024-02-02 10:44:55 +0000225}
226
227/// Wrapper for the read-write libfdt.h functions.
228///
229/// # Safety
230///
231/// Implementors must ensure that at any point where a method of this trait is called, the
232/// underlying type returns the bytes of a valid device tree (as validated by `check_full`)
233/// through its `.as_fdt_slice_mut` method.
234///
235/// Some methods may make previously returned values such as node or string offsets or phandles
236/// invalid by modifying the device tree (e.g. by inserting or removing new nodes or properties).
237/// As most methods take or return such values, instead of marking them all as unsafe, this trait
238/// is marked as unsafe as implementors must ensure that methods that modify the validity of those
239/// values are never called while the values are still in use.
240pub(crate) unsafe trait LibfdtMut {
241 /// Provides a mutable pointer to a buffer containing the device tree.
242 ///
243 /// The implementation must ensure that the size of the returned slice is at least
244 /// `fdt_header::totalsize`, to allow for device tree growth.
245 fn as_fdt_slice_mut(&mut self) -> &mut [u8];
246
247 /// Safe wrapper around `fdt_nop_node()` (C function).
248 fn nop_node(&mut self, node: c_int) -> Result<()> {
249 let fdt = self.as_fdt_slice_mut().as_mut_ptr().cast();
250 // SAFETY: Accesses are constrained to the DT totalsize (validated by ctor).
251 let ret = unsafe { libfdt_bindgen::fdt_nop_node(fdt, node) };
252
253 fdt_err_expect_zero(ret)
254 }
255
256 /// Safe wrapper around `fdt_add_subnode_namelen()` (C function).
257 fn add_subnode_namelen(&mut self, node: c_int, name: &[u8]) -> Result<c_int> {
258 let fdt = self.as_fdt_slice_mut().as_mut_ptr().cast();
259 let namelen = name.len().try_into().unwrap();
260 let name = name.as_ptr().cast();
261 // SAFETY: Accesses are constrained to the DT totalsize (validated by ctor).
262 let ret = unsafe { libfdt_bindgen::fdt_add_subnode_namelen(fdt, node, name, namelen) };
263
264 fdt_err(ret)
265 }
266}
Pierre-Clément Tosi60282ae2023-12-21 16:00:02 +0000267
268pub(crate) fn get_slice_at_ptr(s: &[u8], p: *const u8, len: usize) -> Option<&[u8]> {
269 let offset = get_slice_ptr_offset(s, p)?;
270
271 s.get(offset..offset.checked_add(len)?)
272}
273
274fn get_slice_ptr_offset(s: &[u8], p: *const u8) -> Option<usize> {
275 s.as_ptr_range().contains(&p).then(|| {
276 // SAFETY: Both pointers are in bounds, derive from the same object, and size_of::<T>()=1.
277 (unsafe { p.offset_from(s.as_ptr()) }) as usize
278 // TODO(stable_feature(ptr_sub_ptr)): p.sub_ptr()
279 })
280}