Skip to main content

std/
alloc.rs

1//! Memory allocation APIs.
2//!
3//! In a given program, the standard library has one “global” memory allocator
4//! that is used for example by `Box<T>` and `Vec<T>`.
5//!
6//! Currently the default global allocator is unspecified. Libraries, however,
7//! like `cdylib`s and `staticlib`s are guaranteed to use the [`System`] by
8//! default.
9//!
10//! # The `#[global_allocator]` attribute
11//!
12//! This attribute allows configuring the choice of global allocator.
13//! You can use this to implement a completely custom global allocator
14//! to route all[^system-alloc] default allocation requests to a custom object.
15//!
16//! ```rust
17//! use std::alloc::{GlobalAlloc, System, Layout};
18//!
19//! struct MyAllocator;
20//!
21//! unsafe impl GlobalAlloc for MyAllocator {
22//!     unsafe fn alloc(&self, layout: Layout) -> *mut u8 {
23//!         unsafe { System.alloc(layout) }
24//!     }
25//!
26//!     unsafe fn dealloc(&self, ptr: *mut u8, layout: Layout) {
27//!         unsafe { System.dealloc(ptr, layout) }
28//!     }
29//! }
30//!
31//! #[global_allocator]
32//! static GLOBAL: MyAllocator = MyAllocator;
33//!
34//! fn main() {
35//!     // This `Vec` will allocate memory through `GLOBAL` above
36//!     let mut v = Vec::new();
37//!     v.push(1);
38//! }
39//! ```
40//!
41//! The attribute is used on a `static` item whose type implements the
42//! [`GlobalAlloc`] trait. This type can be provided by an external library:
43//!
44//! ```rust,ignore (demonstrates crates.io usage)
45//! use jemallocator::Jemalloc;
46//!
47//! #[global_allocator]
48//! static GLOBAL: Jemalloc = Jemalloc;
49//!
50//! fn main() {}
51//! ```
52//!
53//! The `#[global_allocator]` can only be used once in a crate
54//! or its recursive dependencies.
55//!
56//! [^system-alloc]: Note that the Rust standard library internals may still
57//! directly call [`System`] when necessary (for example for the runtime
58//! support typically required to implement a global allocator, see [re-entrance] on [`GlobalAlloc`]
59//! for more details).
60//!
61//! [re-entrance]: trait.GlobalAlloc.html#re-entrance
62
63#![deny(unsafe_op_in_unsafe_fn)]
64#![stable(feature = "alloc_module", since = "1.28.0")]
65
66#[stable(feature = "alloc_module", since = "1.28.0")]
67#[doc(inline)]
68pub use alloc_crate::alloc::*;
69
70use crate::ptr::NonNull;
71use crate::sync::atomic::{AtomicBool, AtomicPtr, Ordering};
72use crate::sys::alloc as imp;
73use crate::{hint, mem, ptr};
74
75/// The default memory allocator provided by the operating system.
76///
77/// This is based on `malloc` on Unix platforms and `HeapAlloc` on Windows,
78/// plus related functions. However, it is not valid to mix use of the backing
79/// system allocator with `System`, as this implementation may include extra
80/// work, such as to serve alignment requests greater than the alignment
81/// provided directly by the backing system allocator.
82///
83/// This type implements the [`GlobalAlloc`] trait. Currently the default
84/// global allocator is unspecified. Libraries, however, like `cdylib`s and
85/// `staticlib`s are guaranteed to use the [`System`] by default and as such
86/// work as if they had this definition:
87///
88/// ```rust
89/// use std::alloc::System;
90///
91/// #[global_allocator]
92/// static A: System = System;
93///
94/// fn main() {
95///     let a = Box::new(4); // Allocates from the system allocator.
96///     println!("{a}");
97/// }
98/// ```
99///
100/// You can also define your own wrapper around `System` if you'd like, such as
101/// keeping track of the number of all bytes allocated:
102///
103/// ```rust
104/// use std::alloc::{System, GlobalAlloc, Layout};
105/// use std::sync::atomic::{AtomicUsize, Ordering::Relaxed};
106///
107/// struct Counter;
108///
109/// static ALLOCATED: AtomicUsize = AtomicUsize::new(0);
110///
111/// unsafe impl GlobalAlloc for Counter {
112///     unsafe fn alloc(&self, layout: Layout) -> *mut u8 {
113///         let ret = unsafe { System.alloc(layout) };
114///         if !ret.is_null() {
115///             ALLOCATED.fetch_add(layout.size(), Relaxed);
116///         }
117///         ret
118///     }
119///
120///     unsafe fn dealloc(&self, ptr: *mut u8, layout: Layout) {
121///         unsafe { System.dealloc(ptr, layout); }
122///         ALLOCATED.fetch_sub(layout.size(), Relaxed);
123///     }
124/// }
125///
126/// #[global_allocator]
127/// static A: Counter = Counter;
128///
129/// fn main() {
130///     println!("allocated bytes before main: {}", ALLOCATED.load(Relaxed));
131/// }
132/// ```
133///
134/// It can also be used directly to allocate memory independently of whatever
135/// global allocator has been selected for a Rust program. For example if a Rust
136/// program opts in to using jemalloc as the global allocator, `System` will
137/// still allocate memory using `malloc` and `HeapAlloc`.
138#[stable(feature = "alloc_system_type", since = "1.28.0")]
139#[derive(Copy, Debug)]
140#[derive_const(Clone, Default)]
141pub struct System;
142
143impl System {
144    #[inline]
145    fn alloc_impl(&self, layout: Layout, zeroed: bool) -> Result<NonNull<[u8]>, AllocError> {
146        match layout.size() {
147            0 => Ok(layout.dangling_ptr().cast_slice(0)),
148            // SAFETY: `layout` is non-zero in size,
149            size => unsafe {
150                let raw_ptr = if zeroed { imp::alloc_zeroed(layout) } else { imp::alloc(layout) };
151                let ptr = NonNull::new(raw_ptr).ok_or(AllocError)?;
152                Ok(ptr.cast_slice(size))
153            },
154        }
155    }
156
157    // SAFETY: Same as `Allocator::grow`
158    #[inline]
159    unsafe fn grow_impl(
160        &self,
161        ptr: NonNull<u8>,
162        old_layout: Layout,
163        new_layout: Layout,
164        zeroed: bool,
165    ) -> Result<NonNull<[u8]>, AllocError> {
166        debug_assert!(
167            new_layout.size() >= old_layout.size(),
168            "`new_layout.size()` must be greater than or equal to `old_layout.size()`"
169        );
170
171        match old_layout.size() {
172            0 => self.alloc_impl(new_layout, zeroed),
173
174            // SAFETY: `new_size` is non-zero as `new_size` is greater than or equal to `old_size`
175            // as required by safety conditions and the `old_size == 0` case was handled in the
176            // previous match arm. Other conditions must be upheld by the caller
177            old_size if old_layout.align() == new_layout.align() => unsafe {
178                let new_size = new_layout.size();
179
180                // `realloc` probably checks for `new_size >= old_layout.size()` or something similar.
181                hint::assert_unchecked(new_size >= old_layout.size());
182
183                let raw_ptr = imp::realloc(ptr.as_ptr(), old_layout, new_size);
184                let ptr = NonNull::new(raw_ptr).ok_or(AllocError)?;
185                if zeroed {
186                    raw_ptr.add(old_size).write_bytes(0, new_size - old_size);
187                }
188                Ok(ptr.cast_slice(new_size))
189            },
190
191            // SAFETY: because `new_layout.size()` must be greater than or equal to `old_size`,
192            // both the old and new memory allocation are valid for reads and writes for `old_size`
193            // bytes. Also, because the old allocation wasn't yet deallocated, it cannot overlap
194            // `new_ptr`. Thus, the call to `copy_nonoverlapping` is safe. The safety contract
195            // for `dealloc` must be upheld by the caller.
196            old_size => unsafe {
197                let new_ptr = self.alloc_impl(new_layout, zeroed)?;
198                ptr::copy_nonoverlapping(ptr.as_ptr(), new_ptr.as_mut_ptr(), old_size);
199                Allocator::deallocate(self, ptr, old_layout);
200                Ok(new_ptr)
201            },
202        }
203    }
204}
205
206// The Allocator impl checks the layout size to be non-zero and forwards to the
207// platform functions in `std::sys::*::alloc`.
208#[unstable(feature = "allocator_api", issue = "32838")]
209unsafe impl Allocator for System {
210    #[inline]
211    fn allocate(&self, layout: Layout) -> Result<NonNull<[u8]>, AllocError> {
212        self.alloc_impl(layout, false)
213    }
214
215    #[inline]
216    fn allocate_zeroed(&self, layout: Layout) -> Result<NonNull<[u8]>, AllocError> {
217        self.alloc_impl(layout, true)
218    }
219
220    #[inline]
221    unsafe fn deallocate(&self, ptr: NonNull<u8>, layout: Layout) {
222        if layout.size() != 0 {
223            // SAFETY: `layout` is non-zero in size,
224            // other conditions must be upheld by the caller
225            unsafe { imp::dealloc(ptr.as_ptr(), layout) }
226        }
227    }
228
229    #[inline]
230    unsafe fn grow(
231        &self,
232        ptr: NonNull<u8>,
233        old_layout: Layout,
234        new_layout: Layout,
235    ) -> Result<NonNull<[u8]>, AllocError> {
236        // SAFETY: all conditions must be upheld by the caller
237        unsafe { self.grow_impl(ptr, old_layout, new_layout, false) }
238    }
239
240    #[inline]
241    unsafe fn grow_zeroed(
242        &self,
243        ptr: NonNull<u8>,
244        old_layout: Layout,
245        new_layout: Layout,
246    ) -> Result<NonNull<[u8]>, AllocError> {
247        // SAFETY: all conditions must be upheld by the caller
248        unsafe { self.grow_impl(ptr, old_layout, new_layout, true) }
249    }
250
251    #[inline]
252    unsafe fn shrink(
253        &self,
254        ptr: NonNull<u8>,
255        old_layout: Layout,
256        new_layout: Layout,
257    ) -> Result<NonNull<[u8]>, AllocError> {
258        debug_assert!(
259            new_layout.size() <= old_layout.size(),
260            "`new_layout.size()` must be smaller than or equal to `old_layout.size()`"
261        );
262
263        match new_layout.size() {
264            // SAFETY: conditions must be upheld by the caller
265            0 => unsafe {
266                Allocator::deallocate(self, ptr, old_layout);
267                Ok(new_layout.dangling_ptr().cast_slice(0))
268            },
269
270            // SAFETY: `new_size` is non-zero. Other conditions must be upheld by the caller
271            new_size if old_layout.align() == new_layout.align() => unsafe {
272                // `realloc` probably checks for `new_size <= old_layout.size()` or something similar.
273                hint::assert_unchecked(new_size <= old_layout.size());
274
275                let raw_ptr = imp::realloc(ptr.as_ptr(), old_layout, new_size);
276                let ptr = NonNull::new(raw_ptr).ok_or(AllocError)?;
277                Ok(ptr.cast_slice(new_size))
278            },
279
280            // SAFETY: because `new_size` must be smaller than or equal to `old_layout.size()`,
281            // both the old and new memory allocation are valid for reads and writes for `new_size`
282            // bytes. Also, because the old allocation wasn't yet deallocated, it cannot overlap
283            // `new_ptr`. Thus, the call to `copy_nonoverlapping` is safe. The safety contract
284            // for `dealloc` must be upheld by the caller.
285            new_size => unsafe {
286                let new_ptr = Allocator::allocate(self, new_layout)?;
287                ptr::copy_nonoverlapping(ptr.as_ptr(), new_ptr.as_mut_ptr(), new_size);
288                Allocator::deallocate(self, ptr, old_layout);
289                Ok(new_ptr)
290            },
291        }
292    }
293}
294
295#[unstable(feature = "allocator_api", issue = "32838")]
296unsafe impl GlobalAllocator for System {}
297
298static HOOK: AtomicPtr<()> = AtomicPtr::new(ptr::null_mut());
299
300/// Registers a custom allocation error hook, replacing any that was previously registered.
301///
302/// The allocation error hook is invoked when an infallible memory allocation fails — that is,
303/// as a consequence of calling [`handle_alloc_error`] — before the runtime aborts.
304///
305/// The allocation error hook is a global resource. [`take_alloc_error_hook`] may be used to
306/// retrieve a previously registered hook and wrap or discard it.
307///
308/// # What the provided `hook` function should expect
309///
310/// The hook function is provided with a [`Layout`] struct which contains information
311/// about the allocation that failed.
312///
313/// The hook function may choose to panic or abort; in the event that it returns normally, this
314/// will cause an immediate abort.
315///
316/// Since [`take_alloc_error_hook`] is a safe function that allows retrieving the hook, the hook
317/// function must be _sound_ to call even if no memory allocations were attempted.
318///
319/// # The default hook
320///
321/// The default hook, used if [`set_alloc_error_hook`] is never called, prints a message to
322/// standard error (and then returns, causing the runtime to abort the process).
323/// Compiler options may cause it to panic instead, and the default behavior may be changed
324/// to panicking in future versions of Rust.
325///
326/// # Examples
327///
328/// ```
329/// #![feature(alloc_error_hook)]
330///
331/// use std::alloc::{Layout, set_alloc_error_hook};
332///
333/// fn custom_alloc_error_hook(layout: Layout) {
334///    panic!("memory allocation of {} bytes failed", layout.size());
335/// }
336///
337/// set_alloc_error_hook(custom_alloc_error_hook);
338/// ```
339#[unstable(feature = "alloc_error_hook", issue = "51245")]
340pub fn set_alloc_error_hook(hook: fn(Layout)) {
341    HOOK.store(hook as *mut (), Ordering::Release);
342}
343
344/// Unregisters the current allocation error hook, returning it.
345///
346/// *See also the function [`set_alloc_error_hook`].*
347///
348/// If no custom hook is registered, the default hook will be returned.
349#[unstable(feature = "alloc_error_hook", issue = "51245")]
350pub fn take_alloc_error_hook() -> fn(Layout) {
351    let hook = HOOK.swap(ptr::null_mut(), Ordering::Acquire);
352    if hook.is_null() { default_alloc_error_hook } else { unsafe { mem::transmute(hook) } }
353}
354
355#[optimize(size)]
356fn default_alloc_error_hook(layout: Layout) {
357    if cfg!(panic = "immediate-abort") {
358        return;
359    }
360
361    // This is the default path taken on OOM, and the only path taken on stable with std.
362    // Crucially, it does *not* call any user-defined code, and therefore users do not have to
363    // worry about allocation failure causing reentrancy issues. That makes it different from
364    // the default `__rdl_alloc_error_handler` defined in alloc (i.e., the default alloc error
365    // handler that is  called when there is no `#[alloc_error_handler]`), which triggers a
366    // regular panic and thus can invoke a user-defined panic hook, executing arbitrary
367    // user-defined code.
368
369    static PREV_ALLOC_FAILURE: AtomicBool = AtomicBool::new(false);
370    if PREV_ALLOC_FAILURE.swap(true, Ordering::Relaxed) {
371        // Don't try to print a backtrace if a previous alloc error happened. This likely means
372        // there is not enough memory to print a backtrace, although it could also mean that two
373        // threads concurrently run out of memory.
374        rtprintpanic!(
375            "memory allocation of {} bytes failed\nskipping backtrace printing to avoid potential recursion\n",
376            layout.size()
377        );
378        return;
379    } else {
380        rtprintpanic!("memory allocation of {} bytes failed\n", layout.size());
381    }
382
383    let Some(mut out) = crate::sys::stdio::panic_output() else {
384        return;
385    };
386
387    // Use a lock to prevent mixed output in multithreading context.
388    // Some platforms also require it when printing a backtrace, like `SymFromAddr` on Windows.
389    // Make sure to not take this lock until after checking PREV_ALLOC_FAILURE to avoid deadlocks
390    // when there is too little memory to print a backtrace.
391    let mut lock = crate::sys::backtrace::lock();
392
393    match crate::panic::get_backtrace_style() {
394        Some(crate::panic::BacktraceStyle::Short) => {
395            drop(lock.print(&mut out, crate::backtrace_rs::PrintFmt::Short))
396        }
397        Some(crate::panic::BacktraceStyle::Full) => {
398            drop(lock.print(&mut out, crate::backtrace_rs::PrintFmt::Full))
399        }
400        Some(crate::panic::BacktraceStyle::Off) => {
401            use crate::io::Write;
402            let _ = writeln!(
403                out,
404                "note: run with `RUST_BACKTRACE=1` environment variable to display a \
405                             backtrace"
406            );
407            if cfg!(miri) {
408                let _ = writeln!(
409                    out,
410                    "note: in Miri, you may have to set `MIRIFLAGS=-Zmiri-env-forward=RUST_BACKTRACE` \
411                                for the environment variable to have an effect"
412                );
413            }
414        }
415        // If backtraces aren't supported or are forced-off, do nothing.
416        None => {}
417    }
418}
419
420#[cfg(not(test))]
421#[doc(hidden)]
422#[alloc_error_handler]
423#[unstable(feature = "alloc_internals", issue = "none")]
424pub fn rust_oom(layout: Layout) -> ! {
425    crate::sys::backtrace::__rust_end_short_backtrace(|| {
426        let hook = HOOK.load(Ordering::Acquire);
427        let hook: fn(Layout) =
428            if hook.is_null() { default_alloc_error_hook } else { unsafe { mem::transmute(hook) } };
429        hook(layout);
430        crate::process::abort()
431    })
432}
433
434#[cfg(not(test))]
435#[doc(hidden)]
436#[allow(unused_attributes)]
437#[unstable(feature = "alloc_internals", issue = "none")]
438pub mod __default_lib_allocator {
439    use super::Layout;
440    // We call the system functions directly to avoid any overheads introduced
441    // by the roundtrip through `impl Allocator for System` and
442    // `impl<A: GlobalAllocator> GlobalAlloc for A`.
443    use crate::sys::alloc as imp;
444
445    // These magic symbol names are used as a fallback for implementing the
446    // `__rust_alloc` etc symbols (see `src/liballoc/alloc.rs`) when there is
447    // no `#[global_allocator]` attribute.
448
449    // for symbol names src/librustc_ast/expand/allocator.rs
450    // for signatures src/librustc_allocator/lib.rs
451
452    // linkage directives are provided as part of the current compiler allocator
453    // ABI
454
455    #[rustc_std_internal_symbol]
456    pub unsafe extern "C" fn __rdl_alloc(size: usize, align: usize) -> *mut u8 {
457        // SAFETY: see the guarantees expected by `Layout::from_size_align` and
458        // `GlobalAlloc::alloc`.
459        unsafe {
460            let layout = Layout::from_size_align_unchecked(size, align);
461            imp::alloc(layout)
462        }
463    }
464
465    #[rustc_std_internal_symbol]
466    pub unsafe extern "C" fn __rdl_dealloc(ptr: *mut u8, size: usize, align: usize) {
467        // SAFETY: see the guarantees expected by `Layout::from_size_align` and
468        // `GlobalAlloc::dealloc`.
469        unsafe { imp::dealloc(ptr, Layout::from_size_align_unchecked(size, align)) }
470    }
471
472    #[rustc_std_internal_symbol]
473    pub unsafe extern "C" fn __rdl_realloc(
474        ptr: *mut u8,
475        old_size: usize,
476        align: usize,
477        new_size: usize,
478    ) -> *mut u8 {
479        // SAFETY: see the guarantees expected by `Layout::from_size_align` and
480        // `GlobalAlloc::realloc`.
481        unsafe {
482            let old_layout = Layout::from_size_align_unchecked(old_size, align);
483            imp::realloc(ptr, old_layout, new_size)
484        }
485    }
486
487    #[rustc_std_internal_symbol]
488    pub unsafe extern "C" fn __rdl_alloc_zeroed(size: usize, align: usize) -> *mut u8 {
489        // SAFETY: see the guarantees expected by `Layout::from_size_align` and
490        // `GlobalAlloc::alloc_zeroed`.
491        unsafe {
492            let layout = Layout::from_size_align_unchecked(size, align);
493            imp::alloc_zeroed(layout)
494        }
495    }
496}