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(#[automatically_derived]#[stable(feature = "allocator_api", since =
"1.100.0")]
impl ::core::marker::Copy for Global { }Copy, #[automatically_derived]#[stable(feature = "allocator_api", since =
"1.100.0")]
impl ::core::fmt::Debug for Global {
    #[inline]
    #[rustc_trivial_field_reads]
    fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
        ::core::fmt::Formatter::write_str(f, "Global")
    }
}Debug)]
83#[derive_const(#[automatically_derived]#[rustc_const_unstable(feature = "derive_const", issue = "143874")]#[doc(hidden)]#[stable(feature
= "allocator_api", since = "1.100.0")]
const unsafe impl ::core::clone::TrivialClone for Global { }
#[automatically_derived]#[rustc_const_unstable(feature = "derive_const", issue = "143874")]#[stable(feature
= "allocator_api", since = "1.100.0")]
const impl ::core::clone::Clone for Global {
    #[inline]
    #[rustc_trivial_field_reads]
    fn clone(&self) -> Self { *self }
}Clone, #[automatically_derived]#[rustc_const_unstable(feature = "derive_const", issue = "143874")]#[stable(feature
= "allocator_api", since = "1.100.0")]
const impl ::core::default::Default for Global {
    #[inline]
    fn default() -> Self { Global {} }
}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/// Calling [`Allocator::allocate`] on `Global` is preferred.
123///
124/// # Safety
125///
126/// See [`GlobalAlloc::alloc`].
127///
128/// # Examples
129///
130/// ```
131/// use std::alloc::{alloc, dealloc, handle_alloc_error, Layout};
132///
133/// unsafe {
134///     let layout = Layout::new::<u16>();
135///     let ptr = alloc(layout);
136///     if ptr.is_null() {
137///         handle_alloc_error(layout);
138///     }
139///
140///     *(ptr as *mut u16) = 42;
141///     assert_eq!(*(ptr as *mut u16), 42);
142///
143///     dealloc(ptr, layout);
144/// }
145/// ```
146#[stable(feature = "global_alloc", since = "1.28.0")]
147#[must_use = "losing the pointer will leak memory"]
148#[inline]
149#[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces
150pub unsafe fn alloc(layout: Layout) -> *mut u8 {
151    // SAFETY: Upheld by caller.
152    unsafe {
153        // Make sure we don't accidentally allow omitting the allocator shim in
154        // stable code until it is actually stabilized.
155        __rust_no_alloc_shim_is_unstable_v2();
156
157        __rust_alloc(layout.size(), layout.alignment())
158    }
159}
160
161/// Deallocates memory with the global allocator.
162///
163/// This function forwards calls to the [`GlobalAlloc::dealloc`] method
164/// of the allocator registered with the `#[global_allocator]` attribute
165/// if there is one, or the `std` crate’s default.
166///
167/// Note, however, that invoking this function is *not* equivalent to invoking the underlying
168/// [`GlobalAlloc::dealloc`] method of the registered allocator directly. Users of this function
169/// cannot assume anything about what the allocator does, other than the documented requirements.
170/// This means:
171///
172/// - This function may non-deterministically entirely skip the underlying allocator, e.g. if the
173///   compiler can show that this allocation can be replaced by a stack variable. The compiler may
174///   also merge multiple allocation operations into one, as long as it can also adjust all
175///   corresponding deallocation operations accordingly.
176/// - The pointer passed to this function must have been obtained by invoking [`alloc`],
177///   [`alloc_zeroed`], or [`realloc`]. In particular, passing a pointer returned by the underlying
178///   methods on [`GlobalAlloc`] is not permitted.
179/// - This function de-initializes the contents of the allocation before handing it to the allocator.
180///   So even if you know that the program previously initialized that memory, the allocator cannot
181///   rely on it being initialized.
182///
183/// Users of this function have to consider that in the future, allocators may be allowed to unwind.
184///
185/// This function is expected to be deprecated in favor of the `deallocate` method
186/// of the [`Global`] type when it and the [`Allocator`] trait become stable.
187///
188/// # Safety
189///
190/// See [`GlobalAlloc::dealloc`].
191#[stable(feature = "global_alloc", since = "1.28.0")]
192#[inline]
193#[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces
194pub unsafe fn dealloc(ptr: *mut u8, layout: Layout) {
195    // SAFETY: Upheld by caller.
196    unsafe { dealloc_nonnull(NonNull::new_unchecked(ptr), layout) }
197}
198
199/// Same as [`dealloc`] but when you already have a non-null pointer
200#[inline]
201#[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces
202unsafe fn dealloc_nonnull(ptr: NonNull<u8>, layout: Layout) {
203    // SAFETY: Upheld by caller.
204    unsafe { __rust_dealloc(ptr, layout.size(), layout.alignment()) }
205}
206
207/// Reallocates memory with the global allocator.
208///
209/// This function forwards calls to the [`GlobalAlloc::realloc`] method
210/// of the allocator registered with the `#[global_allocator]` attribute
211/// if there is one, or the `std` crate’s default.
212///
213/// Note, however, that invoking this function is *not* equivalent to invoking the underlying
214/// [`GlobalAlloc::realloc`] method of the registered allocator directly. Users of this function
215/// cannot assume anything about what the allocator does, other than the documented requirements.
216/// This means:
217///
218/// - This function may non-deterministically entirely skip the underlying allocator, e.g. if the
219///   compiler can show that this allocation can be replaced by a stack variable. The compiler may
220///   also merge multiple allocation operations into one, as long as it can also adjust all
221///   corresponding deallocation operations accordingly.
222/// - The pointer passed to this function must have been obtained by invoking [`alloc`],
223///   [`alloc_zeroed`], or [`realloc`]. In particular, passing a pointer returned by the underlying
224///   methods on [`GlobalAlloc`] is not permitted.
225/// - An allocation created by invoking this function has exactly the size and minimum alignment
226///   defined by `layout`, even if the underlying allocator makes stronger promises.
227/// - The allocation can only be freed by invoking [`dealloc`] or [`realloc`]. In particular,
228///   passing a pointer to such an allocation directly to the underlying method on [`GlobalAlloc`] is
229///   not permitted. Until one of those functions is called, it is undefined behavior to access the
230///   memory that backs this allocation with any pointer not derived from the return value of this
231///   function (e.g., with internal pointers the allocator might keep around).
232/// - If this grows the allocation, the contents of the grown part of the new allocation allocation
233///   are de-initialized by this function before returning.
234/// - If this shrinks the allocation, the contents of the removed part of the old allocation are
235///   de-initialized by this function before invoking the underlying allocator.
236///
237/// Users of this function have to consider that in the future, allocators may be allowed to unwind.
238///
239/// This function is expected to be deprecated in favor of the `grow` and `shrink` methods
240/// of the [`Global`] type when it and the [`Allocator`] trait become stable.
241///
242/// # Safety
243///
244/// See [`GlobalAlloc::realloc`].
245#[stable(feature = "global_alloc", since = "1.28.0")]
246#[must_use = "losing the pointer will leak memory"]
247#[inline]
248#[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces
249pub unsafe fn realloc(ptr: *mut u8, layout: Layout, new_size: usize) -> *mut u8 {
250    // SAFETY: Upheld by caller.
251    unsafe { realloc_nonnull(NonNull::new_unchecked(ptr), layout, new_size) }
252}
253
254/// Same as [`realloc`] but when you already have a non-null pointer
255#[inline]
256#[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces
257unsafe fn realloc_nonnull(ptr: NonNull<u8>, layout: Layout, new_size: usize) -> *mut u8 {
258    // SAFETY: Upheld by caller.
259    unsafe { __rust_realloc(ptr, layout.size(), layout.alignment(), new_size) }
260}
261
262/// Allocates zero-initialized memory with the global allocator.
263///
264/// This function forwards calls to the [`GlobalAlloc::alloc_zeroed`] method
265/// of the allocator registered with the `#[global_allocator]` attribute
266/// if there is one, or the `std` crate’s default.
267///
268/// Note, however, that invoking this function is *not* equivalent to invoking the underlying
269/// [`GlobalAlloc::alloc_zeroed`] method of the registered allocator directly. Users of this
270/// function cannot assume anything about what the allocator does, other than the documented
271/// requirements. This means:
272///
273/// - This function may non-deterministically entirely skip the underlying allocator, e.g. if the
274///   compiler can show that this allocation can be replaced by a stack variable. The compiler may
275///   also merge multiple allocation operations into one, as long as it can also adjust all
276///   corresponding deallocation operations accordingly.
277/// - The allocation can only be freed by invoking [`dealloc`] or [`realloc`]. In particular,
278///   passing a pointer to such an allocation directly to the underlying method on [`GlobalAlloc`] is
279///   not permitted. Until one of those functions is called, it is undefined behavior to access the
280///   memory that backs this allocation with any pointer not derived from the return value of this
281///   function (e.g., with internal pointers the allocator might keep around).
282/// - An allocation created by invoking this function has exactly the size and minimum alignment
283///   defined by `layout`, even if the underlying allocator makes stronger promises.
284///
285/// Users of this function have to consider that in the future, allocators may be allowed to unwind.
286///
287/// This function is expected to be deprecated in favor of the `allocate_zeroed` method
288/// of the [`Global`] type when it and the [`Allocator`] trait become stable.
289///
290/// # Safety
291///
292/// See [`GlobalAlloc::alloc_zeroed`].
293///
294/// # Examples
295///
296/// ```
297/// use std::alloc::{alloc_zeroed, dealloc, handle_alloc_error, Layout};
298///
299/// unsafe {
300///     let layout = Layout::new::<u16>();
301///     let ptr = alloc_zeroed(layout);
302///     if ptr.is_null() {
303///         handle_alloc_error(layout);
304///     }
305///
306///     assert_eq!(*(ptr as *mut u16), 0);
307///
308///     dealloc(ptr, layout);
309/// }
310/// ```
311#[stable(feature = "global_alloc", since = "1.28.0")]
312#[must_use = "losing the pointer will leak memory"]
313#[inline]
314#[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces
315pub unsafe fn alloc_zeroed(layout: Layout) -> *mut u8 {
316    // SAFETY: Upheld by caller.
317    unsafe {
318        // Make sure we don't accidentally allow omitting the allocator shim in
319        // stable code until it is actually stabilized.
320        __rust_no_alloc_shim_is_unstable_v2();
321
322        __rust_alloc_zeroed(layout.size(), layout.alignment())
323    }
324}
325
326impl Global {
327    #[inline]
328    #[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces
329    fn alloc_impl_runtime(layout: Layout, zeroed: bool) -> Result<NonNull<[u8]>, AllocError> {
330        match layout.size() {
331            0 => Ok(layout.dangling_ptr().cast_slice(0)),
332            // SAFETY: `layout` is non-zero in size,
333            size => unsafe {
334                let raw_ptr = if zeroed { alloc_zeroed(layout) } else { alloc(layout) };
335                let ptr = NonNull::new(raw_ptr).ok_or(AllocError)?;
336                Ok(ptr.cast_slice(size))
337            },
338        }
339    }
340
341    #[inline]
342    #[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces
343    fn deallocate_impl_runtime(ptr: NonNull<u8>, layout: Layout) {
344        if layout.size() != 0 {
345            // SAFETY:
346            // * We have checked that `layout` is non-zero in size.
347            // * The caller is obligated to provide a layout that "fits", and in this case,
348            //   "fit" always means a layout that is equal to the original, because our
349            //   `allocate()`, `grow()`, and `shrink()` implementations never returns a larger
350            //   allocation than requested.
351            // * Other conditions must be upheld by the caller, as per `Allocator::deallocate()`'s
352            //   safety documentation.
353            unsafe { dealloc_nonnull(ptr, layout) }
354        }
355    }
356
357    // SAFETY: Same as `Allocator::grow`
358    #[inline]
359    #[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces
360    fn grow_impl_runtime(
361        &self,
362        ptr: NonNull<u8>,
363        old_layout: Layout,
364        new_layout: Layout,
365        zeroed: bool,
366    ) -> Result<NonNull<[u8]>, AllocError> {
367        if true {
    if !(new_layout.size() >= old_layout.size()) {
        {
            ::core::panicking::panic_fmt(format_args!("`new_layout.size()` must be greater than or equal to `old_layout.size()`"));
        }
    };
};debug_assert!(
368            new_layout.size() >= old_layout.size(),
369            "`new_layout.size()` must be greater than or equal to `old_layout.size()`"
370        );
371
372        match old_layout.size() {
373            0 => self.alloc_impl(new_layout, zeroed),
374
375            // SAFETY: `new_size` is non-zero as `old_size` is greater than or equal to `new_size`
376            // as required by safety conditions. Other conditions must be upheld by the caller
377            old_size if old_layout.align() == new_layout.align() => unsafe {
378                let new_size = new_layout.size();
379
380                // `realloc` probably checks for `new_size >= old_layout.size()` or something similar.
381                hint::assert_unchecked(new_size >= old_layout.size());
382
383                let raw_ptr = realloc_nonnull(ptr, old_layout, new_size);
384                let ptr = NonNull::new(raw_ptr).ok_or(AllocError)?;
385                if zeroed {
386                    raw_ptr.add(old_size).write_bytes(0, new_size - old_size);
387                }
388                Ok(ptr.cast_slice(new_size))
389            },
390
391            // SAFETY: because `new_layout.size()` must be greater than or equal to `old_size`,
392            // both the old and new memory allocation are valid for reads and writes for `old_size`
393            // bytes. Also, because the old allocation wasn't yet deallocated, it cannot overlap
394            // `new_ptr`. Thus, the call to `copy_nonoverlapping` is safe. The safety contract
395            // for `dealloc` must be upheld by the caller.
396            old_size => unsafe {
397                let new_ptr = self.alloc_impl(new_layout, zeroed)?;
398                ptr::copy_nonoverlapping(ptr.as_ptr(), new_ptr.as_mut_ptr(), old_size);
399                self.deallocate(ptr, old_layout);
400                Ok(new_ptr)
401            },
402        }
403    }
404
405    // SAFETY: Same as `Allocator::grow`
406    #[inline]
407    #[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces
408    fn shrink_impl_runtime(
409        &self,
410        ptr: NonNull<u8>,
411        old_layout: Layout,
412        new_layout: Layout,
413        _zeroed: bool,
414    ) -> Result<NonNull<[u8]>, AllocError> {
415        if true {
    if !(new_layout.size() <= old_layout.size()) {
        {
            ::core::panicking::panic_fmt(format_args!("`new_layout.size()` must be smaller than or equal to `old_layout.size()`"));
        }
    };
};debug_assert!(
416            new_layout.size() <= old_layout.size(),
417            "`new_layout.size()` must be smaller than or equal to `old_layout.size()`"
418        );
419
420        match new_layout.size() {
421            // SAFETY: conditions must be upheld by the caller
422            0 => unsafe {
423                self.deallocate(ptr, old_layout);
424                Ok(new_layout.dangling_ptr().cast_slice(0))
425            },
426
427            // SAFETY: `new_size` is non-zero. Other conditions must be upheld by the caller
428            new_size if old_layout.align() == new_layout.align() => unsafe {
429                // `realloc` probably checks for `new_size <= old_layout.size()` or something similar.
430                hint::assert_unchecked(new_size <= old_layout.size());
431
432                let raw_ptr = realloc_nonnull(ptr, old_layout, new_size);
433                let ptr = NonNull::new(raw_ptr).ok_or(AllocError)?;
434                Ok(ptr.cast_slice(new_size))
435            },
436
437            // SAFETY: because `new_size` must be smaller than or equal to `old_layout.size()`,
438            // both the old and new memory allocation are valid for reads and writes for `new_size`
439            // bytes. Also, because the old allocation wasn't yet deallocated, it cannot overlap
440            // `new_ptr`. Thus, the call to `copy_nonoverlapping` is safe. The safety contract
441            // for `dealloc` must be upheld by the caller.
442            new_size => unsafe {
443                let new_ptr = self.allocate(new_layout)?;
444                ptr::copy_nonoverlapping(ptr.as_ptr(), new_ptr.as_mut_ptr(), new_size);
445                self.deallocate(ptr, old_layout);
446                Ok(new_ptr)
447            },
448        }
449    }
450
451    // SAFETY: Same as `Allocator::allocate`
452    #[inline]
453    #[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces
454    #[rustc_const_unstable(feature = "const_heap", issue = "79597")]
455    const fn alloc_impl(&self, layout: Layout, zeroed: bool) -> Result<NonNull<[u8]>, AllocError> {
456        core::intrinsics::const_eval_select(
457            (layout, zeroed),
458            Global::alloc_impl_const,
459            Global::alloc_impl_runtime,
460        )
461    }
462
463    // SAFETY: Same as `Allocator::deallocate`
464    #[inline]
465    #[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces
466    #[rustc_const_unstable(feature = "const_heap", issue = "79597")]
467    const unsafe fn deallocate_impl(&self, ptr: NonNull<u8>, layout: Layout) {
468        core::intrinsics::const_eval_select(
469            (ptr, layout),
470            Global::deallocate_impl_const,
471            Global::deallocate_impl_runtime,
472        )
473    }
474
475    // SAFETY: Same as `Allocator::grow`
476    #[inline]
477    #[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces
478    #[rustc_const_unstable(feature = "const_heap", issue = "79597")]
479    const unsafe fn grow_impl(
480        &self,
481        ptr: NonNull<u8>,
482        old_layout: Layout,
483        new_layout: Layout,
484        zeroed: bool,
485    ) -> Result<NonNull<[u8]>, AllocError> {
486        core::intrinsics::const_eval_select(
487            (self, ptr, old_layout, new_layout, zeroed),
488            Global::grow_shrink_impl_const,
489            Global::grow_impl_runtime,
490        )
491    }
492
493    // SAFETY: Same as `Allocator::shrink`
494    #[inline]
495    #[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces
496    #[rustc_const_unstable(feature = "const_heap", issue = "79597")]
497    const unsafe fn shrink_impl(
498        &self,
499        ptr: NonNull<u8>,
500        old_layout: Layout,
501        new_layout: Layout,
502    ) -> Result<NonNull<[u8]>, AllocError> {
503        core::intrinsics::const_eval_select(
504            (self, ptr, old_layout, new_layout, false),
505            Global::grow_shrink_impl_const,
506            Global::shrink_impl_runtime,
507        )
508    }
509
510    #[inline]
511    #[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces
512    #[rustc_const_unstable(feature = "const_heap", issue = "79597")]
513    const fn alloc_impl_const(layout: Layout, zeroed: bool) -> Result<NonNull<[u8]>, AllocError> {
514        match layout.size() {
515            0 => Ok(layout.dangling_ptr().cast_slice(0)),
516            // SAFETY: `layout` is non-zero in size,
517            size => unsafe {
518                let raw_ptr = core::intrinsics::const_allocate(layout.size(), layout.align());
519                let ptr = NonNull::new(raw_ptr).ok_or(AllocError)?;
520                if zeroed {
521                    // SAFETY: the pointer returned by `const_allocate` is valid to write to.
522                    ptr.write_bytes(0, size);
523                }
524                Ok(ptr.cast_slice(size))
525            },
526        }
527    }
528
529    #[inline]
530    #[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces
531    #[rustc_const_unstable(feature = "const_heap", issue = "79597")]
532    const fn deallocate_impl_const(ptr: NonNull<u8>, layout: Layout) {
533        if layout.size() != 0 {
534            // SAFETY: We checked for nonzero size; other preconditions must be upheld by caller.
535            unsafe {
536                core::intrinsics::const_deallocate(ptr.as_ptr(), layout.size(), layout.align());
537            }
538        }
539    }
540
541    #[inline]
542    #[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces
543    #[rustc_const_unstable(feature = "const_heap", issue = "79597")]
544    const fn grow_shrink_impl_const(
545        &self,
546        ptr: NonNull<u8>,
547        old_layout: Layout,
548        new_layout: Layout,
549        zeroed: bool,
550    ) -> Result<NonNull<[u8]>, AllocError> {
551        let new_ptr = self.alloc_impl(new_layout, zeroed)?;
552        // SAFETY: both pointers are valid and this operations is in bounds.
553        unsafe {
554            ptr::copy_nonoverlapping(
555                ptr.as_ptr(),
556                new_ptr.as_mut_ptr(),
557                cmp::min(old_layout.size(), new_layout.size()),
558            );
559        }
560        // SAFETY: Caller ensures the ptr & layout are correct.
561        unsafe {
562            self.deallocate_impl(ptr, old_layout);
563        }
564        Ok(new_ptr)
565    }
566}
567
568#[stable(feature = "allocator_api", since = "1.100.0")]
569#[rustc_const_unstable(feature = "const_heap", issue = "79597")]
570const unsafe impl Allocator for Global {
571    #[inline]
572    #[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces
573    fn allocate(&self, layout: Layout) -> Result<NonNull<[u8]>, AllocError> {
574        self.alloc_impl(layout, false)
575    }
576
577    #[inline]
578    #[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces
579    fn allocate_zeroed(&self, layout: Layout) -> Result<NonNull<[u8]>, AllocError> {
580        self.alloc_impl(layout, true)
581    }
582
583    #[inline]
584    #[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces
585    unsafe fn deallocate(&self, ptr: NonNull<u8>, layout: Layout) {
586        // SAFETY: all conditions must be upheld by the caller
587        unsafe { self.deallocate_impl(ptr, layout) }
588    }
589
590    #[inline]
591    #[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces
592    unsafe fn grow(
593        &self,
594        ptr: NonNull<u8>,
595        old_layout: Layout,
596        new_layout: Layout,
597    ) -> Result<NonNull<[u8]>, AllocError> {
598        // SAFETY: all conditions must be upheld by the caller
599        unsafe { self.grow_impl(ptr, old_layout, new_layout, false) }
600    }
601
602    #[inline]
603    #[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces
604    unsafe fn grow_zeroed(
605        &self,
606        ptr: NonNull<u8>,
607        old_layout: Layout,
608        new_layout: Layout,
609    ) -> Result<NonNull<[u8]>, AllocError> {
610        // SAFETY: all conditions must be upheld by the caller
611        unsafe { self.grow_impl(ptr, old_layout, new_layout, true) }
612    }
613
614    #[inline]
615    #[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces
616    unsafe fn shrink(
617        &self,
618        ptr: NonNull<u8>,
619        old_layout: Layout,
620        new_layout: Layout,
621    ) -> Result<NonNull<[u8]>, AllocError> {
622        // SAFETY: all conditions must be upheld by the caller
623        unsafe { self.shrink_impl(ptr, old_layout, new_layout) }
624    }
625}
626
627// # Allocation error handler
628
629#[cfg(not(no_global_oom_handling))]
630unsafe extern "Rust" {
631    // This is the magic symbol to call the global alloc error handler. rustc generates
632    // it to call `__rg_oom` if there is a `#[alloc_error_handler]`, or to call the
633    // default implementations below (`__rdl_alloc_error_handler`) otherwise.
634    #[rustc_std_internal_symbol]
635    fn __rust_alloc_error_handler(size: usize, align: usize) -> !;
636}
637
638/// Signals a memory allocation error.
639///
640/// Callers of memory allocation APIs wishing to cease execution
641/// in response to an allocation error are encouraged to call this function,
642/// rather than directly invoking [`panic!`] or similar.
643///
644/// This function is guaranteed to diverge (not return normally with a value), but depending on
645/// global configuration, it may either panic (resulting in unwinding or aborting as per
646/// configuration for all panics), or abort the process (with no unwinding).
647///
648/// The default behavior is:
649///
650///  * If the binary links against `std` (typically the case), then
651///   print a message to standard error and abort the process.
652///   This behavior can be replaced with [`set_alloc_error_hook`] and [`take_alloc_error_hook`].
653///   Future versions of Rust may panic by default instead.
654///
655/// * If the binary does not link against `std` (all of its crates are marked
656///   [`#![no_std]`][no_std]), then call [`panic!`] with a message.
657///   [The panic handler] applies as to any panic.
658///
659/// [`set_alloc_error_hook`]: ../../std/alloc/fn.set_alloc_error_hook.html
660/// [`take_alloc_error_hook`]: ../../std/alloc/fn.take_alloc_error_hook.html
661/// [The panic handler]: https://doc.rust-lang.org/reference/runtime.html#the-panic_handler-attribute
662/// [no_std]: https://doc.rust-lang.org/reference/names/preludes.html#the-no_std-attribute
663#[stable(feature = "global_alloc", since = "1.28.0")]
664#[rustc_const_unstable(feature = "const_alloc_error", issue = "92523")]
665#[cfg(not(no_global_oom_handling))]
666#[cold]
667#[optimize(size)]
668pub const fn handle_alloc_error(layout: Layout) -> ! {
669    const fn ct_error(_: Layout) -> ! {
670        { ::core::panicking::panic_fmt(format_args!("allocation failed")); };panic!("allocation failed");
671    }
672
673    #[inline]
674    fn rt_error(layout: Layout) -> ! {
675        // SAFETY: Safe to call; we control this function.
676        unsafe {
677            __rust_alloc_error_handler(layout.size(), layout.align());
678        }
679    }
680
681    #[cfg(not(panic = "immediate-abort"))]
682    {
683        core::intrinsics::const_eval_select((layout,), ct_error, rt_error)
684    }
685
686    #[cfg(panic = "immediate-abort")]
687    ct_error(layout)
688}
689
690#[cfg(not(no_global_oom_handling))]
691#[doc(hidden)]
692#[unstable(feature = "alloc_internals", issue = "none")]
693pub mod __alloc_error_handler {
694    // called via generated `__rust_alloc_error_handler` if there is no
695    // `#[alloc_error_handler]`.
696    #[rustc_std_internal_symbol]
697    pub unsafe fn __rdl_alloc_error_handler(size: usize, _align: usize) -> ! {
698        core::panicking::panic_nounwind_fmt(
699            format_args!("memory allocation of {0} bytes failed", size)format_args!("memory allocation of {size} bytes failed"),
700            /* force_no_backtrace */ false,
701        )
702    }
703}
704
705#[unstable(feature = "allocator_ext", issue = "163177", implied_by = "allocator_api")]
706impl AllocatorNightly for Global {}