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