Skip to main content

core/alloc/
mod.rs

1//! Memory allocation APIs
2
3#![stable(feature = "alloc_module", since = "1.28.0")]
4
5mod global;
6mod layout;
7
8#[stable(feature = "global_alloc", since = "1.28.0")]
9pub use self::global::GlobalAlloc;
10#[stable(feature = "alloc_layout", since = "1.28.0")]
11pub use self::layout::Layout;
12#[stable(feature = "alloc_layout", since = "1.28.0")]
13#[deprecated(
14    since = "1.52.0",
15    note = "Name does not follow std convention, use LayoutError",
16    suggestion = "LayoutError"
17)]
18#[allow(deprecated, deprecated_in_future)]
19pub use self::layout::LayoutErr;
20#[stable(feature = "alloc_layout_error", since = "1.50.0")]
21pub use self::layout::LayoutError;
22use crate::error::Error;
23use crate::fmt;
24use crate::ptr::{self, NonNull};
25
26/// The `AllocError` error indicates an allocation failure
27/// that may be due to resource exhaustion or to
28/// something wrong when combining the given input arguments with this
29/// allocator.
30#[unstable(feature = "allocator_api", issue = "32838")]
31#[derive(Copy, Clone, PartialEq, Eq, Debug)]
32pub struct AllocError;
33
34#[unstable(
35    feature = "allocator_api",
36    reason = "the precise API and guarantees it provides may be tweaked.",
37    issue = "32838"
38)]
39impl Error for AllocError {}
40
41// (we need this for downstream impl of trait Error)
42#[unstable(feature = "allocator_api", issue = "32838")]
43impl fmt::Display for AllocError {
44    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
45        f.write_str("memory allocation failed")
46    }
47}
48
49/// An implementation of `Allocator` can allocate, grow, shrink, and deallocate arbitrary blocks of
50/// data described via [`Layout`][].
51///
52/// `Allocator` is designed to be implemented on ZSTs, references, or smart pointers.
53/// An allocator for `MyAlloc([u8; N])` cannot be moved, without updating the pointers to the
54/// allocated memory.
55///
56/// In contrast to [`GlobalAlloc`][], `Allocator` allows zero-sized allocations. If an underlying
57/// allocator does not support this (like jemalloc) or responds by returning a null pointer
58/// (such as `libc::malloc`), this must be caught by the implementation.
59///
60/// ### Currently allocated memory
61///
62/// Some of the methods require that a memory block is *currently allocated* by an allocator.
63/// This means that:
64///  * the starting address for that memory block was previously
65///    returned by [`allocate`], [`grow`], or [`shrink`], and
66///  * the memory block has not subsequently been deallocated.
67///
68/// A memory block is deallocated by a call to [`deallocate`],
69/// or by a call to [`grow`] or [`shrink`] that returns `Ok`.
70/// A call to `grow` or `shrink` that returns `Err`,
71/// does not deallocate the memory block passed to it.
72///
73/// [`allocate`]: Allocator::allocate
74/// [`grow`]: Allocator::grow
75/// [`shrink`]: Allocator::shrink
76/// [`deallocate`]: Allocator::deallocate
77///
78/// ### Memory fitting
79///
80/// Some of the methods require that a `layout` *fit* a memory block or vice versa. This means that the
81/// following conditions must hold:
82///  * the memory block must be *currently allocated* with alignment of [`layout.align()`], and
83///  * [`layout.size()`] must fall in the range `min ..= max`, where:
84///    - `min` is the size of the layout used to allocate the block, and
85///    - `max` is the actual size returned from [`allocate`], [`grow`], or [`shrink`].
86///
87/// [`layout.align()`]: Layout::align
88/// [`layout.size()`]: Layout::size
89///
90/// # Safety
91///
92/// Memory blocks that are [*currently allocated*] by an allocator,
93/// must point to valid memory, and retain their validity until either:
94///  - the memory block is deallocated, or
95///  - the allocator is dropped.
96///
97/// Copying, cloning, or moving the allocator must not invalidate memory blocks returned from it.
98/// A copied or cloned allocator must behave like the original allocator.
99///
100/// A memory block which is [*currently allocated*] may be passed to
101/// any method of the allocator that accepts such an argument.
102///
103/// Additionally, any memory block returned by the allocator must
104/// satisfy the allocation invariants described in `core::ptr`.
105/// In particular, if a block has base address `p` and size `n`,
106/// then `p as usize + n <= usize::MAX` must hold.
107///
108/// This ensures that pointer arithmetic within the allocation
109/// (for example, `ptr.add(len)`) cannot overflow the address space.
110/// [*currently allocated*]: #currently-allocated-memory
111#[unstable(feature = "allocator_api", issue = "32838")]
112#[rustc_const_unstable(feature = "const_heap", issue = "79597")]
113pub const unsafe trait Allocator {
114    /// Attempts to allocate a block of memory.
115    ///
116    /// On success, returns a [`NonNull<[u8]>`][NonNull] meeting the size and alignment guarantees of `layout`.
117    ///
118    /// The returned block may have a larger size than specified by `layout.size()`, and may or may
119    /// not have its contents initialized.
120    ///
121    /// The returned block of memory remains valid as long as it is [*currently allocated*] and the shorter of:
122    ///   - the borrow-checker lifetime of the allocator type itself.
123    ///   - as long as the allocator and all its clones have not been dropped.
124    ///
125    /// [*currently allocated*]: #currently-allocated-memory
126    ///
127    /// # Errors
128    ///
129    /// Returning `Err` indicates that either memory is exhausted or `layout` does not meet
130    /// allocator's size or alignment constraints.
131    ///
132    /// Implementations are encouraged to return `Err` on memory exhaustion rather than panicking or
133    /// aborting, but this is not a strict requirement. (Specifically: it is *legal* to implement
134    /// this trait atop an underlying native allocation library that aborts on memory exhaustion.)
135    ///
136    /// Clients wishing to abort computation in response to an allocation error are encouraged to
137    /// call the [`handle_alloc_error`] function, rather than directly invoking `panic!` or similar.
138    ///
139    /// [`handle_alloc_error`]: ../../alloc/alloc/fn.handle_alloc_error.html
140    fn allocate(&self, layout: Layout) -> Result<NonNull<[u8]>, AllocError>;
141
142    /// Behaves like `allocate`, but also ensures that the returned memory is zero-initialized.
143    ///
144    /// # Errors
145    ///
146    /// Returning `Err` indicates that either memory is exhausted or `layout` does not meet
147    /// allocator's size or alignment constraints.
148    ///
149    /// Implementations are encouraged to return `Err` on memory exhaustion rather than panicking or
150    /// aborting, but this is not a strict requirement. (Specifically: it is *legal* to implement
151    /// this trait atop an underlying native allocation library that aborts on memory exhaustion.)
152    ///
153    /// Clients wishing to abort computation in response to an allocation error are encouraged to
154    /// call the [`handle_alloc_error`] function, rather than directly invoking `panic!` or similar.
155    ///
156    /// [`handle_alloc_error`]: ../../alloc/alloc/fn.handle_alloc_error.html
157    fn allocate_zeroed(&self, layout: Layout) -> Result<NonNull<[u8]>, AllocError> {
158        let ptr = self.allocate(layout)?;
159        // SAFETY: `alloc` returns a valid memory block
160        unsafe { ptr.as_non_null_ptr().as_ptr().write_bytes(0, ptr.len()) }
161        Ok(ptr)
162    }
163
164    /// Deallocates the memory referenced by `ptr`.
165    ///
166    /// # Safety
167    ///
168    /// * `ptr` must denote a block of memory [*currently allocated*] via this allocator, and
169    /// * `layout` must [*fit*] that block of memory.
170    ///
171    /// [*currently allocated*]: #currently-allocated-memory
172    /// [*fit*]: #memory-fitting
173    unsafe fn deallocate(&self, ptr: NonNull<u8>, layout: Layout);
174
175    /// Attempts to extend the memory block.
176    ///
177    /// Returns a new [`NonNull<[u8]>`][NonNull] containing a pointer and the actual size of the allocated
178    /// memory. The pointer is suitable for holding data described by `new_layout`. To accomplish
179    /// this, the allocator may extend the allocation referenced by `ptr` to fit the new layout.
180    ///
181    /// If this returns `Ok`, then ownership of the memory block referenced by `ptr` has been
182    /// transferred to this allocator. Any access to the old `ptr` is Undefined Behavior, even if the
183    /// allocation was grown in-place. The newly returned pointer is the only valid pointer
184    /// for accessing this memory now.
185    ///
186    /// If this method returns `Err`, then ownership of the memory block has not been transferred to
187    /// this allocator, and the contents of the memory block are unaltered.
188    ///
189    /// # Safety
190    ///
191    /// * `ptr` must denote a block of memory [*currently allocated*] via this allocator.
192    /// * `old_layout` must [*fit*] that block of memory (The `new_layout` argument need not fit it.).
193    /// * `new_layout.size()` must be greater than or equal to `old_layout.size()`.
194    ///
195    /// Note that `new_layout.align()` need not be the same as `old_layout.align()`.
196    ///
197    /// [*currently allocated*]: #currently-allocated-memory
198    /// [*fit*]: #memory-fitting
199    ///
200    /// # Errors
201    ///
202    /// Returns `Err` if the new layout does not meet the allocator's size and alignment
203    /// constraints of the allocator, or if growing otherwise fails.
204    ///
205    /// Implementations are encouraged to return `Err` on memory exhaustion rather than panicking or
206    /// aborting, but this is not a strict requirement. (Specifically: it is *legal* to implement
207    /// this trait atop an underlying native allocation library that aborts on memory exhaustion.)
208    ///
209    /// Clients wishing to abort computation in response to an allocation error are encouraged to
210    /// call the [`handle_alloc_error`] function, rather than directly invoking `panic!` or similar.
211    ///
212    /// [`handle_alloc_error`]: ../../alloc/alloc/fn.handle_alloc_error.html
213    unsafe fn grow(
214        &self,
215        ptr: NonNull<u8>,
216        old_layout: Layout,
217        new_layout: Layout,
218    ) -> Result<NonNull<[u8]>, AllocError> {
219        debug_assert!(
220            new_layout.size() >= old_layout.size(),
221            "`new_layout.size()` must be greater than or equal to `old_layout.size()`"
222        );
223
224        let new_ptr = self.allocate(new_layout)?;
225
226        // SAFETY: because `new_layout.size()` must be greater than or equal to
227        // `old_layout.size()`, both the old and new memory allocation are valid for reads and
228        // writes for `old_layout.size()` bytes. Also, because the old allocation wasn't yet
229        // deallocated, it cannot overlap `new_ptr`. Thus, the call to `copy_nonoverlapping` is
230        // safe. The safety contract for `dealloc` must be upheld by the caller.
231        unsafe {
232            ptr::copy_nonoverlapping(ptr.as_ptr(), new_ptr.as_mut_ptr(), old_layout.size());
233            self.deallocate(ptr, old_layout);
234        }
235
236        Ok(new_ptr)
237    }
238
239    /// Behaves like `grow`, but also ensures that the new contents are set to zero before being
240    /// returned.
241    ///
242    /// The memory block will contain the following contents after a successful call to
243    /// `grow_zeroed`:
244    ///   * Bytes `0..old_layout.size()` are preserved from the original allocation.
245    ///   * Bytes `old_layout.size()..old_size` will either be preserved or zeroed, depending on
246    ///     the allocator implementation. `old_size` refers to the size of the memory block prior
247    ///     to the `grow_zeroed` call, which may be larger than the size that was originally
248    ///     requested when it was allocated.
249    ///   * Bytes `old_size..new_size` are zeroed. `new_size` refers to the size of the memory
250    ///     block returned by the `grow_zeroed` call.
251    ///
252    /// # Safety
253    ///
254    /// * `ptr` must denote a block of memory [*currently allocated*] via this allocator.
255    /// * `old_layout` must [*fit*] that block of memory (The `new_layout` argument need not fit it.).
256    /// * `new_layout.size()` must be greater than or equal to `old_layout.size()`.
257    ///
258    /// Note that `new_layout.align()` need not be the same as `old_layout.align()`.
259    ///
260    /// [*currently allocated*]: #currently-allocated-memory
261    /// [*fit*]: #memory-fitting
262    ///
263    /// # Errors
264    ///
265    /// Returns `Err` if the new layout does not meet the allocator's size and alignment
266    /// constraints of the allocator, or if growing otherwise fails.
267    ///
268    /// Implementations are encouraged to return `Err` on memory exhaustion rather than panicking or
269    /// aborting, but this is not a strict requirement. (Specifically: it is *legal* to implement
270    /// this trait atop an underlying native allocation library that aborts on memory exhaustion.)
271    ///
272    /// Clients wishing to abort computation in response to an allocation error are encouraged to
273    /// call the [`handle_alloc_error`] function, rather than directly invoking `panic!` or similar.
274    ///
275    /// [`handle_alloc_error`]: ../../alloc/alloc/fn.handle_alloc_error.html
276    unsafe fn grow_zeroed(
277        &self,
278        ptr: NonNull<u8>,
279        old_layout: Layout,
280        new_layout: Layout,
281    ) -> Result<NonNull<[u8]>, AllocError> {
282        debug_assert!(
283            new_layout.size() >= old_layout.size(),
284            "`new_layout.size()` must be greater than or equal to `old_layout.size()`"
285        );
286
287        let new_ptr = self.allocate_zeroed(new_layout)?;
288
289        // SAFETY: because `new_layout.size()` must be greater than or equal to
290        // `old_layout.size()`, both the old and new memory allocation are valid for reads and
291        // writes for `old_layout.size()` bytes. Also, because the old allocation wasn't yet
292        // deallocated, it cannot overlap `new_ptr`. Thus, the call to `copy_nonoverlapping` is
293        // safe. The safety contract for `dealloc` must be upheld by the caller.
294        unsafe {
295            ptr::copy_nonoverlapping(ptr.as_ptr(), new_ptr.as_mut_ptr(), old_layout.size());
296            self.deallocate(ptr, old_layout);
297        }
298
299        Ok(new_ptr)
300    }
301
302    /// Attempts to shrink the memory block.
303    ///
304    /// Returns a new [`NonNull<[u8]>`][NonNull] containing a pointer and the actual size of the allocated
305    /// memory. The pointer is suitable for holding data described by `new_layout`. To accomplish
306    /// this, the allocator may shrink the allocation referenced by `ptr` to fit the new layout.
307    ///
308    /// If this returns `Ok`, then ownership of the memory block referenced by `ptr` has been
309    /// transferred to this allocator. Any access to the old `ptr` is Undefined Behavior, even if the
310    /// allocation was shrunk in-place. The newly returned pointer is the only valid pointer
311    /// for accessing this memory now.
312    ///
313    /// If this method returns `Err`, then ownership of the memory block has not been transferred to
314    /// this allocator, and the contents of the memory block are unaltered.
315    ///
316    /// # Safety
317    ///
318    /// * `ptr` must denote a block of memory [*currently allocated*] via this allocator.
319    /// * `old_layout` must [*fit*] that block of memory (The `new_layout` argument need not fit it.).
320    /// * `new_layout.size()` must be smaller than or equal to `old_layout.size()`.
321    ///
322    /// Note that `new_layout.align()` need not be the same as `old_layout.align()`.
323    ///
324    /// [*currently allocated*]: #currently-allocated-memory
325    /// [*fit*]: #memory-fitting
326    ///
327    /// # Errors
328    ///
329    /// Returns `Err` if the new layout does not meet the allocator's size and alignment
330    /// constraints of the allocator, or if shrinking otherwise fails.
331    ///
332    /// Implementations are encouraged to return `Err` on memory exhaustion rather than panicking or
333    /// aborting, but this is not a strict requirement. (Specifically: it is *legal* to implement
334    /// this trait atop an underlying native allocation library that aborts on memory exhaustion.)
335    ///
336    /// Clients wishing to abort computation in response to an allocation error are encouraged to
337    /// call the [`handle_alloc_error`] function, rather than directly invoking `panic!` or similar.
338    ///
339    /// [`handle_alloc_error`]: ../../alloc/alloc/fn.handle_alloc_error.html
340    unsafe fn shrink(
341        &self,
342        ptr: NonNull<u8>,
343        old_layout: Layout,
344        new_layout: Layout,
345    ) -> Result<NonNull<[u8]>, AllocError> {
346        debug_assert!(
347            new_layout.size() <= old_layout.size(),
348            "`new_layout.size()` must be smaller than or equal to `old_layout.size()`"
349        );
350
351        let new_ptr = self.allocate(new_layout)?;
352
353        // SAFETY: because `new_layout.size()` must be lower than or equal to
354        // `old_layout.size()`, both the old and new memory allocation are valid for reads and
355        // writes for `new_layout.size()` bytes. Also, because the old allocation wasn't yet
356        // deallocated, it cannot overlap `new_ptr`. Thus, the call to `copy_nonoverlapping` is
357        // safe. The safety contract for `dealloc` must be upheld by the caller.
358        unsafe {
359            ptr::copy_nonoverlapping(ptr.as_ptr(), new_ptr.as_mut_ptr(), new_layout.size());
360            self.deallocate(ptr, old_layout);
361        }
362
363        Ok(new_ptr)
364    }
365
366    /// Creates a "by reference" adapter for this instance of `Allocator`.
367    ///
368    /// The returned adapter also implements `Allocator` and will simply borrow this.
369    #[inline(always)]
370    fn by_ref(&self) -> &Self
371    where
372        Self: Sized,
373    {
374        self
375    }
376}
377
378#[unstable(feature = "allocator_api", issue = "32838")]
379#[rustc_const_unstable(feature = "const_heap", issue = "79597")]
380unsafe impl<A> const Allocator for &A
381where
382    A: [const] Allocator + ?Sized,
383{
384    #[inline]
385    fn allocate(&self, layout: Layout) -> Result<NonNull<[u8]>, AllocError> {
386        (**self).allocate(layout)
387    }
388
389    #[inline]
390    fn allocate_zeroed(&self, layout: Layout) -> Result<NonNull<[u8]>, AllocError> {
391        (**self).allocate_zeroed(layout)
392    }
393
394    #[inline]
395    unsafe fn deallocate(&self, ptr: NonNull<u8>, layout: Layout) {
396        // SAFETY: the safety contract must be upheld by the caller
397        unsafe { (**self).deallocate(ptr, layout) }
398    }
399
400    #[inline]
401    unsafe fn grow(
402        &self,
403        ptr: NonNull<u8>,
404        old_layout: Layout,
405        new_layout: Layout,
406    ) -> Result<NonNull<[u8]>, AllocError> {
407        // SAFETY: the safety contract must be upheld by the caller
408        unsafe { (**self).grow(ptr, old_layout, new_layout) }
409    }
410
411    #[inline]
412    unsafe fn grow_zeroed(
413        &self,
414        ptr: NonNull<u8>,
415        old_layout: Layout,
416        new_layout: Layout,
417    ) -> Result<NonNull<[u8]>, AllocError> {
418        // SAFETY: the safety contract must be upheld by the caller
419        unsafe { (**self).grow_zeroed(ptr, old_layout, new_layout) }
420    }
421
422    #[inline]
423    unsafe fn shrink(
424        &self,
425        ptr: NonNull<u8>,
426        old_layout: Layout,
427        new_layout: Layout,
428    ) -> Result<NonNull<[u8]>, AllocError> {
429        // SAFETY: the safety contract must be upheld by the caller
430        unsafe { (**self).shrink(ptr, old_layout, new_layout) }
431    }
432}
433
434#[unstable(feature = "allocator_api", issue = "32838")]
435unsafe impl<A> Allocator for &mut A
436where
437    A: Allocator + ?Sized,
438{
439    #[inline]
440    fn allocate(&self, layout: Layout) -> Result<NonNull<[u8]>, AllocError> {
441        (**self).allocate(layout)
442    }
443
444    #[inline]
445    fn allocate_zeroed(&self, layout: Layout) -> Result<NonNull<[u8]>, AllocError> {
446        (**self).allocate_zeroed(layout)
447    }
448
449    #[inline]
450    unsafe fn deallocate(&self, ptr: NonNull<u8>, layout: Layout) {
451        // SAFETY: the safety contract must be upheld by the caller
452        unsafe { (**self).deallocate(ptr, layout) }
453    }
454
455    #[inline]
456    unsafe fn grow(
457        &self,
458        ptr: NonNull<u8>,
459        old_layout: Layout,
460        new_layout: Layout,
461    ) -> Result<NonNull<[u8]>, AllocError> {
462        // SAFETY: the safety contract must be upheld by the caller
463        unsafe { (**self).grow(ptr, old_layout, new_layout) }
464    }
465
466    #[inline]
467    unsafe fn grow_zeroed(
468        &self,
469        ptr: NonNull<u8>,
470        old_layout: Layout,
471        new_layout: Layout,
472    ) -> Result<NonNull<[u8]>, AllocError> {
473        // SAFETY: the safety contract must be upheld by the caller
474        unsafe { (**self).grow_zeroed(ptr, old_layout, new_layout) }
475    }
476
477    #[inline]
478    unsafe fn shrink(
479        &self,
480        ptr: NonNull<u8>,
481        old_layout: Layout,
482        new_layout: Layout,
483    ) -> Result<NonNull<[u8]>, AllocError> {
484        // SAFETY: the safety contract must be upheld by the caller
485        unsafe { (**self).shrink(ptr, old_layout, new_layout) }
486    }
487}