Skip to main content

Alloc

Trait Alloc 

Source
pub unsafe trait Alloc: Meta {
    // Provided methods
    fn alloc_uninit(
        &self,
        size: usize,
    ) -> Result<NonNull<MaybeUninit<u8>>, Self::Error> { ... }
    fn alloc_zeroed(&self, size: usize) -> Result<NonNull<u8>, Self::Error> { ... }
}
Expand description

Allocation functions with alignment (up to Meta::MAX_ALIGN) implied by size: fn alloc_uninit(size: usize) -> Result<NonNull<_>, _> fn alloc_zeroed(size: usize) -> Result<NonNull<_>, _>

§Safety

Invariants that Alloc must uphold for the soundness of various unsafe code include:

ItemDescription
alignReturned allocations must have correct alignment based on size per the alignment guarantees section bellow.
sizeReturned allocations must be valid to read and/or write for at least size bytes.
pinReturned allocations must remain valid at their initial address for the lifetime of Self (typically 'static!), or until freed by Free or successful Realloc - whichever comes first. In some cases (e.g. structs allocating from arrays on self without heap indirection), this might mean that the traits can only be implemented on shared references, rather than on the structs themselves.
compatibleReturned allocations must be compatible with all other thin traits implemented on the same allocator (at minimum in the sense that they must not cause undefined behavior when passed pointers to said allocations)
exclusiveReturned allocations belong exclusively to the caller. Double allocating the same pool slot without a free would be undefined behavior.
exceptionsSystem allocators typically use extern "C" FFI, which is not safe to unwind exceptions through. Ensure you catch any expected exceptions such as C++’s std::bad_alloc and SEH exceptions like STATUS_HEAP_CORRUPTION (e.g. don’t use HEAP_GENERATE_EXCEPTIONS) on the C/C++ side before returning into Rust code.
threadsAllocators are typically implicitly Send+Sync, which means the underlying FFI calls must be thread safe too.
zeroedAllocations returned by Alloc::alloc_zeroed must be zeroed for their entire size. This might be for more than size if SizeOfDebug is implemented.

§Alignment Guarantees

Requested SizeGuaranteed Alignment (if successful)
0 .. Meta::MIN_ALIGNMeta::MIN_ALIGN
Meta::MIN_ALIGN .. MAX_ALIGNThe largest power of two that fits within size
Meta::MAX_ALIGN ..Meta::MAX_ALIGN

Provided Methods§

Source

fn alloc_uninit( &self, size: usize, ) -> Result<NonNull<MaybeUninit<u8>>, Self::Error>

Allocate at least size bytes of uninitialized memory.

The resulting allocation can typically be freed with Free::free

Examples found in repository?
examples/alloc-tester.rs (line 33)
28    pub fn thin(&mut self) -> &mut Self where A : thin::Alloc + thin::Free {
29        let mut thin = AlignmentRange { min: Alignment::MAX, max: Alignment::MAX };
30        for (dst, min_size) in [(&mut thin.min, 1), (&mut thin.max, 4096)] {
31            for _ in 0 .. 100 {
32                let alloc = (self.create)();
33                let addrs = [(); 4096].into_iter().enumerate().map(|(i, _)| alloc.alloc_uninit(i%16+min_size).unwrap()).collect::<Vec<_>>();
34                let addrbits = addrs[..].iter().copied().map(|addr| addr.as_ptr() as usize).reduce(|x,y| x|y).unwrap();
35                addrs.iter().copied().for_each(|addr| unsafe { alloc.free(addr) });
36                let align = Alignment::new(1 << addrbits.trailing_zeros()).unwrap();
37                *dst = align.min(*dst);
38            }
39        }
40        self.thin = Some(thin);
41        self
42    }
Source

fn alloc_zeroed(&self, size: usize) -> Result<NonNull<u8>, Self::Error>

Allocate at least size bytes of zeroed memory.

The resulting allocation can typically be freed with Free::free

Dyn Compatibility§

This trait is not dyn compatible.

In older versions of Rust, dyn compatibility was called "object safety".

Implementations on Foreign Types§

Source§

impl<'a, A: Alloc> Alloc for &'a A

Source§

fn alloc_uninit( &self, size: usize, ) -> Result<NonNull<MaybeUninit<u8>>, Self::Error>

Source§

fn alloc_zeroed(&self, size: usize) -> Result<NonNull<u8>, Self::Error>

Implementors§

Source§

impl Alloc for CoTaskMem

Safety ItemDescription
align✔️ Validated via thin::test::alignment
size✔️ Validated via thin::test::edge_case_sizes
pin✔️ CoTaskMem is 'static - allocations by CoTaskMemAlloc live until CoTaskMemRealloced or CoTaskMemFreed
compatible✔️ CoTaskMem uses exclusively intercompatible fns
exclusive✔️ Allocations by CoTaskMemAlloc are exclusive/unique
exceptions✔️ CoTaskMemAlloc returns null on error per docs / lack of HEAP_GENERATE_EXCEPTIONS. Non-unwinding fatalish heap corruption exceptions will only occur after previous undefined behavior.
threads✔️ CoTaskMemAlloc uses a no-init gCMalloc::Alloc → HeapAlloc with dwFlags=0 (e.g. not using HEAP_NO_SERIALIZE) under the hood
zeroed✔️ Validated via thin::test::zeroed_alloc, trivial default impl
Source§

impl Alloc for CryptMem

Safety ItemDescription
align✔️ Validated via thin::test::alignment
size✔️ Validated via thin::test::edge_case_sizes
pin✔️ CryptMem is 'static - allocations by CryptMemAlloc live until CryptMemRealloced or CryptMemFreed
compatible✔️ CryptMem uses exclusively intercompatible fns
exclusive✔️ Allocations by CryptMemAlloc are exclusive/unique
exceptions✔️ CryptMemAlloc returns null on error per docs / lack of HEAP_GENERATE_EXCEPTIONS. Non-unwinding fatalish heap corruption exceptions will only occur after previous undefined behavior.
threads✔️ CryptMemAlloc uses LocalAlloc(LMEM_ZEROINIT, size), and Local claims to be thread safe
zeroed✔️ Validated via thin::test::zeroed_alloc, trivial default impl
Source§

impl Alloc for Global

Safety ItemDescription
align✔️ Validated via thin::test::alignment
size✔️ Validated via thin::test::edge_case_sizes, no oddball flags like GMEM_MOVEABLE that would ruin dereferencability of the returned allocation
pin✔️ Global is 'static - allocations by GlobalAlloc live until GlobalReAlloced or GlobalFreed (as we don’t use GMEM_MOVEABLE)
compatible✔️ Global uses exclusively intercompatible Global* fns
exclusive✔️ Allocations by GlobalAlloc are exclusive/unique
exceptions✔️ GlobalAlloc returns null on error per docs / lack of HEAP_GENERATE_EXCEPTIONS. Non-unwinding fatalish heap corruption exceptions will only occur after previous undefined behavior.
threads⚠️ GlobalAlloc eventually calls HeapAlloc, without HEAP_NO_SERIALIZE, which should be thread safe - as claimed by random Stack Overflow threads.
zeroed✔️ Validated via thin::test::zeroed_alloc, GMEM_ZEROINIT used appropriately
Source§

impl Alloc for Heap

Safety ItemDescription
align✔️ Validated via thin::test::alignment
size✔️ Validated via thin::test::edge_case_sizes
pin✔️ Heap is 'static - allocations by HeapAlloc live until HeapReAlloced, HeapFreed, or the Heap is Droped outright (not merely moved.)
compatible✔️ Heap uses exclusively intercompatible Heap* fns
exclusive✔️ Allocations by HeapAlloc are exclusive/unique
exceptions✔️ HeapAlloc returns null on error per docs / lack of HEAP_GENERATE_EXCEPTIONS. Non-unwinding fatalish heap corruption exceptions will only occur after previous undefined behavior.
threads✔️ HEAP_NO_SERIALIZE is not used, making this thread safe.
zeroed✔️ Validated via thin::test::zeroed_alloc, correct use of HEAP_ZERO_MEMORY
Source§

impl Alloc for HeapNoSerialize

Safety ItemDescription
align✔️ Validated via thin::test::alignment
size✔️ Validated via thin::test::edge_case_sizes
pin✔️ HeapNoSerialize is 'static - allocations by HeapAlloc live until HeapReAlloced, HeapFreed, or the HeapNoSerialize is Droped outright (not merely moved.)
compatible✔️ HeapNoSerialize uses exclusively intercompatible Heap* fns
exclusive✔️ Allocations by HeapAlloc are exclusive/unique
exceptions✔️ HeapAlloc returns null on error per docs / lack of HEAP_GENERATE_EXCEPTIONS. Non-unwinding fatalish heap corruption exceptions will only occur after previous undefined behavior.
threads✔️ HEAP_NO_SERIALIZE is used, making this not thread safe. However, we enforce HeapNoSerialize : !Send + !Sync as validated by AssertNotSendSync.
zeroed✔️ Validated via thin::test::zeroed_alloc, correct use of HEAP_ZERO_MEMORY
Source§

impl Alloc for IMalloc

Safety ItemDescription
align✔️ Validated via thin::test::alignment
size✔️ Validated via thin::test::edge_case_sizes
pin✔️ IMalloc is 'static - allocations by IMalloc::Alloc live until IMalloc::Realloced, IMalloc::Freed, or theoretically with some impls, perhaps if the last reference to the underlying IMalloc is released (not merely moved.)
compatible✔️ IMalloc uses exclusively intercompatible fns
exclusive✔️ Allocations by IMalloc are exclusive/unique
exceptions✔️ IMalloc::Alloc returns null on error per docs / lack of HEAP_GENERATE_EXCEPTIONS. Non-unwinding fatalish heap corruption exceptions will only occur after previous undefined behavior.
threads✔️ IMalloc is !Send + !Sync
zeroed✔️ Validated via thin::test::zeroed_alloc, trivial default impl
Source§

impl Alloc for Local

Safety ItemDescription
align✔️ Validated via thin::test::alignment
size✔️ Validated via thin::test::edge_case_sizes, no oddball flags like LMEM_MOVEABLE that would ruin dereferencability of the returned allocation
pin✔️ Local is 'static - allocations by LocalAlloc live until LocalReAlloced or LocalFreed (as we don’t use LMEM_MOVEABLE)
compatible✔️ Local uses exclusively intercompatible Local* fns
exclusive✔️ Allocations by LocalAlloc are exclusive/unique
exceptions✔️ LocalAlloc returns null on error per docs / lack of HEAP_GENERATE_EXCEPTIONS. Non-unwinding fatalish heap corruption exceptions will only occur after previous undefined behavior.
threads⚠️ LocalAlloc eventually calls HeapAlloc, without HEAP_NO_SERIALIZE, which should be thread safe - as claimed by random Stack Overflow threads.
zeroed✔️ Validated via thin::test::zeroed_alloc, LMEM_ZEROINIT used appropriately
Source§

impl Alloc for Malloc

Safety ItemDescription
align✔️ Validated via fat::test::alignment (“The pointer returned if the allocation succeeds is suitably aligned so that it may be assigned to a pointer to any type of object and then used to access such an object or an array of such objects in the space allocated (until the space is explicitly deallocated).” C89 § 7.20.3 ¶ 1)
size✔️ Validated via fat::test::edge_case_sizes
pin✔️ Malloc is 'static - allocations by malloc / calloc live until freed (“The lifetime of an allocated object extends from the allocation until the deallocation.” C89 § 7.20.3 ¶ 1)
compatible✔️ Malloc uses exclusively intercompatible malloc / realloc / calloc / free / _recalloc
exclusive✔️ Allocations by malloc / calloc are exclusive/unique (“Each such allocation shall yield a pointer to an object disjoint from any other object.” C89 § 7.20.3 ¶ 1)
exceptions✔️ malloc / calloc throw no exceptions (it’s C) and return null on errors (C89 § 7.20.3.1 ¶ 3, C89 § 7.20.3.3 ¶ 3)
threads⚠️ thread-unsafe stdlibs existed once upon a time. I consider linking them in a multithreaded program defacto undefined behavior beyond the scope of this to guard against.
zeroed✔️ Validated via thin::test::zeroed_alloc, correct use of calloc (“The space is initialized to all bits zero” C89 § 7.20.3.1 ¶ 2)
Source§

impl Alloc for NewDelete

Safety ItemDescription
align✔️ Validated via thin::test::alignment
size✔️ Validated via thin::test::edge_case_sizes
pin✔️ NewDelete is 'static - allocations by ::operator new(size_t, nothrow_t) live until ::operator delete(void*)ed.
compatible✔️ NewDelete uses exclusively intercompatible un-arrayed, implicit-alignment operators from the same stdlib.
compatible✔️ ::operator delete(void*) is compatible with ::operator new(size_t, nothrow_t) (C++03 § 18.4.1.1 ¶ 12)
exclusive✔️ ::operator new(size_t, nothrow_t) allocations are exclusive/unique
exceptions✔️ ::operator new(size_t, nothrow_t) is throw() and will return null on error (C++03 § 18.4.1.1 ¶ 5, or noexcept in C++11+)
threads⚠️ thread-unsafe stdlibs existed once upon a time. I consider linking them in a multithreaded program defacto undefined behavior beyond the scope of this to guard against.
zeroed✔️ Validated via thin::test::zeroed_alloc
Source§

impl Alloc for NewDeleteArray

Safety ItemDescription
align✔️ Validated via thin::test::alignment
size✔️ Validated via thin::test::edge_case_sizes
pin✔️ NewDeleteArray is 'static - allocations by ::operator new[](size_t, nothrow_t) live until ::operator delete[](void*)ed.
compatible✔️ NewDeleteArray uses exclusively intercompatible arrayed, implicit-alignment operators from the same stdlib.
compatible✔️ ::operator delete[](void*) is compatible with ::operator new[](size_t, nothrow_t) (C++03 § 18.4.1.2 ¶ 11)
exclusive✔️ ::operator new[](size_t, nothrow_t) allocations are exclusive/unique
exceptions✔️ ::operator new[](size_t, nothrow_t) is throw() and will return null on error (C++03 § 18.4.1.2 ¶ 5, or noexcept in C++11+)
threads⚠️ thread-unsafe stdlibs existed once upon a time. I consider linking them in a multithreaded program defacto undefined behavior beyond the scope of this to guard against.
zeroed✔️ Validated via thin::test::zeroed_alloc
Source§

impl Alloc for Null

Source§

impl Alloc for ProcessHeap

Source§

impl Alloc for StdAllocator<c_char>

Safety ItemDescription
align✔️ Validated via fat::test::alignment
size✔️ Validated via fat::test::edge_case_sizes
pin✔️ StdAllocator<c_char> is 'static - allocations by std::allocator<T>::allocate live until std::allocator<T>::deallocated.
compatible✔️ StdAllocator<c_char> uses exclusively intercompatible std::allocator<char> functions
compatible✔️ std::allocator<char> is stateless (see is_always_equal checks in ffi.cpp)
exclusive✔️ std::allocator<T>::allocate allocations are exclusive/unique
exceptions✔️ std::allocator<T>::allocate can throw std::bad_alloc - the FFI wrapper around it catches std::bad_alloc and returns nullptr instead.
threads⚠️ thread-unsafe stdlibs existed once upon a time. I consider linking them in a multithreaded program defacto undefined behavior beyond the scope of this to guard against.
zeroed✔️ Validated via fat::test::zeroed_alloc
Source§

impl Alloc for VirtualCommit

Safety ItemDescription
align✔️ Validated via thin::test::alignment. Minimum 4 KiB pages in practice (Windows doesn’t generally support smaller pages even when processors do), often more (e.g. 64 KiB)
size✔️ Validated via thin::test::edge_case_sizes
pin✔️ VirtualCommit is 'static - allocations by VirtualAlloc live until VirtualFreeed or similar.
compatible✔️ VirtualCommit uses exclusively intercompatible Virtual* fns
exclusive✔️ Allocations by VirtualAlloc are exclusive/unique
exceptions✔️ VirtualAlloc returns null on error per docs, page structures live outside of process memory where they’re “incorruptable”
threads⚠️ As everything builds upon Virtual*, and Microsoft isn’t a bunch of dummies, VirtualAlloc should should be thread safe, although it’s poorly documented
zeroed✔️ Validated via thin::test::zeroed_alloc, correct use of HEAP_ZERO_MEMORY
Source§

impl<A: Alloc> Alloc for AllocZst<A>

Source§

impl<A: Alloc> Alloc for DangleZst<A>

Source§

impl<A: Alloc> Alloc for PanicOverAlign<A>

Source§

impl<const A: usize, const B: usize, const N: usize> Alloc for &FixedPoolLinearProbe<A, B, N>
where [(); A]: ValidAlignLessThan1GiB,