allocator.rs

cdk-rsx/crates/cdk-rsx-engine-nyxus/src/allocator.rs

allocator.rs461 lines← SDK documentation
1use core::{alloc::Layout, any::TypeId, ops::Range, ptr::NonNull};2use std::alloc::{AllocError, Allocator, AllocatorClone, StaticAllocator};34// This is the same pinned allocation algorithm used by the platform. Its5// concrete private types are an explicit root of the separate ABI certificate.6use cdk_rsx_platform::transient::{self as heap, HintedHeap as Heap, PageSource};78pub const PAGE_BYTES: usize = 65_536;9pub const MARK_OFFSET: usize = 64;10pub const HEAP_OFFSET: usize = 256;11pub const HEAP_END: usize = 4096;12pub const ALLOCATOR_FORMAT: u64 = 0x33414e4552415253;13/// Source-qualified class/page-bin algorithms, separately from layout facts.14/// The build-time ABI recipe hashes this source; it is not persisted data.15#[doc(hidden)]16pub const ALLOCATOR_RECIPE_SOURCE: &str = heap::RECIPE_SOURCE;17const _: () = assert!(size_of::<Heap>() <= HEAP_END - HEAP_OFFSET);1819/// Compiler-private allocator representation root for the build-time ABI guard.20/// Certification must include its pointees, class algorithms and page provider.21#[doc(hidden)]22pub const fn allocator_layout_types() -> [TypeId; 3] {23    heap::physical_types()24}2526#[derive(Clone, Copy, Debug, PartialEq, Eq)]27pub enum ArenaError {28    Uninitialized,29    AlreadyInitialized,30    FormatMismatch,31    Provider,32}33impl core::fmt::Display for ArenaError {34    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {35        write!(f, "{self:?}")36    }37}38impl std::error::Error for ArenaError {}3940/// Nyxus is the process-global persistent-heap allocation authority. Moving, dropping and41/// cloning this ZST do not change or invalidate any allocation.42#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]43pub struct Nyxus;4445/// Initialize a fresh Nyxus Heap. A repeated call in this opening is inert;46/// a saved allocator requires guarded `reopen` and is never reset here.47/// Native builds use one independent System-backed Heap for the process.48pub fn initialize() -> Result<(), ArenaError> {49    backend::initialize()50}5152/// Reopen the same Nyxus allocation authority without changing its Heap.53/// Native support retains the process image and does not simulate Wasm startup.54///55/// # Safety56/// The generated early/raw guard must first accept the complete compiled57/// allocator/provider ABI and quiescent handoff. No other retained provider58/// capability may exist. An identical magic, size or compiler hash alone is not59/// a sufficient certificate for Heap/private-node interpretation.60pub unsafe fn reopen() -> Result<(), ArenaError> {61    // SAFETY: forwards the guarded-format and sole-authority obligations.62    unsafe { backend::reopen() }63}6465/// Whether all bytes belong to the retained page domain in this opening.66/// This is not an allocation identity, liveness proof or permission to access67/// bytes. Module generations and scoped typed loans supply those proofs.68pub fn contains(range: Range<usize>) -> bool {69    backend::contains(range)70}7172fn fatal() -> ! {73    #[cfg(target_arch = "wasm32")]74    core::arch::wasm32::unreachable();75    #[cfg(target_arch = "wasm64")]76    core::arch::wasm64::unreachable();77    #[cfg(not(target_family = "wasm"))]78    std::process::abort()79}8081fn slice(pointer: NonNull<u8>, size: usize) -> NonNull<[u8]> {82    NonNull::slice_from_raw_parts(pointer, size)83}8485// SAFETY: the sole Heap returns disjoint aligned live storage. It cannot be86// reset through safe APIs. Every method accepts the actual allocation Layout;87// resizing preserves old bytes and leaves the old allocation live on failure.88unsafe impl Allocator for Nyxus {89    fn allocate(&self, layout: Layout) -> Result<NonNull<[u8]>, AllocError> {90        if layout.size() == 0 {91            return Ok(slice(layout.dangling_ptr(), 0));92        }93        backend::allocate(layout).map(|pointer| slice(pointer, layout.size()))94    }95    unsafe fn deallocate(&self, pointer: NonNull<u8>, layout: Layout) {96        if layout.size() != 0 {97            // SAFETY: caller supplies a currently live allocation and its layout.98            unsafe { backend::deallocate(pointer, layout) }99        }100    }101    unsafe fn grow(102        &self,103        pointer: NonNull<u8>,104        old: Layout,105        new: Layout,106    ) -> Result<NonNull<[u8]>, AllocError> {107        // SAFETY: caller supplies live ownership and new.size>=old.size.108        unsafe { self.resize(pointer, old, new, false) }109    }110    unsafe fn grow_zeroed(111        &self,112        pointer: NonNull<u8>,113        old: Layout,114        new: Layout,115    ) -> Result<NonNull<[u8]>, AllocError> {116        // SAFETY: same contract as grow; resize zeroes only the added extent.117        unsafe { self.resize(pointer, old, new, true) }118    }119    unsafe fn shrink(120        &self,121        pointer: NonNull<u8>,122        old: Layout,123        new: Layout,124    ) -> Result<NonNull<[u8]>, AllocError> {125        // SAFETY: caller supplies live ownership and new.size<=old.size.126        unsafe { self.resize(pointer, old, new, false) }127    }128}129impl Nyxus {130    unsafe fn resize(131        self,132        pointer: NonNull<u8>,133        old: Layout,134        new: Layout,135        zero_tail: bool,136    ) -> Result<NonNull<[u8]>, AllocError> {137        if old.size() == 0 {138            return if zero_tail {139                self.allocate_zeroed(new)140            } else {141                self.allocate(new)142            };143        }144        if new.size() == 0 {145            // SAFETY: caller transfers this live allocation to its empty result.146            unsafe { self.deallocate(pointer, old) };147            return Ok(slice(new.dangling_ptr(), 0));148        }149        // The original small slab band survives alignment-changing resize too.150        // Direct runs are unbanded; current placement context never governs free.151        let next = unsafe { backend::resize(pointer, old, new)? };152        if zero_tail && new.size() > old.size() {153            // SAFETY: added bytes belong to the new live extent. Never clear154            // the preserved prefix, including on an in-place class resize.155            unsafe {156                next.as_ptr()157                    .add(old.size())158                    .write_bytes(0, new.size() - old.size());159            }160        }161        Ok(slice(next, new.size()))162    }163}164// SAFETY: all copies/clones name the same permanent authority and never unwind.165unsafe impl AllocatorClone for Nyxus {}166// SAFETY: safe APIs never reset/release live allocations; dropping a ZST is inert.167unsafe impl StaticAllocator for Nyxus {}168169#[cfg(not(target_family = "wasm"))]170mod backend {171    use super::*;172    use core::{173        cell::UnsafeCell,174        sync::atomic::{AtomicBool, Ordering},175    };176    use std::{alloc::System, collections::BTreeMap};177    struct State {178        heap: Heap,179        runs: BTreeMap<usize, Layout, System>,180    }181    struct Locked {182        busy: AtomicBool,183        value: UnsafeCell<State>,184    }185    // SAFETY: process-global lock serializes every Heap/page-bookkeeping loan.186    // All run pointers name pinned System allocations and may cross threads.187    unsafe impl Sync for Locked {}188    static STATE: Locked = Locked {189        busy: AtomicBool::new(false),190        value: UnsafeCell::new(State {191            heap: Heap::empty(),192            runs: BTreeMap::new_in(System),193        }),194    };195    fn with<R>(f: impl FnOnce(&mut State) -> R) -> R {196        while STATE197            .busy198            .compare_exchange_weak(false, true, Ordering::Acquire, Ordering::Relaxed)199            .is_err()200        {201            core::hint::spin_loop();202        }203        struct Unlock;204        impl Drop for Unlock {205            fn drop(&mut self) {206                STATE.busy.store(false, Ordering::Release);207            }208        }209        let _unlock = Unlock;210        // SAFETY: only this guard can access the process-global allocator state.211        f(unsafe { &mut *STATE.value.get() })212    }213    struct Pages<'a>(&'a mut BTreeMap<usize, Layout, System>);214    // SAFETY: System returns pinned disjoint aligned storage; this list records215    // exact whole-page ownership. Its own nodes use System, never Global.216    unsafe impl PageSource for Pages<'_> {217        unsafe fn allocate_pages(&mut self, count: usize, alignment: usize) -> Option<NonNull<u8>> {218            let layout = Layout::from_size_align(219                count.checked_mul(PAGE_BYTES)?,220                alignment.checked_mul(PAGE_BYTES)?,221            )222            .ok()?;223            let pointer = System.allocate(layout).ok()?.cast::<u8>();224            self.0.insert(pointer.addr().get(), layout);225            Some(pointer)226        }227        unsafe fn release_pages(&mut self, pointer: NonNull<u8>, count: usize) {228            let Some(layout) = self.0.remove(&pointer.addr().get()) else {229                fatal()230            };231            if layout.size() / PAGE_BYTES != count {232                fatal();233            }234            // SAFETY: exact live run/layout recorded on successful allocation.235            unsafe {236                System.deallocate(pointer, layout);237            }238        }239    }240    pub(super) fn initialize() -> Result<(), ArenaError> {241        Ok(())242    }243    pub(super) unsafe fn reopen() -> Result<(), ArenaError> {244        Ok(())245    }246    pub(super) fn allocate(layout: Layout) -> Result<NonNull<u8>, AllocError> {247        with(|s| {248            NonNull::new(unsafe {249                s.heap.allocate(250                    &mut Pages(&mut s.runs),251                    layout,252                    cdk_rsx_platform::allocation::allocation_priority(),253                )254            })255            .ok_or(AllocError)256        })257    }258    pub(super) unsafe fn deallocate(pointer: NonNull<u8>, layout: Layout) {259        with(|s| unsafe {260            s.heap261                .release(&mut Pages(&mut s.runs), pointer.as_ptr(), layout)262        });263    }264    pub(super) unsafe fn resize(265        pointer: NonNull<u8>,266        old: Layout,267        new: Layout,268    ) -> Result<NonNull<u8>, AllocError> {269        with(|s| {270            NonNull::new(unsafe {271                s.heap272                    .resize_layout(&mut Pages(&mut s.runs), pointer.as_ptr(), old, new)273            })274            .ok_or(AllocError)275        })276    }277    pub(super) fn contains(range: Range<usize>) -> bool {278        if range.start > range.end {279            return false;280        }281        if range.is_empty() {282            return true;283        }284        with(|s| {285            let mut through = range.start;286            for (&base, layout) in s.runs.range(..range.end) {287                if base > through {288                    return false;289                }290                through = through.max(base + layout.size());291                if through >= range.end {292                    return true;293                }294            }295            false296        })297    }298}299300#[cfg(target_family = "wasm")]301mod backend {302    use super::*;303    use cdk_rsx_platform::{CONTROL_BASE, RetainedMemory, profile::BOOTSTRAP_BASE};304    use cdk_rsx_platform::{Memory, RetainedBounds};305    use core::{306        cell::{Cell, UnsafeCell},307        mem::MaybeUninit,308    };309    const MARK: usize = BOOTSTRAP_BASE + MARK_OFFSET;310    const HEAP: usize = BOOTSTRAP_BASE + HEAP_OFFSET;311    const _: () = {312        assert!(HEAP.is_multiple_of(align_of::<Heap>()));313        assert!(MARK.is_multiple_of(align_of::<u64>()));314    };315    struct Provider {316        ready: Cell<bool>,317        busy: Cell<bool>,318        memory: UnsafeCell<MaybeUninit<RetainedMemory>>,319    }320    // SAFETY: the IC execution is single-threaded. The busy guard prevents any321    // allocator reentry while an exclusive Heap/provider loan is held.322    unsafe impl Sync for Provider {}323    static PROVIDER: Provider = Provider {324        ready: Cell::new(false),325        busy: Cell::new(false),326        memory: UnsafeCell::new(MaybeUninit::uninit()),327    };328    pub(super) fn initialize() -> Result<(), ArenaError> {329        if PROVIDER.ready.get() {330            return Ok(());331        }332        // SAFETY: the checked profile pins this protected bootstrap window.333        let mark = unsafe { (MARK as *const u64).read() };334        if mark != 0 {335            return Err(ArenaError::AlreadyInitialized);336        }337        // SAFETY: no capability exists in this opening and the allocator marker338        // is fresh. Provider installation rejects a competing Store authority.339        let memory = unsafe { RetainedMemory::initialize() }.map_err(|_| ArenaError::Provider)?;340        unsafe {341            (HEAP as *mut Heap).write(Heap::empty());342            (MARK as *mut u64).write(ALLOCATOR_FORMAT);343            ((MARK + 8) as *mut u64).write(!ALLOCATOR_FORMAT);344            (*PROVIDER.memory.get()).write(memory);345        }346        PROVIDER.ready.set(true);347        Ok(())348    }349    pub(super) unsafe fn reopen() -> Result<(), ArenaError> {350        if PROVIDER.ready.get() {351            return Ok(());352        }353        let (mark, complement) = unsafe {354            (355                (MARK as *const u64).read(),356                ((MARK + 8) as *const u64).read(),357            )358        };359        if mark == 0 {360            return Err(ArenaError::Uninitialized);361        }362        if mark != ALLOCATOR_FORMAT || complement != !mark {363            return Err(ArenaError::FormatMismatch);364        }365        // SAFETY: the caller has certified allocator/provider ABI and the raw366        // quiescent handoff before any private pointer/Heap interpretation.367        let memory = unsafe { RetainedMemory::reopen() }.map_err(|_| ArenaError::Provider)?;368        unsafe {369            (*PROVIDER.memory.get()).write(memory);370        }371        PROVIDER.ready.set(true);372        Ok(())373    }374    struct Pages;375    // SAFETY: the sole RetainedMemory capability claims disjoint pinned Store376    // runs. They exclude runtime pages and all protected controls/statics.377    unsafe impl PageSource for Pages {378        unsafe fn allocate_pages(&mut self, count: usize, alignment: usize) -> Option<NonNull<u8>> {379            let bytes = count.checked_mul(PAGE_BYTES)? as u64;380            let align = alignment.checked_mul(PAGE_BYTES)? as u64;381            let memory = unsafe { (*PROVIDER.memory.get()).assume_init_mut() };382            let offset = memory.allocate_retained_extent(bytes, align).ok()?;383            NonNull::new((CONTROL_BASE + offset as usize) as *mut u8)384        }385        unsafe fn release_pages(&mut self, pointer: NonNull<u8>, count: usize) {386            let memory = unsafe { (*PROVIDER.memory.get()).assume_init_mut() };387            let Some(offset) = pointer.addr().get().checked_sub(CONTROL_BASE) else {388                fatal()389            };390            let Some(bytes) = count.checked_mul(PAGE_BYTES) else {391                fatal()392            };393            if memory394                .release_retained_extent(offset as u64, bytes as u64)395                .is_err()396            {397                fatal();398            }399        }400    }401    fn with<R>(f: impl FnOnce(&mut Heap, &mut Pages) -> R) -> Option<R> {402        if !PROVIDER.ready.get() {403            return None;404        }405        if PROVIDER.busy.replace(true) {406            fatal();407        }408        struct End;409        impl Drop for End {410            fn drop(&mut self) {411                PROVIDER.busy.set(false);412            }413        }414        let _end = End;415        // SAFETY: protected Heap is live under the admitted opening, and this416        // non-reentrant synchronous loan excludes all other allocator access.417        Some(f(unsafe { &mut *(HEAP as *mut Heap) }, &mut Pages))418    }419    pub(super) fn allocate(layout: Layout) -> Result<NonNull<u8>, AllocError> {420        with(|heap, pages| {421            NonNull::new(unsafe {422                heap.allocate(423                    pages,424                    layout,425                    cdk_rsx_platform::allocation::allocation_priority(),426                )427            })428            .ok_or(AllocError)429        })430        .ok_or(AllocError)?431    }432    pub(super) unsafe fn deallocate(pointer: NonNull<u8>, layout: Layout) {433        if with(|heap, pages| unsafe { heap.release(pages, pointer.as_ptr(), layout) }).is_none() {434            fatal();435        }436    }437    pub(super) unsafe fn resize(438        pointer: NonNull<u8>,439        old: Layout,440        new: Layout,441    ) -> Result<NonNull<u8>, AllocError> {442        with(|heap, pages| {443            NonNull::new(unsafe { heap.resize_layout(pages, pointer.as_ptr(), old, new) })444                .ok_or(AllocError)445        })446        .ok_or(AllocError)?447    }448    pub(super) fn contains(range: Range<usize>) -> bool {449        if !PROVIDER.ready.get() || PROVIDER.busy.get() || range.start > range.end {450            return false;451        }452        let Some(start) = range.start.checked_sub(CONTROL_BASE) else {453            return false;454        };455        let Some(end) = range.end.checked_sub(CONTROL_BASE) else {456            return false;457        };458        // SAFETY: immutable page-domain observation with no live mutable loan.459        unsafe { (*PROVIDER.memory.get()).assume_init_ref() }.contains(start..end)460    }461}