lehit 0.2.0

Embeddable Lehit language frontend and Cranelift JIT runtime
Documentation
use std::alloc::Layout;

pub const ALLOCATE_SYMBOL: &str = "__lehit_allocate";
pub const DEALLOCATE_SYMBOL: &str = "__lehit_deallocate";

/// Allocator entrypoints shared by every compilation unit of one runtime.
///
/// Allocation and deallocation must be paired and remain callable while any
/// compilation unit created by the runtime is alive.
#[derive(Debug, Clone, Copy)]
pub struct RuntimeAllocator {
    pub(crate) allocate: unsafe extern "C" fn(size: usize, align: usize) -> *mut u8,
    pub(crate) deallocate: unsafe extern "C" fn(pointer: *mut u8, size: usize, align: usize),
}

impl RuntimeAllocator {
    /// Installs host allocator callbacks used by generated code.
    ///
    /// # Safety
    ///
    /// Both callbacks must remain valid for every compilation unit created by
    /// the runtime and must not unwind. `allocate` must return storage valid for
    /// at least `size.max(1)` bytes with the requested non-zero power-of-two
    /// alignment. `deallocate` must accept exactly the pointers/layouts returned
    /// by `allocate`. Returning an unusable pointer can make generated writes
    /// undefined behavior.
    pub const unsafe fn new(
        allocate: unsafe extern "C" fn(usize, usize) -> *mut u8,
        deallocate: unsafe extern "C" fn(*mut u8, usize, usize),
    ) -> Self {
        Self {
            allocate,
            deallocate,
        }
    }
}

impl Default for RuntimeAllocator {
    fn default() -> Self {
        // SAFETY: both callbacks use Rust's global allocator with the exact
        // requested layout and remain callable for the process lifetime.
        unsafe { Self::new(default_allocate, default_deallocate) }
    }
}

unsafe extern "C" fn default_allocate(size: usize, align: usize) -> *mut u8 {
    let Ok(layout) = Layout::from_size_align(size.max(1), align) else {
        return std::ptr::null_mut();
    };
    let pointer = unsafe { std::alloc::alloc(layout) };
    if pointer.is_null() {
        std::alloc::handle_alloc_error(layout);
    }
    pointer
}

unsafe extern "C" fn default_deallocate(pointer: *mut u8, size: usize, align: usize) {
    if pointer.is_null() {
        return;
    }
    let Ok(layout) = Layout::from_size_align(size.max(1), align) else {
        return;
    };
    unsafe { std::alloc::dealloc(pointer, layout) }
}