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