blob: 7e3b65a6c052bc58c9d2f86e5bf7a3058435c090 [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
24use crate::{fdt_err, fdt_err_expect_zero, fdt_err_or_option, FdtError, 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
81 /// Safe wrapper around `fdt_node_offset_by_compatible()` (C function).
82 fn node_offset_by_compatible(&self, prev: c_int, compatible: &CStr) -> Result<Option<c_int>> {
83 let fdt = self.as_fdt_slice().as_ptr().cast();
84 let compatible = compatible.as_ptr();
85 // SAFETY: Accesses (read-only) are constrained to the DT totalsize.
86 let ret = unsafe { libfdt_bindgen::fdt_node_offset_by_compatible(fdt, prev, compatible) };
87
88 fdt_err_or_option(ret)
89 }
90
91 /// Safe wrapper around `fdt_next_node()` (C function).
92 fn next_node(&self, node: c_int, depth: usize) -> Result<Option<(c_int, usize)>> {
93 let fdt = self.as_fdt_slice().as_ptr().cast();
94 let mut depth = depth.try_into().unwrap();
95 // SAFETY: Accesses (read-only) are constrained to the DT totalsize.
96 let ret = unsafe { libfdt_bindgen::fdt_next_node(fdt, node, &mut depth) };
97
98 match fdt_err_or_option(ret)? {
99 Some(offset) if depth >= 0 => {
100 let depth = depth.try_into().unwrap();
101 Ok(Some((offset, depth)))
102 }
103 _ => Ok(None),
104 }
105 }
106
107 /// Safe wrapper around `fdt_parent_offset()` (C function).
108 ///
109 /// Note that this function returns a `Err` when called on a root.
110 fn parent_offset(&self, node: c_int) -> Result<c_int> {
111 let fdt = self.as_fdt_slice().as_ptr().cast();
112 // SAFETY: Accesses (read-only) are constrained to the DT totalsize.
113 let ret = unsafe { libfdt_bindgen::fdt_parent_offset(fdt, node) };
114
115 fdt_err(ret)
116 }
117
118 /// Safe wrapper around `fdt_supernode_atdepth_offset()` (C function).
119 ///
120 /// Note that this function returns a `Err` when called on a node at a depth shallower than
121 /// the provided `depth`.
122 fn supernode_atdepth_offset(&self, node: c_int, depth: usize) -> Result<c_int> {
123 let fdt = self.as_fdt_slice().as_ptr().cast();
124 let depth = depth.try_into().unwrap();
125 let nodedepth = ptr::null_mut();
126 let ret =
127 // SAFETY: Accesses (read-only) are constrained to the DT totalsize.
128 unsafe { libfdt_bindgen::fdt_supernode_atdepth_offset(fdt, node, depth, nodedepth) };
129
130 fdt_err(ret)
131 }
132
133 /// Safe wrapper around `fdt_subnode_offset_namelen()` (C function).
134 fn subnode_offset_namelen(&self, parent: c_int, name: &[u8]) -> Result<Option<c_int>> {
135 let fdt = self.as_fdt_slice().as_ptr().cast();
136 let namelen = name.len().try_into().unwrap();
137 let name = name.as_ptr().cast();
138 // SAFETY: Accesses are constrained to the DT totalsize (validated by ctor).
139 let ret = unsafe { libfdt_bindgen::fdt_subnode_offset_namelen(fdt, parent, name, namelen) };
140
141 fdt_err_or_option(ret)
142 }
143 /// Safe wrapper around `fdt_first_subnode()` (C function).
144 fn first_subnode(&self, node: c_int) -> Result<Option<c_int>> {
145 let fdt = self.as_fdt_slice().as_ptr().cast();
146 // SAFETY: Accesses (read-only) are constrained to the DT totalsize.
147 let ret = unsafe { libfdt_bindgen::fdt_first_subnode(fdt, node) };
148
149 fdt_err_or_option(ret)
150 }
151
152 /// Safe wrapper around `fdt_next_subnode()` (C function).
153 fn next_subnode(&self, node: c_int) -> Result<Option<c_int>> {
154 let fdt = self.as_fdt_slice().as_ptr().cast();
155 // SAFETY: Accesses (read-only) are constrained to the DT totalsize.
156 let ret = unsafe { libfdt_bindgen::fdt_next_subnode(fdt, node) };
157
158 fdt_err_or_option(ret)
159 }
160
161 /// Safe wrapper around `fdt_address_cells()` (C function).
162 fn address_cells(&self, node: c_int) -> Result<usize> {
163 let fdt = self.as_fdt_slice().as_ptr().cast();
164 // SAFETY: Accesses are constrained to the DT totalsize (validated by ctor).
165 let ret = unsafe { libfdt_bindgen::fdt_address_cells(fdt, node) };
166
167 Ok(fdt_err(ret)?.try_into().unwrap())
168 }
169
170 /// Safe wrapper around `fdt_size_cells()` (C function).
171 fn size_cells(&self, node: c_int) -> Result<usize> {
172 let fdt = self.as_fdt_slice().as_ptr().cast();
173 // SAFETY: Accesses are constrained to the DT totalsize (validated by ctor).
174 let ret = unsafe { libfdt_bindgen::fdt_size_cells(fdt, node) };
175
176 Ok(fdt_err(ret)?.try_into().unwrap())
177 }
178}
179
180/// Wrapper for the read-write libfdt.h functions.
181///
182/// # Safety
183///
184/// Implementors must ensure that at any point where a method of this trait is called, the
185/// underlying type returns the bytes of a valid device tree (as validated by `check_full`)
186/// through its `.as_fdt_slice_mut` method.
187///
188/// Some methods may make previously returned values such as node or string offsets or phandles
189/// invalid by modifying the device tree (e.g. by inserting or removing new nodes or properties).
190/// As most methods take or return such values, instead of marking them all as unsafe, this trait
191/// is marked as unsafe as implementors must ensure that methods that modify the validity of those
192/// values are never called while the values are still in use.
193pub(crate) unsafe trait LibfdtMut {
194 /// Provides a mutable pointer to a buffer containing the device tree.
195 ///
196 /// The implementation must ensure that the size of the returned slice is at least
197 /// `fdt_header::totalsize`, to allow for device tree growth.
198 fn as_fdt_slice_mut(&mut self) -> &mut [u8];
199
200 /// Safe wrapper around `fdt_nop_node()` (C function).
201 fn nop_node(&mut self, node: c_int) -> Result<()> {
202 let fdt = self.as_fdt_slice_mut().as_mut_ptr().cast();
203 // SAFETY: Accesses are constrained to the DT totalsize (validated by ctor).
204 let ret = unsafe { libfdt_bindgen::fdt_nop_node(fdt, node) };
205
206 fdt_err_expect_zero(ret)
207 }
208
209 /// Safe wrapper around `fdt_add_subnode_namelen()` (C function).
210 fn add_subnode_namelen(&mut self, node: c_int, name: &[u8]) -> Result<c_int> {
211 let fdt = self.as_fdt_slice_mut().as_mut_ptr().cast();
212 let namelen = name.len().try_into().unwrap();
213 let name = name.as_ptr().cast();
214 // SAFETY: Accesses are constrained to the DT totalsize (validated by ctor).
215 let ret = unsafe { libfdt_bindgen::fdt_add_subnode_namelen(fdt, node, name, namelen) };
216
217 fdt_err(ret)
218 }
219}