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