Skip to main content

openhcl_boot/host_params/dt/
bump_alloc.rs

1// Copyright (c) Microsoft Corporation.
2// Licensed under the MIT License.
3
4//! The boot loader's global bump allocator.
5//!
6//! Allocations are allowed only in a small window for supporting
7//! mesh_protobuf. Any other attempt to allocate results in a panic.
8
9use minimal_rt::bump_alloc::BumpAllocator;
10
11// Only enable the bump allocator when compiling with minimal_rt, as otherwise
12// it will override the global allocator in unit tests which is not what we
13// want.
14#[cfg_attr(minimal_rt, global_allocator)]
15// SAFETY: The boot loader runs on one thread only.
16pub static ALLOCATOR: BumpAllocator = unsafe { BumpAllocator::new() };
17
18/// Run the provided closure with enabling the global bump allocator. This is
19/// only intended to be used for mesh_protobuf decode.
20///
21/// Note that if the global allocator was ever used before, this function will
22/// panic.
23pub fn with_global_alloc<T>(f: impl FnOnce() -> T) -> T {
24    let val = ALLOCATOR.with_alloc(f);
25    let stats = ALLOCATOR.stats();
26    log::info!(
27        "Bump allocator: allocated {} bytes in {} allocations ({} bytes free)",
28        stats.allocated,
29        stats.count,
30        stats.free
31    );
32    val
33}