Pierre-Clément Tosi | fbb5ee2 | 2023-12-21 13:49:59 +0000 | [diff] [blame] | 1 | // 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 Tosi | d83741d | 2024-02-02 10:44:55 +0000 | [diff] [blame] | 16 | //! |
| 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 Tosi | fbb5ee2 | 2023-12-21 13:49:59 +0000 | [diff] [blame] | 20 | |
Pierre-Clément Tosi | d83741d | 2024-02-02 10:44:55 +0000 | [diff] [blame] | 21 | use core::ffi::{c_int, CStr}; |
Pierre-Clément Tosi | eabe1f5 | 2024-01-23 22:47:43 +0000 | [diff] [blame] | 22 | use core::mem; |
Pierre-Clément Tosi | d83741d | 2024-02-02 10:44:55 +0000 | [diff] [blame] | 23 | use core::ptr; |
| 24 | |
Pierre-Clément Tosi | ecd5bbc | 2023-12-21 15:12:45 +0000 | [diff] [blame] | 25 | use crate::{fdt_err, fdt_err_expect_zero, fdt_err_or_option, FdtError, Phandle, Result}; |
Pierre-Clément Tosi | fbb5ee2 | 2023-12-21 13:49:59 +0000 | [diff] [blame] | 26 | |
| 27 | // Function names are the C function names without the `fdt_` prefix. |
| 28 | |
| 29 | /// Safe wrapper around `fdt_create_empty_tree()` (C function). |
| 30 | pub(crate) fn create_empty_tree(fdt: &mut [u8]) -> Result<()> { |
| 31 | let len = fdt.len().try_into().unwrap(); |
| 32 | let fdt = fdt.as_mut_ptr().cast(); |
| 33 | // SAFETY: fdt_create_empty_tree() only write within the specified length, |
| 34 | // and returns error if buffer was insufficient. |
| 35 | // There will be no memory write outside of the given fdt. |
| 36 | let ret = unsafe { libfdt_bindgen::fdt_create_empty_tree(fdt, len) }; |
| 37 | |
| 38 | fdt_err_expect_zero(ret) |
| 39 | } |
| 40 | |
| 41 | /// Safe wrapper around `fdt_check_full()` (C function). |
| 42 | pub(crate) fn check_full(fdt: &[u8]) -> Result<()> { |
| 43 | let len = fdt.len(); |
| 44 | let fdt = fdt.as_ptr().cast(); |
| 45 | // SAFETY: Only performs read accesses within the limits of the slice. If successful, this |
| 46 | // call guarantees to other unsafe calls that the header contains a valid totalsize (w.r.t. |
| 47 | // 'len' i.e. the self.fdt slice) that those C functions can use to perform bounds |
| 48 | // checking. The library doesn't maintain an internal state (such as pointers) between |
| 49 | // calls as it expects the client code to keep track of the objects (DT, nodes, ...). |
| 50 | let ret = unsafe { libfdt_bindgen::fdt_check_full(fdt, len) }; |
| 51 | |
| 52 | fdt_err_expect_zero(ret) |
| 53 | } |
Pierre-Clément Tosi | d83741d | 2024-02-02 10:44:55 +0000 | [diff] [blame] | 54 | |
| 55 | /// Wrapper for the read-only libfdt.h functions. |
| 56 | /// |
| 57 | /// # Safety |
| 58 | /// |
| 59 | /// Implementors must ensure that at any point where a method of this trait is called, the |
| 60 | /// underlying type returns the bytes of a valid device tree (as validated by `check_full`) |
| 61 | /// through its `.as_fdt_slice` method. |
| 62 | pub(crate) unsafe trait Libfdt { |
| 63 | /// Provides an immutable slice containing the device tree. |
| 64 | /// |
| 65 | /// The implementation must ensure that the size of the returned slice and |
| 66 | /// `fdt_header::totalsize` match. |
| 67 | fn as_fdt_slice(&self) -> &[u8]; |
| 68 | |
| 69 | /// Safe wrapper around `fdt_path_offset_namelen()` (C function). |
| 70 | fn path_offset_namelen(&self, path: &[u8]) -> Result<Option<c_int>> { |
| 71 | let fdt = self.as_fdt_slice().as_ptr().cast(); |
| 72 | // *_namelen functions don't include the trailing nul terminator in 'len'. |
| 73 | let len = path.len().try_into().map_err(|_| FdtError::BadPath)?; |
| 74 | let path = path.as_ptr().cast(); |
| 75 | // SAFETY: Accesses are constrained to the DT totalsize (validated by ctor) and the |
| 76 | // function respects the passed number of characters. |
| 77 | let ret = unsafe { libfdt_bindgen::fdt_path_offset_namelen(fdt, path, len) }; |
| 78 | |
| 79 | fdt_err_or_option(ret) |
| 80 | } |
| 81 | |
Pierre-Clément Tosi | ecd5bbc | 2023-12-21 15:12:45 +0000 | [diff] [blame] | 82 | /// Safe wrapper around `fdt_node_offset_by_phandle()` (C function). |
| 83 | fn node_offset_by_phandle(&self, phandle: Phandle) -> Result<Option<c_int>> { |
| 84 | let fdt = self.as_fdt_slice().as_ptr().cast(); |
| 85 | let phandle = phandle.into(); |
| 86 | // SAFETY: Accesses are constrained to the DT totalsize. |
| 87 | let ret = unsafe { libfdt_bindgen::fdt_node_offset_by_phandle(fdt, phandle) }; |
| 88 | |
| 89 | fdt_err_or_option(ret) |
| 90 | } |
| 91 | |
Pierre-Clément Tosi | d83741d | 2024-02-02 10:44:55 +0000 | [diff] [blame] | 92 | /// Safe wrapper around `fdt_node_offset_by_compatible()` (C function). |
| 93 | fn node_offset_by_compatible(&self, prev: c_int, compatible: &CStr) -> Result<Option<c_int>> { |
| 94 | let fdt = self.as_fdt_slice().as_ptr().cast(); |
| 95 | let compatible = compatible.as_ptr(); |
| 96 | // SAFETY: Accesses (read-only) are constrained to the DT totalsize. |
| 97 | let ret = unsafe { libfdt_bindgen::fdt_node_offset_by_compatible(fdt, prev, compatible) }; |
| 98 | |
| 99 | fdt_err_or_option(ret) |
| 100 | } |
| 101 | |
| 102 | /// Safe wrapper around `fdt_next_node()` (C function). |
| 103 | fn next_node(&self, node: c_int, depth: usize) -> Result<Option<(c_int, usize)>> { |
| 104 | let fdt = self.as_fdt_slice().as_ptr().cast(); |
| 105 | let mut depth = depth.try_into().unwrap(); |
| 106 | // SAFETY: Accesses (read-only) are constrained to the DT totalsize. |
| 107 | let ret = unsafe { libfdt_bindgen::fdt_next_node(fdt, node, &mut depth) }; |
| 108 | |
| 109 | match fdt_err_or_option(ret)? { |
| 110 | Some(offset) if depth >= 0 => { |
| 111 | let depth = depth.try_into().unwrap(); |
| 112 | Ok(Some((offset, depth))) |
| 113 | } |
| 114 | _ => Ok(None), |
| 115 | } |
| 116 | } |
| 117 | |
| 118 | /// Safe wrapper around `fdt_parent_offset()` (C function). |
| 119 | /// |
| 120 | /// Note that this function returns a `Err` when called on a root. |
| 121 | fn parent_offset(&self, node: c_int) -> Result<c_int> { |
| 122 | let fdt = self.as_fdt_slice().as_ptr().cast(); |
| 123 | // SAFETY: Accesses (read-only) are constrained to the DT totalsize. |
| 124 | let ret = unsafe { libfdt_bindgen::fdt_parent_offset(fdt, node) }; |
| 125 | |
| 126 | fdt_err(ret) |
| 127 | } |
| 128 | |
| 129 | /// Safe wrapper around `fdt_supernode_atdepth_offset()` (C function). |
| 130 | /// |
| 131 | /// Note that this function returns a `Err` when called on a node at a depth shallower than |
| 132 | /// the provided `depth`. |
| 133 | fn supernode_atdepth_offset(&self, node: c_int, depth: usize) -> Result<c_int> { |
| 134 | let fdt = self.as_fdt_slice().as_ptr().cast(); |
| 135 | let depth = depth.try_into().unwrap(); |
| 136 | let nodedepth = ptr::null_mut(); |
| 137 | let ret = |
| 138 | // SAFETY: Accesses (read-only) are constrained to the DT totalsize. |
| 139 | unsafe { libfdt_bindgen::fdt_supernode_atdepth_offset(fdt, node, depth, nodedepth) }; |
| 140 | |
| 141 | fdt_err(ret) |
| 142 | } |
| 143 | |
| 144 | /// Safe wrapper around `fdt_subnode_offset_namelen()` (C function). |
| 145 | fn subnode_offset_namelen(&self, parent: c_int, name: &[u8]) -> Result<Option<c_int>> { |
| 146 | let fdt = self.as_fdt_slice().as_ptr().cast(); |
| 147 | let namelen = name.len().try_into().unwrap(); |
| 148 | let name = name.as_ptr().cast(); |
| 149 | // SAFETY: Accesses are constrained to the DT totalsize (validated by ctor). |
| 150 | let ret = unsafe { libfdt_bindgen::fdt_subnode_offset_namelen(fdt, parent, name, namelen) }; |
| 151 | |
| 152 | fdt_err_or_option(ret) |
| 153 | } |
| 154 | /// Safe wrapper around `fdt_first_subnode()` (C function). |
| 155 | fn first_subnode(&self, node: c_int) -> Result<Option<c_int>> { |
| 156 | let fdt = self.as_fdt_slice().as_ptr().cast(); |
| 157 | // SAFETY: Accesses (read-only) are constrained to the DT totalsize. |
| 158 | let ret = unsafe { libfdt_bindgen::fdt_first_subnode(fdt, node) }; |
| 159 | |
| 160 | fdt_err_or_option(ret) |
| 161 | } |
| 162 | |
| 163 | /// Safe wrapper around `fdt_next_subnode()` (C function). |
| 164 | fn next_subnode(&self, node: c_int) -> Result<Option<c_int>> { |
| 165 | let fdt = self.as_fdt_slice().as_ptr().cast(); |
| 166 | // SAFETY: Accesses (read-only) are constrained to the DT totalsize. |
| 167 | let ret = unsafe { libfdt_bindgen::fdt_next_subnode(fdt, node) }; |
| 168 | |
| 169 | fdt_err_or_option(ret) |
| 170 | } |
| 171 | |
| 172 | /// Safe wrapper around `fdt_address_cells()` (C function). |
| 173 | fn address_cells(&self, node: c_int) -> Result<usize> { |
| 174 | let fdt = self.as_fdt_slice().as_ptr().cast(); |
| 175 | // SAFETY: Accesses are constrained to the DT totalsize (validated by ctor). |
| 176 | let ret = unsafe { libfdt_bindgen::fdt_address_cells(fdt, node) }; |
| 177 | |
| 178 | Ok(fdt_err(ret)?.try_into().unwrap()) |
| 179 | } |
| 180 | |
| 181 | /// Safe wrapper around `fdt_size_cells()` (C function). |
| 182 | fn size_cells(&self, node: c_int) -> Result<usize> { |
| 183 | let fdt = self.as_fdt_slice().as_ptr().cast(); |
| 184 | // SAFETY: Accesses are constrained to the DT totalsize (validated by ctor). |
| 185 | let ret = unsafe { libfdt_bindgen::fdt_size_cells(fdt, node) }; |
| 186 | |
| 187 | Ok(fdt_err(ret)?.try_into().unwrap()) |
| 188 | } |
Pierre-Clément Tosi | ecd5bbc | 2023-12-21 15:12:45 +0000 | [diff] [blame] | 189 | |
Pierre-Clément Tosi | 60282ae | 2023-12-21 16:00:02 +0000 | [diff] [blame] | 190 | /// Safe wrapper around `fdt_get_name()` (C function). |
| 191 | fn get_name(&self, node: c_int) -> Result<&[u8]> { |
| 192 | let fdt = self.as_fdt_slice().as_ptr().cast(); |
| 193 | let mut len = 0; |
| 194 | // SAFETY: Accesses are constrained to the DT totalsize (validated by ctor). On success, the |
| 195 | // function returns valid null terminating string and otherwise returned values are dropped. |
| 196 | let name = unsafe { libfdt_bindgen::fdt_get_name(fdt, node, &mut len) }; |
| 197 | let len = usize::try_from(fdt_err(len)?).unwrap().checked_add(1).unwrap(); |
| 198 | |
| 199 | get_slice_at_ptr(self.as_fdt_slice(), name.cast(), len).ok_or(FdtError::Internal) |
| 200 | } |
| 201 | |
Pierre-Clément Tosi | 410e46a | 2023-12-24 11:33:11 +0000 | [diff] [blame] | 202 | /// Safe wrapper around `fdt_getprop_namelen()` (C function). |
| 203 | fn getprop_namelen(&self, node: c_int, name: &[u8]) -> Result<Option<&[u8]>> { |
| 204 | let fdt = self.as_fdt_slice().as_ptr().cast(); |
| 205 | let namelen = name.len().try_into().map_err(|_| FdtError::BadPath)?; |
| 206 | let name = name.as_ptr().cast(); |
| 207 | let mut len = 0; |
| 208 | let prop = |
| 209 | // SAFETY: Accesses are constrained to the DT totalsize (validated by ctor) and the |
| 210 | // function respects the passed number of characters. |
| 211 | unsafe { libfdt_bindgen::fdt_getprop_namelen(fdt, node, name, namelen, &mut len) }; |
| 212 | |
| 213 | if let Some(len) = fdt_err_or_option(len)? { |
| 214 | let len = usize::try_from(len).unwrap(); |
| 215 | 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 Tosi | eabe1f5 | 2024-01-23 22:47:43 +0000 | [diff] [blame] | 229 | |
| 230 | let data_len = fdt_err(len)?.try_into().unwrap(); |
| 231 | // 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 Tosi | 410e46a | 2023-12-24 11:33:11 +0000 | [diff] [blame] | 237 | } |
| 238 | |
Pierre-Clément Tosi | eabe1f5 | 2024-01-23 22:47:43 +0000 | [diff] [blame] | 239 | // 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 Tosi | 410e46a | 2023-12-24 11:33:11 +0000 | [diff] [blame] | 247 | } |
| 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 | |
| 255 | fdt_err_or_option(ret) |
| 256 | } |
| 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 | |
| 264 | fdt_err_or_option(ret) |
| 265 | } |
| 266 | |
Pierre-Clément Tosi | ecd5bbc | 2023-12-21 15:12:45 +0000 | [diff] [blame] | 267 | /// 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 | |
| 274 | fdt_err_expect_zero(ret)?; |
| 275 | |
| 276 | phandle.try_into() |
| 277 | } |
Pierre-Clément Tosi | 60282ae | 2023-12-21 16:00:02 +0000 | [diff] [blame] | 278 | |
| 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 Tosi | a4eaba9 | 2024-01-23 21:24:37 +0000 | [diff] [blame] | 284 | let bytes = |
| 285 | get_slice_from_ptr(self.as_fdt_slice(), ptr.cast()).ok_or(FdtError::Internal)?; |
Pierre-Clément Tosi | 60282ae | 2023-12-21 16:00:02 +0000 | [diff] [blame] | 286 | |
Pierre-Clément Tosi | a4eaba9 | 2024-01-23 21:24:37 +0000 | [diff] [blame] | 287 | CStr::from_bytes_until_nul(bytes).map_err(|_| FdtError::Internal) |
Pierre-Clément Tosi | 60282ae | 2023-12-21 16:00:02 +0000 | [diff] [blame] | 288 | } |
Pierre-Clément Tosi | e21ed3f | 2024-01-23 18:16:13 +0000 | [diff] [blame^] | 289 | |
| 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 Tosi | d83741d | 2024-02-02 10:44:55 +0000 | [diff] [blame] | 296 | } |
| 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. |
| 311 | pub(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 | |
| 324 | fdt_err_expect_zero(ret) |
| 325 | } |
| 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 | |
| 335 | fdt_err(ret) |
| 336 | } |
Pierre-Clément Tosi | 843845d | 2024-01-23 23:35:01 +0000 | [diff] [blame] | 337 | |
Pierre-Clément Tosi | 410e46a | 2023-12-24 11:33:11 +0000 | [diff] [blame] | 338 | /// 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 | |
| 348 | fdt_err_expect_zero(ret) |
| 349 | } |
| 350 | |
Pierre-Clément Tosi | 843845d | 2024-01-23 23:35:01 +0000 | [diff] [blame] | 351 | /// 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 | |
| 361 | fdt_err_expect_zero(ret)?; |
| 362 | |
| 363 | get_mut_slice_at_ptr(self.as_fdt_slice_mut(), data.cast(), size).ok_or(FdtError::Internal) |
| 364 | } |
Pierre-Clément Tosi | 410e46a | 2023-12-24 11:33:11 +0000 | [diff] [blame] | 365 | |
| 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 | |
| 376 | fdt_err_expect_zero(ret) |
| 377 | } |
| 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 | |
| 388 | fdt_err_expect_zero(ret) |
| 389 | } |
| 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 | |
| 407 | fdt_err_expect_zero(ret) |
| 408 | } |
| 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 | |
| 420 | fdt_err_expect_zero(ret) |
| 421 | } |
| 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 | |
| 431 | fdt_err_expect_zero(ret) |
| 432 | } |
Pierre-Clément Tosi | e21ed3f | 2024-01-23 18:16:13 +0000 | [diff] [blame^] | 433 | |
| 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 | |
| 454 | fdt_err_expect_zero(ret) |
| 455 | } |
| 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 | |
| 473 | fdt_err_expect_zero(ret) |
| 474 | } |
Pierre-Clément Tosi | d83741d | 2024-02-02 10:44:55 +0000 | [diff] [blame] | 475 | } |
Pierre-Clément Tosi | 60282ae | 2023-12-21 16:00:02 +0000 | [diff] [blame] | 476 | |
| 477 | pub(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 Tosi | 843845d | 2024-01-23 23:35:01 +0000 | [diff] [blame] | 483 | fn 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 Tosi | a4eaba9 | 2024-01-23 21:24:37 +0000 | [diff] [blame] | 489 | fn 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 Tosi | 60282ae | 2023-12-21 16:00:02 +0000 | [diff] [blame] | 493 | fn 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 Tosi | eabe1f5 | 2024-01-23 22:47:43 +0000 | [diff] [blame] | 500 | |
Pierre-Clément Tosi | e21ed3f | 2024-01-23 18:16:13 +0000 | [diff] [blame^] | 501 | fn 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 | |
| 511 | fdt_err_expect_zero(ret) |
| 512 | } |
| 513 | |
Pierre-Clément Tosi | eabe1f5 | 2024-01-23 22:47:43 +0000 | [diff] [blame] | 514 | // TODO(stable_feature(pointer_is_aligned)): p.is_aligned() |
| 515 | fn is_aligned<T>(p: *const T) -> bool { |
| 516 | (p as usize) % mem::align_of::<T>() == 0 |
| 517 | } |