blob: 40e264a12f406616d2c3162f42fafdd659c523a4 [file]
// Copyright 2026 The Fuchsia Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
//! Allocator layout, error, and link-time C-ABI heap primitives (`vx_alloc::alloc`).
//!
//! Connects to the runtime allocator strictly via the two link-time C-ABI
//! symbols `__vx_alloc` and `__vx_dealloc` (zero `vx_zx` dependency, zero
//! `AllocHandle` fields, zero mutable globals).
use core::fmt;
use core::mem::{align_of, size_of};
use core::ptr::{self, NonNull};
/// Maximum single allocation size in bytes (`isize::MAX`), matching Rust's
/// pointer-offset soundness bound so `ptr.add(n)` never wraps `isize`.
pub const MAX_ALLOC_BYTES: usize = isize::MAX as usize;
unsafe extern "C" {
/// Allocate `size` (> 0) bytes aligned to power-of-2 `align` from the
/// active fiber-local / standalone runtime heap.
///
/// Returns null on out-of-memory, quota exhaustion, or invalid arguments.
pub fn __vx_alloc(size: usize, align: usize) -> *mut u8;
/// Deallocate a previous allocation `(ptr, size, align)` returned by
/// [`__vx_alloc`].
pub fn __vx_dealloc(ptr: *mut u8, size: usize, align: usize);
}
/// Error returned when a heap allocation or layout/capacity computation fails.
///
/// Zero-sized so `Result<NonNull<u8>, AllocError>` and `Result<Box<T>, AllocError>`
/// are 8 bytes and return directly in `x0` with zero `SRET(x8)`.
#[derive(Copy, Clone, PartialEq, Eq)]
pub struct AllocError;
const _: () = assert!(size_of::<AllocError>() == 0);
const _: () = assert!(size_of::<Result<NonNull<u8>, AllocError>>() == 8);
// Implemented manually with `#[inline(always)]` rather than `#[derive(Debug)]`
// so compiled AArch64 objects never emit out-of-line `core::fmt` calls.
impl fmt::Debug for AllocError {
#[inline(always)]
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str("AllocError")
}
}
impl fmt::Display for AllocError {
#[inline(always)]
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str("memory allocation failed")
}
}
/// Return `true` iff `align` is a non-zero power of two and `size` fits within
/// [`MAX_ALLOC_BYTES`] when rounded up to `align`.
#[inline(always)]
pub const fn is_valid_layout(size: usize, align: usize) -> bool {
if align == 0 || (align & (align - 1)) != 0 {
return false;
}
size <= MAX_ALLOC_BYTES - (align - 1)
}
/// Construct a non-null, `align`-aligned dangling pointer without allocating.
///
/// Falls back to alignment `1` if `align == 0`.
#[inline(always)]
pub(crate) const fn dangling_for_align(align: usize) -> NonNull<u8> {
let addr = if align == 0 { 1 } else { align };
// SAFETY: `addr >= 1`, so `without_provenance_mut(addr)` is non-null.
unsafe { NonNull::new_unchecked(ptr::without_provenance_mut(addr)) }
}
/// Memory allocation layout `(size, align)` with power-of-2 alignment and
/// overflow-checked size bounds (`size <= isize::MAX - (align - 1)`).
#[repr(C)]
#[derive(Copy, Clone, PartialEq, Eq)]
pub struct Layout {
size: usize,
align: usize,
}
const _: () = assert!(size_of::<Layout>() == 16);
const _: () = assert!(align_of::<Layout>() == 8);
impl fmt::Debug for Layout {
#[inline(always)]
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("Layout").field("size", &self.size).field("align", &self.align).finish()
}
}
impl Layout {
/// Construct a [`Layout`] from `(size, align)`, returning `Err(AllocError)`
/// if `align` is not a power of two or `size` would overflow `isize::MAX`
/// when rounded up to `align`.
#[inline(always)]
pub const fn from_size_align(size: usize, align: usize) -> Result<Self, AllocError> {
if !is_valid_layout(size, align) {
return Err(AllocError);
}
Ok(Self { size, align })
}
/// Construct the [`Layout`] for a single value of type `T`.
#[inline(always)]
pub const fn new<T>() -> Self {
Self { size: size_of::<T>(), align: align_of::<T>() }
}
/// Construct the [`Layout`] for a contiguous array of `n` values of type `T`,
/// returning `Err(AllocError)` on arithmetic or `isize::MAX` overflow.
#[inline(always)]
pub const fn array<T>(n: usize) -> Result<Self, AllocError> {
let Some(total) = n.checked_mul(size_of::<T>()) else {
return Err(AllocError);
};
Self::from_size_align(total, align_of::<T>())
}
/// Return the minimum size in bytes for this layout.
#[inline(always)]
pub const fn size(&self) -> usize {
self.size
}
/// Return the power-of-2 alignment in bytes for this layout.
#[inline(always)]
pub const fn align(&self) -> usize {
self.align
}
/// Return a non-null dangling pointer aligned to `self.align()`.
#[inline(always)]
pub const fn dangling(&self) -> NonNull<u8> {
dangling_for_align(self.align)
}
}
/// Allocate `size` (> 0) bytes aligned to power-of-2 `align` via [`__vx_alloc`].
///
/// Rejects `size == 0`, invalid alignments, or sizes exceeding
/// `MAX_ALLOC_BYTES - (align - 1)` without calling [`__vx_alloc`].
///
/// # Safety
///
/// The active runtime allocator backing [`__vx_alloc`] must be initialized (or
/// safely return null when unavailable).
#[curry::verified]
pub unsafe fn raw_alloc(size: usize, align: usize) -> Result<NonNull<u8>, AllocError> {
if size == 0 || !is_valid_layout(size, align) {
return Err(AllocError);
}
// SAFETY: `size > 0` and `(size, align)` satisfies `is_valid_layout`.
let ptr = unsafe { __vx_alloc(size, align) };
match NonNull::new(ptr) {
Some(nn) => Ok(nn),
None => Err(AllocError),
}
}
/// Allocate `size` (> 0) zero-initialized bytes aligned to power-of-2 `align`.
///
/// # Safety
///
/// Same preconditions as [`raw_alloc`].
#[curry::verified]
pub unsafe fn raw_alloc_zeroed(size: usize, align: usize) -> Result<NonNull<u8>, AllocError> {
// SAFETY: Forwarded from caller.
let nn = unsafe { raw_alloc(size, align)? };
// SAFETY: `nn` is a freshly allocated, unaliased buffer valid for writes of `size` bytes.
unsafe {
ptr::write_bytes(nn.as_ptr(), 0, size);
}
Ok(nn)
}
/// Deallocate a non-null allocation `(ptr, size, align)` via [`__vx_dealloc`].
///
/// No-op if `ptr` is null, `size == 0`, or `(size, align)` is invalid.
///
/// # Safety
///
/// When `ptr` is non-null and `size > 0`, `(ptr, size, align)` must match a
/// live allocation previously returned by [`raw_alloc`] / [`__vx_alloc`] and
/// not yet deallocated.
#[curry::verified]
pub unsafe fn raw_dealloc(ptr: *mut u8, size: usize, align: usize) {
if ptr.is_null() || size == 0 || !is_valid_layout(size, align) {
return;
}
// SAFETY: Caller guarantees `(ptr, size, align)` matches a live allocation.
unsafe {
__vx_dealloc(ptr, size, align);
}
}
/// Allocate uninitialized memory for `layout` (`layout.size() > 0`).
///
/// # Safety
///
/// Same preconditions as [`raw_alloc`].
#[inline(always)]
pub unsafe fn alloc(layout: Layout) -> Result<NonNull<u8>, AllocError> {
// SAFETY: Forwarded from caller.
unsafe { raw_alloc(layout.size(), layout.align()) }
}
/// Allocate zero-initialized memory for `layout` (`layout.size() > 0`).
///
/// # Safety
///
/// Same preconditions as [`raw_alloc_zeroed`].
#[inline(always)]
pub unsafe fn alloc_zeroed(layout: Layout) -> Result<NonNull<u8>, AllocError> {
// SAFETY: Forwarded from caller.
unsafe { raw_alloc_zeroed(layout.size(), layout.align()) }
}
/// Deallocate `ptr` previously allocated with `layout`.
///
/// # Safety
///
/// `ptr` must be a live allocation previously obtained with the exact same
/// `layout`.
#[inline(always)]
pub unsafe fn dealloc(ptr: NonNull<u8>, layout: Layout) {
// SAFETY: Forwarded from caller.
unsafe { raw_dealloc(ptr.as_ptr(), layout.size(), layout.align()) }
}