Skip to main content

alloc/
alloc.rs

1//! Memory allocation APIs
2
3#![stable(feature = "alloc_module", since = "1.28.0")]
4
5#[stable(feature = "alloc_module", since = "1.28.0")]
6#[doc(inline)]
7pub use core::alloc::*;
8use core::mem::Alignment;
9use core::ptr::{self, NonNull};
10use core::{cmp, hint};
11
12unsafe extern "Rust" {
13    // These are the magic symbols to call the global allocator. rustc generates
14    // them to call the global allocator if there is a `#[global_allocator]` attribute
15    // (the code expanding that attribute macro generates those functions), or to call
16    // the default implementations in std (`__rdl_alloc` etc. in `library/std/src/alloc.rs`)
17    // otherwise.
18    #[rustc_allocator]
19    #[rustc_nounwind]
20    #[rustc_std_internal_symbol]
21    #[rustc_allocator_zeroed_variant = "__rust_alloc_zeroed"]
22    fn __rust_alloc(size: usize, align: Alignment) -> *mut u8;
23    #[rustc_deallocator]
24    #[rustc_nounwind]
25    #[rustc_std_internal_symbol]
26    fn __rust_dealloc(ptr: NonNull<u8>, size: usize, align: Alignment);
27    #[rustc_reallocator]
28    #[rustc_nounwind]
29    #[rustc_std_internal_symbol]
30    fn __rust_realloc(
31        ptr: NonNull<u8>,
32        old_size: usize,
33        align: Alignment,
34        new_size: usize,
35    ) -> *mut u8;
36    #[rustc_allocator_zeroed]
37    #[rustc_nounwind]
38    #[rustc_std_internal_symbol]
39    fn __rust_alloc_zeroed(size: usize, align: Alignment) -> *mut u8;
40
41    #[rustc_nounwind]
42    #[rustc_std_internal_symbol]
43    fn __rust_no_alloc_shim_is_unstable_v2();
44}
45
46/// A wrapper for the global allocator.
47///
48/// This type implements the [`Allocator`] trait by forwarding calls
49/// to the allocator registered with the `#[global_allocator]` attribute
50/// if there is one, or the `std` crate’s default.
51///
52/// `Global` is not "the global allocator", but a wrapper for it.
53/// If the global allocator used `Global`, it would call itself recursively.
54/// To avoid this, `Global` does not implement [`GlobalAlloc`].
55///
56/// Similar to [`alloc`], [`dealloc`], and the other global allocation functions,
57/// when and how calls are forwarded to the allocator registered with
58/// `#[global_allocator]` is unspecified. See their safety docs for more information.
59///
60/// In particular, even if you know which allocator was registered
61/// as the global allocator, calling it directly is not the same as calling
62/// `Global`. You cannot deallocate memory from one using the other.
63///
64/// `Global` must be treated like an opaque allocator that only guarantees the contract
65/// described in the docs of [`Allocator`], as well as the following:
66/// * All instances of `Global` are [*equivalent*].
67/// * Allocations from `Global` are only invalidated by calls to de-/reallocating functions.
68///   If no such call is made, then the allocation will live for the rest of the program.
69/// * The global allocation functions in the [`alloc`](self) module are equivalent to the
70///   methods on `Global`, except that they disallow zero-sized allocations, and implicitly
71///   ignore any returned excess size.
72///   In particular, you may deallocate memory from [`alloc::alloc`](self::alloc) using
73///   [`Global.deallocate`](Global::deallocate) and vice-versa.
74///
75/// Note that the current implementation of `Global` does not take advantage of
76/// some features of [`Allocator`], such as zero-sized allocations (which currently
77/// return a dangling pointer) and overallocating.
78/// This may change in the future. You must not rely on it for correctness!
79///
80/// [*equivalent*]: Allocator#equivalent-allocators
81#[stable(feature = "allocator_api", since = "1.100.0")]
82#[derive(Copy, Debug)]
83#[derive_const(Clone, Default)]
84// the compiler needs to know when a Box uses the global allocator vs a custom one
85#[lang = "global_alloc_ty"]
86pub struct Global;
87
88#[unstable(feature = "allocator_ext", issue = "163177", implied_by = "allocator_api")]
89unsafe impl core::alloc::AllocatorClone for Global {}
90
91#[unstable(feature = "allocator_ext", issue = "163177", implied_by = "allocator_api")]
92unsafe impl core::alloc::StaticAllocator for Global {}
93
94/// Allocates memory with the global allocator.
95///
96/// This function forwards calls to the [`GlobalAlloc::alloc`] method
97/// of the allocator registered with the `#[global_allocator]` attribute
98/// if there is one, or the `std` crate’s default.
99///
100/// Note, however, that invoking this function is *not* equivalent to invoking the underlying
101/// [`GlobalAlloc::alloc`] method of the registered allocator directly. Users of this function
102/// cannot assume anything about what the allocator does, other than the documented requirements.
103/// This means:
104///
105/// - This function may non-deterministically entirely skip the underlying allocator, e.g. if the
106///   compiler can show that this allocation can be replaced by a stack variable. The compiler may
107///   also merge multiple allocation operations into one, as long as it can also adjust all
108///   corresponding deallocation operations accordingly.
109/// - An allocation created by invoking this function has exactly the size and minimum alignment
110///   defined by `layout`, even if the underlying allocator makes stronger promises.
111/// - The allocation can only be freed by invoking [`dealloc`] or [`realloc`]. In particular,
112///   passing a pointer to such an allocation directly to the underlying method on [`GlobalAlloc`] is
113///   not permitted. Until one of those functions is called, it is undefined behavior to access the
114///   memory that backs this allocation with any pointer not derived from the return value of this
115///   function (e.g., with internal pointers the allocator might keep around).
116/// - This function de-initializes the contents of the allocation before handing it to the user. So even
117///   if you control the underlying allocator and know that it explicitly initialized this memory,
118///   you cannot rely on it being initialized.
119///
120/// Users of this function have to consider that in the future, allocators may be allowed to unwind.
121///
122/// This function is expected to be deprecated in favor of the `allocate` method
123/// of the [`Global`] type when it and the [`Allocator`] trait become stable.
124///
125/// # Safety
126///
127/// See [`GlobalAlloc::alloc`].
128///
129/// # Examples
130///
131/// ```
132/// use std::alloc::{alloc, dealloc, handle_alloc_error, Layout};
133///
134/// unsafe {
135///     let layout = Layout::new::<u16>();
136///     let ptr = alloc(layout);
137///     if ptr.is_null() {
138///         handle_alloc_error(layout);
139///     }
140///
141///     *(ptr as *mut u16) = 42;
142///     assert_eq!(*(ptr as *mut u16), 42);
143///
144///     dealloc(ptr, layout);
145/// }
146/// ```
147#[stable(feature = "global_alloc", since = "1.28.0")]
148#[must_use = "losing the pointer will leak memory"]
149#[inline]
150#[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces
151pub unsafe fn alloc(layout: Layout) -> *mut u8 {
152    // SAFETY: Upheld by caller.
153    unsafe {
154        // Make sure we don't accidentally allow omitting the allocator shim in
155        // stable code until it is actually stabilized.
156        __rust_no_alloc_shim_is_unstable_v2();
157
158        __rust_alloc(layout.size(), layout.alignment())
159    }
160}
161
162/// Deallocates memory with the global allocator.
163///
164/// This function forwards calls to the [`GlobalAlloc::dealloc`] method
165/// of the allocator registered with the `#[global_allocator]` attribute
166/// if there is one, or the `std` crate’s default.
167///
168/// Note, however, that invoking this function is *not* equivalent to invoking the underlying
169/// [`GlobalAlloc::dealloc`] method of the registered allocator directly. Users of this function
170/// cannot assume anything about what the allocator does, other than the documented requirements.
171/// This means:
172///
173/// - This function may non-deterministically entirely skip the underlying allocator, e.g. if the
174///   compiler can show that this allocation can be replaced by a stack variable. The compiler may
175///   also merge multiple allocation operations into one, as long as it can also adjust all
176///   corresponding deallocation operations accordingly.
177/// - The pointer passed to this function must have been obtained by invoking [`alloc`],
178///   [`alloc_zeroed`], or [`realloc`]. In particular, passing a pointer returned by the underlying
179///   methods on [`GlobalAlloc`] is not permitted.
180/// - This function de-initializes the contents of the allocation before handing it to the allocator.
181///   So even if you know that the program previously initialized that memory, the allocator cannot
182///   rely on it being initialized.
183///
184/// Users of this function have to consider that in the future, allocators may be allowed to unwind.
185///
186/// This function is expected to be deprecated in favor of the `deallocate` method
187/// of the [`Global`] type when it and the [`Allocator`] trait become stable.
188///
189/// # Safety
190///
191/// See [`GlobalAlloc::dealloc`].
192#[stable(feature = "global_alloc", since = "1.28.0")]
193#[inline]
194#[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces
195pub unsafe fn dealloc(ptr: *mut u8, layout: Layout) {
196    // SAFETY: Upheld by caller.
197    unsafe { dealloc_nonnull(NonNull::new_unchecked(ptr), layout) }
198}
199
200/// Same as [`dealloc`] but when you already have a non-null pointer
201#[inline]
202#[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces
203unsafe fn dealloc_nonnull(ptr: NonNull<u8>, layout: Layout) {
204    // SAFETY: Upheld by caller.
205    unsafe { __rust_dealloc(ptr, layout.size(), layout.alignment()) }
206}
207
208/// Reallocates memory with the global allocator.
209///
210/// This function forwards calls to the [`GlobalAlloc::realloc`] method
211/// of the allocator registered with the `#[global_allocator]` attribute
212/// if there is one, or the `std` crate’s default.
213///
214/// Note, however, that invoking this function is *not* equivalent to invoking the underlying
215/// [`GlobalAlloc::realloc`] method of the registered allocator directly. Users of this function
216/// cannot assume anything about what the allocator does, other than the documented requirements.
217/// This means:
218///
219/// - This function may non-deterministically entirely skip the underlying allocator, e.g. if the
220///   compiler can show that this allocation can be replaced by a stack variable. The compiler may
221///   also merge multiple allocation operations into one, as long as it can also adjust all
222///   corresponding deallocation operations accordingly.
223/// - The pointer passed to this function must have been obtained by invoking [`alloc`],
224///   [`alloc_zeroed`], or [`realloc`]. In particular, passing a pointer returned by the underlying
225///   methods on [`GlobalAlloc`] is not permitted.
226/// - An allocation created by invoking this function has exactly the size and minimum alignment
227///   defined by `layout`, even if the underlying allocator makes stronger promises.
228/// - The allocation can only be freed by invoking [`dealloc`] or [`realloc`]. In particular,
229///   passing a pointer to such an allocation directly to the underlying method on [`GlobalAlloc`] is
230///   not permitted. Until one of those functions is called, it is undefined behavior to access the
231///   memory that backs this allocation with any pointer not derived from the return value of this
232///   function (e.g., with internal pointers the allocator might keep around).
233/// - If this grows the allocation, the contents of the grown part of the new allocation allocation
234///   are de-initialized by this function before returning.
235/// - If this shrinks the allocation, the contents of the removed part of the old allocation are
236///   de-initialized by this function before invoking the underlying allocator.
237///
238/// Users of this function have to consider that in the future, allocators may be allowed to unwind.
239///
240/// This function is expected to be deprecated in favor of the `grow` and `shrink` methods
241/// of the [`Global`] type when it and the [`Allocator`] trait become stable.
242///
243/// # Safety
244///
245/// See [`GlobalAlloc::realloc`].
246#[stable(feature = "global_alloc", since = "1.28.0")]
247#[must_use = "losing the pointer will leak memory"]
248#[inline]
249#[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces
250pub unsafe fn realloc(ptr: *mut u8, layout: Layout, new_size: usize) -> *mut u8 {
251    // SAFETY: Upheld by caller.
252    unsafe { realloc_nonnull(NonNull::new_unchecked(ptr), layout, new_size) }
253}
254
255/// Same as [`realloc`] but when you already have a non-null pointer
256#[inline]
257#[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces
258unsafe fn realloc_nonnull(ptr: NonNull<u8>, layout: Layout, new_size: usize) -> *mut u8 {
259    // SAFETY: Upheld by caller.
260    unsafe { __rust_realloc(ptr, layout.size(), layout.alignment(), new_size) }
261}
262
263/// Allocates zero-initialized memory with the global allocator.
264///
265/// This function forwards calls to the [`GlobalAlloc::alloc_zeroed`] method
266/// of the allocator registered with the `#[global_allocator]` attribute
267/// if there is one, or the `std` crate’s default.
268///
269/// Note, however, that invoking this function is *not* equivalent to invoking the underlying
270/// [`GlobalAlloc::alloc_zeroed`] method of the registered allocator directly. Users of this
271/// function cannot assume anything about what the allocator does, other than the documented
272/// requirements. This means:
273///
274/// - This function may non-deterministically entirely skip the underlying allocator, e.g. if the
275///   compiler can show that this allocation can be replaced by a stack variable. The compiler may
276///   also merge multiple allocation operations into one, as long as it can also adjust all
277///   corresponding deallocation operations accordingly.
278/// - The allocation can only be freed by invoking [`dealloc`] or [`realloc`]. In particular,
279///   passing a pointer to such an allocation directly to the underlying method on [`GlobalAlloc`] is
280///   not permitted. Until one of those functions is called, it is undefined behavior to access the
281///   memory that backs this allocation with any pointer not derived from the return value of this
282///   function (e.g., with internal pointers the allocator might keep around).
283/// - An allocation created by invoking this function has exactly the size and minimum alignment
284///   defined by `layout`, even if the underlying allocator makes stronger promises.
285///
286/// Users of this function have to consider that in the future, allocators may be allowed to unwind.
287///
288/// This function is expected to be deprecated in favor of the `allocate_zeroed` method
289/// of the [`Global`] type when it and the [`Allocator`] trait become stable.
290///
291/// # Safety
292///
293/// See [`GlobalAlloc::alloc_zeroed`].
294///
295/// # Examples
296///
297/// ```
298/// use std::alloc::{alloc_zeroed, dealloc, handle_alloc_error, Layout};
299///
300/// unsafe {
301///     let layout = Layout::new::<u16>();
302///     let ptr = alloc_zeroed(layout);
303///     if ptr.is_null() {
304///         handle_alloc_error(layout);
305///     }
306///
307///     assert_eq!(*(ptr as *mut u16), 0);
308///
309///     dealloc(ptr, layout);
310/// }
311/// ```
312#[stable(feature = "global_alloc", since = "1.28.0")]
313#[must_use = "losing the pointer will leak memory"]
314#[inline]
315#[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces
316pub unsafe fn alloc_zeroed(layout: Layout) -> *mut u8 {
317    // SAFETY: Upheld by caller.
318    unsafe {
319        // Make sure we don't accidentally allow omitting the allocator shim in
320        // stable code until it is actually stabilized.
321        __rust_no_alloc_shim_is_unstable_v2();
322
323        __rust_alloc_zeroed(layout.size(), layout.alignment())
324    }
325}
326
327impl Global {
328    #[inline]
329    #[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces
330    fn alloc_impl_runtime(layout: Layout, zeroed: bool) -> Result<NonNull<[u8]>, AllocError> {
331        match layout.size() {
332            0 => Ok(layout.dangling_ptr().cast_slice(0)),
333            // SAFETY: `layout` is non-zero in size,
334            size => unsafe {
335                let raw_ptr = if zeroed { alloc_zeroed(layout) } else { alloc(layout) };
336                let ptr = NonNull::new(raw_ptr).ok_or(AllocError)?;
337                Ok(ptr.cast_slice(size))
338            },
339        }
340    }
341
342    #[inline]
343    #[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces
344    fn deallocate_impl_runtime(ptr: NonNull<u8>, layout: Layout) {
345        if layout.size() != 0 {
346            // SAFETY:
347            // * We have checked that `layout` is non-zero in size.
348            // * The caller is obligated to provide a layout that "fits", and in this case,
349            //   "fit" always means a layout that is equal to the original, because our
350            //   `allocate()`, `grow()`, and `shrink()` implementations never returns a larger
351            //   allocation than requested.
352            // * Other conditions must be upheld by the caller, as per `Allocator::deallocate()`'s
353            //   safety documentation.
354            unsafe { dealloc_nonnull(ptr, layout) }
355        }
356    }
357
358    // SAFETY: Same as `Allocator::grow`
359    #[inline]
360    #[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces
361    fn grow_impl_runtime(
362        &self,
363        ptr: NonNull<u8>,
364        old_layout: Layout,
365        new_layout: Layout,
366        zeroed: bool,
367    ) -> Result<NonNull<[u8]>, AllocError> {
368        debug_assert!(
369            new_layout.size() >= old_layout.size(),
370            "`new_layout.size()` must be greater than or equal to `old_layout.size()`"
371        );
372
373        match old_layout.size() {
374            0 => self.alloc_impl(new_layout, zeroed),
375
376            // SAFETY: `new_size` is non-zero as `old_size` is greater than or equal to `new_size`
377            // as required by safety conditions. Other conditions must be upheld by the caller
378            old_size if old_layout.align() == new_layout.align() => unsafe {
379                let new_size = new_layout.size();
380
381                // `realloc` probably checks for `new_size >= old_layout.size()` or something similar.
382                hint::assert_unchecked(new_size >= old_layout.size());
383
384                let raw_ptr = realloc_nonnull(ptr, old_layout, new_size);
385                let ptr = NonNull::new(raw_ptr).ok_or(AllocError)?;
386                if zeroed {
387                    raw_ptr.add(old_size).write_bytes(0, new_size - old_size);
388                }
389                Ok(ptr.cast_slice(new_size))
390            },
391
392            // SAFETY: because `new_layout.size()` must be greater than or equal to `old_size`,
393            // both the old and new memory allocation are valid for reads and writes for `old_size`
394            // bytes. Also, because the old allocation wasn't yet deallocated, it cannot overlap
395            // `new_ptr`. Thus, the call to `copy_nonoverlapping` is safe. The safety contract
396            // for `dealloc` must be upheld by the caller.
397            old_size => unsafe {
398                let new_ptr = self.alloc_impl(new_layout, zeroed)?;
399                ptr::copy_nonoverlapping(ptr.as_ptr(), new_ptr.as_mut_ptr(), old_size);
400                self.deallocate(ptr, old_layout);
401                Ok(new_ptr)
402            },
403        }
404    }
405
406    // SAFETY: Same as `Allocator::grow`
407    #[inline]
408    #[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces
409    fn shrink_impl_runtime(
410        &self,
411        ptr: NonNull<u8>,
412        old_layout: Layout,
413        new_layout: Layout,
414        _zeroed: bool,
415    ) -> Result<NonNull<[u8]>, AllocError> {
416        debug_assert!(
417            new_layout.size() <= old_layout.size(),
418            "`new_layout.size()` must be smaller than or equal to `old_layout.size()`"
419        );
420
421        match new_layout.size() {
422            // SAFETY: conditions must be upheld by the caller
423            0 => unsafe {
424                self.deallocate(ptr, old_layout);
425                Ok(new_layout.dangling_ptr().cast_slice(0))
426            },
427
428            // SAFETY: `new_size` is non-zero. Other conditions must be upheld by the caller
429            new_size if old_layout.align() == new_layout.align() => unsafe {
430                // `realloc` probably checks for `new_size <= old_layout.size()` or something similar.
431                hint::assert_unchecked(new_size <= old_layout.size());
432
433                let raw_ptr = realloc_nonnull(ptr, old_layout, new_size);
434                let ptr = NonNull::new(raw_ptr).ok_or(AllocError)?;
435                Ok(ptr.cast_slice(new_size))
436            },
437
438            // SAFETY: because `new_size` must be smaller than or equal to `old_layout.size()`,
439            // both the old and new memory allocation are valid for reads and writes for `new_size`
440            // bytes. Also, because the old allocation wasn't yet deallocated, it cannot overlap
441            // `new_ptr`. Thus, the call to `copy_nonoverlapping` is safe. The safety contract
442            // for `dealloc` must be upheld by the caller.
443            new_size => unsafe {
444                let new_ptr = self.allocate(new_layout)?;
445                ptr::copy_nonoverlapping(ptr.as_ptr(), new_ptr.as_mut_ptr(), new_size);
446                self.deallocate(ptr, old_layout);
447                Ok(new_ptr)
448            },
449        }
450    }
451
452    // SAFETY: Same as `Allocator::allocate`
453    #[inline]
454    #[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces
455    #[rustc_const_unstable(feature = "const_heap", issue = "79597")]
456    const fn alloc_impl(&self, layout: Layout, zeroed: bool) -> Result<NonNull<[u8]>, AllocError> {
457        core::intrinsics::const_eval_select(
458            (layout, zeroed),
459            Global::alloc_impl_const,
460            Global::alloc_impl_runtime,
461        )
462    }
463
464    // SAFETY: Same as `Allocator::deallocate`
465    #[inline]
466    #[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces
467    #[rustc_const_unstable(feature = "const_heap", issue = "79597")]
468    const unsafe fn deallocate_impl(&self, ptr: NonNull<u8>, layout: Layout) {
469        core::intrinsics::const_eval_select(
470            (ptr, layout),
471            Global::deallocate_impl_const,
472            Global::deallocate_impl_runtime,
473        )
474    }
475
476    // SAFETY: Same as `Allocator::grow`
477    #[inline]
478    #[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces
479    #[rustc_const_unstable(feature = "const_heap", issue = "79597")]
480    const unsafe fn grow_impl(
481        &self,
482        ptr: NonNull<u8>,
483        old_layout: Layout,
484        new_layout: Layout,
485        zeroed: bool,
486    ) -> Result<NonNull<[u8]>, AllocError> {
487        core::intrinsics::const_eval_select(
488            (self, ptr, old_layout, new_layout, zeroed),
489            Global::grow_shrink_impl_const,
490            Global::grow_impl_runtime,
491        )
492    }
493
494    // SAFETY: Same as `Allocator::shrink`
495    #[inline]
496    #[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces
497    #[rustc_const_unstable(feature = "const_heap", issue = "79597")]
498    const unsafe fn shrink_impl(
499        &self,
500        ptr: NonNull<u8>,
501        old_layout: Layout,
502        new_layout: Layout,
503    ) -> Result<NonNull<[u8]>, AllocError> {
504        core::intrinsics::const_eval_select(
505            (self, ptr, old_layout, new_layout, false),
506            Global::grow_shrink_impl_const,
507            Global::shrink_impl_runtime,
508        )
509    }
510
511    #[inline]
512    #[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces
513    #[rustc_const_unstable(feature = "const_heap", issue = "79597")]
514    const fn alloc_impl_const(layout: Layout, zeroed: bool) -> Result<NonNull<[u8]>, AllocError> {
515        match layout.size() {
516            0 => Ok(layout.dangling_ptr().cast_slice(0)),
517            // SAFETY: `layout` is non-zero in size,
518            size => unsafe {
519                let raw_ptr = core::intrinsics::const_allocate(layout.size(), layout.align());
520                let ptr = NonNull::new(raw_ptr).ok_or(AllocError)?;
521                if zeroed {
522                    // SAFETY: the pointer returned by `const_allocate` is valid to write to.
523                    ptr.write_bytes(0, size);
524                }
525                Ok(ptr.cast_slice(size))
526            },
527        }
528    }
529
530    #[inline]
531    #[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces
532    #[rustc_const_unstable(feature = "const_heap", issue = "79597")]
533    const fn deallocate_impl_const(ptr: NonNull<u8>, layout: Layout) {
534        if layout.size() != 0 {
535            // SAFETY: We checked for nonzero size; other preconditions must be upheld by caller.
536            unsafe {
537                core::intrinsics::const_deallocate(ptr.as_ptr(), layout.size(), layout.align());
538            }
539        }
540    }
541
542    #[inline]
543    #[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces
544    #[rustc_const_unstable(feature = "const_heap", issue = "79597")]
545    const fn grow_shrink_impl_const(
546        &self,
547        ptr: NonNull<u8>,
548        old_layout: Layout,
549        new_layout: Layout,
550        zeroed: bool,
551    ) -> Result<NonNull<[u8]>, AllocError> {
552        let new_ptr = self.alloc_impl(new_layout, zeroed)?;
553        // SAFETY: both pointers are valid and this operations is in bounds.
554        unsafe {
555            ptr::copy_nonoverlapping(
556                ptr.as_ptr(),
557                new_ptr.as_mut_ptr(),
558                cmp::min(old_layout.size(), new_layout.size()),
559            );
560        }
561        // SAFETY: Caller ensures the ptr & layout are correct.
562        unsafe {
563            self.deallocate_impl(ptr, old_layout);
564        }
565        Ok(new_ptr)
566    }
567}
568
569#[stable(feature = "allocator_api", since = "1.100.0")]
570#[rustc_const_unstable(feature = "const_heap", issue = "79597")]
571const unsafe impl Allocator for Global {
572    #[inline]
573    #[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces
574    fn allocate(&self, layout: Layout) -> Result<NonNull<[u8]>, AllocError> {
575        self.alloc_impl(layout, false)
576    }
577
578    #[inline]
579    #[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces
580    fn allocate_zeroed(&self, layout: Layout) -> Result<NonNull<[u8]>, AllocError> {
581        self.alloc_impl(layout, true)
582    }
583
584    #[inline]
585    #[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces
586    unsafe fn deallocate(&self, ptr: NonNull<u8>, layout: Layout) {
587        // SAFETY: all conditions must be upheld by the caller
588        unsafe { self.deallocate_impl(ptr, layout) }
589    }
590
591    #[inline]
592    #[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces
593    unsafe fn grow(
594        &self,
595        ptr: NonNull<u8>,
596        old_layout: Layout,
597        new_layout: Layout,
598    ) -> Result<NonNull<[u8]>, AllocError> {
599        // SAFETY: all conditions must be upheld by the caller
600        unsafe { self.grow_impl(ptr, old_layout, new_layout, false) }
601    }
602
603    #[inline]
604    #[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces
605    unsafe fn grow_zeroed(
606        &self,
607        ptr: NonNull<u8>,
608        old_layout: Layout,
609        new_layout: Layout,
610    ) -> Result<NonNull<[u8]>, AllocError> {
611        // SAFETY: all conditions must be upheld by the caller
612        unsafe { self.grow_impl(ptr, old_layout, new_layout, true) }
613    }
614
615    #[inline]
616    #[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces
617    unsafe fn shrink(
618        &self,
619        ptr: NonNull<u8>,
620        old_layout: Layout,
621        new_layout: Layout,
622    ) -> Result<NonNull<[u8]>, AllocError> {
623        // SAFETY: all conditions must be upheld by the caller
624        unsafe { self.shrink_impl(ptr, old_layout, new_layout) }
625    }
626}
627
628// # Allocation error handler
629
630#[cfg(not(no_global_oom_handling))]
631unsafe extern "Rust" {
632    // This is the magic symbol to call the global alloc error handler. rustc generates
633    // it to call `__rg_oom` if there is a `#[alloc_error_handler]`, or to call the
634    // default implementations below (`__rdl_alloc_error_handler`) otherwise.
635    #[rustc_std_internal_symbol]
636    fn __rust_alloc_error_handler(size: usize, align: usize) -> !;
637}
638
639/// Signals a memory allocation error.
640///
641/// Callers of memory allocation APIs wishing to cease execution
642/// in response to an allocation error are encouraged to call this function,
643/// rather than directly invoking [`panic!`] or similar.
644///
645/// This function is guaranteed to diverge (not return normally with a value), but depending on
646/// global configuration, it may either panic (resulting in unwinding or aborting as per
647/// configuration for all panics), or abort the process (with no unwinding).
648///
649/// The default behavior is:
650///
651///  * If the binary links against `std` (typically the case), then
652///   print a message to standard error and abort the process.
653///   This behavior can be replaced with [`set_alloc_error_hook`] and [`take_alloc_error_hook`].
654///   Future versions of Rust may panic by default instead.
655///
656/// * If the binary does not link against `std` (all of its crates are marked
657///   [`#![no_std]`][no_std]), then call [`panic!`] with a message.
658///   [The panic handler] applies as to any panic.
659///
660/// [`set_alloc_error_hook`]: ../../std/alloc/fn.set_alloc_error_hook.html
661/// [`take_alloc_error_hook`]: ../../std/alloc/fn.take_alloc_error_hook.html
662/// [The panic handler]: https://doc.rust-lang.org/reference/runtime.html#the-panic_handler-attribute
663/// [no_std]: https://doc.rust-lang.org/reference/names/preludes.html#the-no_std-attribute
664#[stable(feature = "global_alloc", since = "1.28.0")]
665#[rustc_const_unstable(feature = "const_alloc_error", issue = "92523")]
666#[cfg(not(no_global_oom_handling))]
667#[cold]
668#[optimize(size)]
669pub const fn handle_alloc_error(layout: Layout) -> ! {
670    const fn ct_error(_: Layout) -> ! {
671        panic!("allocation failed");
672    }
673
674    #[inline]
675    fn rt_error(layout: Layout) -> ! {
676        // SAFETY: Safe to call; we control this function.
677        unsafe {
678            __rust_alloc_error_handler(layout.size(), layout.align());
679        }
680    }
681
682    #[cfg(not(panic = "immediate-abort"))]
683    {
684        core::intrinsics::const_eval_select((layout,), ct_error, rt_error)
685    }
686
687    #[cfg(panic = "immediate-abort")]
688    ct_error(layout)
689}
690
691#[cfg(not(no_global_oom_handling))]
692#[doc(hidden)]
693#[unstable(feature = "alloc_internals", issue = "none")]
694pub mod __alloc_error_handler {
695    // called via generated `__rust_alloc_error_handler` if there is no
696    // `#[alloc_error_handler]`.
697    #[rustc_std_internal_symbol]
698    pub unsafe fn __rdl_alloc_error_handler(size: usize, _align: usize) -> ! {
699        core::panicking::panic_nounwind_fmt(
700            format_args!("memory allocation of {size} bytes failed"),
701            /* force_no_backtrace */ false,
702        )
703    }
704}
705
706/// Allocator marker trait that is implemented only on `Global`, except when
707/// the allocator feature gate is enabled (in which case it is implemented
708/// for all allocators).
709///
710/// This is to prevent stable code from e.g. constructing `Arc<T, NotGlobal>`
711/// using the `From<Box<T, A>> for Arc<T, A>` impl.
712///
713/// Note that this trait cannot appear in specialization impls (even if not
714/// specialized on).
715///
716/// This trait should be used as a bound whenever a function constructing
717/// a type with an `#[unstable] A: Allocator = Global` parameter may be
718/// callable for `A != Global`.
719#[marker]
720#[unstable(feature = "allocator_ext", issue = "163177", implied_by = "allocator_api")]
721#[doc(hidden)]
722pub trait AllocatorNightly: Allocator {}
723
724#[unstable(feature = "allocator_ext", issue = "163177", implied_by = "allocator_api")]
725#[unstable_feature_bound(allocator_ext)]
726impl<A: Allocator + ?Sized> AllocatorNightly for A {}
727
728#[unstable(feature = "allocator_ext", issue = "163177", implied_by = "allocator_api")]
729impl AllocatorNightly for Global {}