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