blob: bd9ae1ea0180a4e22caf2482f249832dd7a5db99 [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.
16
17use crate::{fdt_err_expect_zero, Result};
18
19// Function names are the C function names without the `fdt_` prefix.
20
21/// Safe wrapper around `fdt_create_empty_tree()` (C function).
22pub(crate) fn create_empty_tree(fdt: &mut [u8]) -> Result<()> {
23 let len = fdt.len().try_into().unwrap();
24 let fdt = fdt.as_mut_ptr().cast();
25 // SAFETY: fdt_create_empty_tree() only write within the specified length,
26 // and returns error if buffer was insufficient.
27 // There will be no memory write outside of the given fdt.
28 let ret = unsafe { libfdt_bindgen::fdt_create_empty_tree(fdt, len) };
29
30 fdt_err_expect_zero(ret)
31}
32
33/// Safe wrapper around `fdt_check_full()` (C function).
34pub(crate) fn check_full(fdt: &[u8]) -> Result<()> {
35 let len = fdt.len();
36 let fdt = fdt.as_ptr().cast();
37 // SAFETY: Only performs read accesses within the limits of the slice. If successful, this
38 // call guarantees to other unsafe calls that the header contains a valid totalsize (w.r.t.
39 // 'len' i.e. the self.fdt slice) that those C functions can use to perform bounds
40 // checking. The library doesn't maintain an internal state (such as pointers) between
41 // calls as it expects the client code to keep track of the objects (DT, nodes, ...).
42 let ret = unsafe { libfdt_bindgen::fdt_check_full(fdt, len) };
43
44 fdt_err_expect_zero(ret)
45}