1 //! Memory allocation APIs
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>`.
6 //! Currently the default global allocator is unspecified. Libraries, however,
7 //! like `cdylib`s and `staticlib`s are guaranteed to use the [`System`] by
10 //! [`System`]: struct.System.html
12 //! # The `#[global_allocator]` attribute
14 //! This attribute allows configuring the choice of global allocator.
15 //! You can use this to implement a completely custom global allocator
16 //! to route all default allocation requests to a custom object.
19 //! use std::alloc::{GlobalAlloc, System, Layout};
21 //! struct MyAllocator;
23 //! unsafe impl GlobalAlloc for MyAllocator {
24 //! unsafe fn alloc(&self, layout: Layout) -> *mut u8 {
25 //! System.alloc(layout)
28 //! unsafe fn dealloc(&self, ptr: *mut u8, layout: Layout) {
29 //! System.dealloc(ptr, layout)
33 //! #[global_allocator]
34 //! static GLOBAL: MyAllocator = MyAllocator;
37 //! // This `Vec` will allocate memory through `GLOBAL` above
38 //! let mut v = Vec::new();
43 //! The attribute is used on a `static` item whose type implements the
44 //! [`GlobalAlloc`] trait. This type can be provided by an external library:
46 //! [`GlobalAlloc`]: ../../core/alloc/trait.GlobalAlloc.html
48 //! ```rust,ignore (demonstrates crates.io usage)
49 //! extern crate jemallocator;
51 //! use jemallocator::Jemalloc;
53 //! #[global_allocator]
54 //! static GLOBAL: Jemalloc = Jemalloc;
59 //! The `#[global_allocator]` can only be used once in a crate
60 //! or its recursive dependencies.
62 #![stable(feature = "alloc_module", since = "1.28.0")]
64 use core::sync::atomic::{AtomicPtr, Ordering};
66 use core::ptr::NonNull;
67 use sys_common::util::dumb_print;
69 #[stable(feature = "alloc_module", since = "1.28.0")]
71 pub use alloc_crate::alloc::*;
73 /// The default memory allocator provided by the operating system.
75 /// This is based on `malloc` on Unix platforms and `HeapAlloc` on Windows,
76 /// plus related functions.
78 /// This type implements the `GlobalAlloc` trait and Rust programs by default
79 /// work as if they had this definition:
82 /// use std::alloc::System;
84 /// #[global_allocator]
85 /// static A: System = System;
88 /// let a = Box::new(4); // Allocates from the system allocator.
89 /// println!("{}", a);
93 /// You can also define your own wrapper around `System` if you'd like, such as
94 /// keeping track of the number of all bytes allocated:
97 /// use std::alloc::{System, GlobalAlloc, Layout};
98 /// use std::sync::atomic::{AtomicUsize, Ordering::SeqCst};
102 /// static ALLOCATED: AtomicUsize = AtomicUsize::new(0);
104 /// unsafe impl GlobalAlloc for Counter {
105 /// unsafe fn alloc(&self, layout: Layout) -> *mut u8 {
106 /// let ret = System.alloc(layout);
107 /// if !ret.is_null() {
108 /// ALLOCATED.fetch_add(layout.size(), SeqCst);
113 /// unsafe fn dealloc(&self, ptr: *mut u8, layout: Layout) {
114 /// System.dealloc(ptr, layout);
115 /// ALLOCATED.fetch_sub(layout.size(), SeqCst);
119 /// #[global_allocator]
120 /// static A: Counter = Counter;
123 /// println!("allocated bytes before main: {}", ALLOCATED.load(SeqCst));
127 /// It can also be used directly to allocate memory independently of whatever
128 /// global allocator has been selected for a Rust program. For example if a Rust
129 /// program opts in to using jemalloc as the global allocator, `System` will
130 /// still allocate memory using `malloc` and `HeapAlloc`.
131 #[stable(feature = "alloc_system_type", since = "1.28.0")]
132 #[derive(Debug, Copy, Clone)]
135 // The Alloc impl just forwards to the GlobalAlloc impl, which is in `std::sys::*::alloc`.
136 #[unstable(feature = "allocator_api", issue = "32838")]
137 unsafe impl Alloc for System {
139 unsafe fn alloc(&mut self, layout: Layout) -> Result<NonNull<u8>, AllocErr> {
140 NonNull::new(GlobalAlloc::alloc(self, layout)).ok_or(AllocErr)
144 unsafe fn alloc_zeroed(&mut self, layout: Layout) -> Result<NonNull<u8>, AllocErr> {
145 NonNull::new(GlobalAlloc::alloc_zeroed(self, layout)).ok_or(AllocErr)
149 unsafe fn dealloc(&mut self, ptr: NonNull<u8>, layout: Layout) {
150 GlobalAlloc::dealloc(self, ptr.as_ptr(), layout)
154 unsafe fn realloc(&mut self,
157 new_size: usize) -> Result<NonNull<u8>, AllocErr> {
158 NonNull::new(GlobalAlloc::realloc(self, ptr.as_ptr(), layout, new_size)).ok_or(AllocErr)
162 static HOOK: AtomicPtr<()> = AtomicPtr::new(ptr::null_mut());
164 /// Registers a custom allocation error hook, replacing any that was previously registered.
166 /// The allocation error hook is invoked when an infallible memory allocation fails, before
167 /// the runtime aborts. The default hook prints a message to standard error,
168 /// but this behavior can be customized with the [`set_alloc_error_hook`] and
169 /// [`take_alloc_error_hook`] functions.
171 /// The hook is provided with a `Layout` struct which contains information
172 /// about the allocation that failed.
174 /// The allocation error hook is a global resource.
175 #[unstable(feature = "alloc_error_hook", issue = "51245")]
176 pub fn set_alloc_error_hook(hook: fn(Layout)) {
177 HOOK.store(hook as *mut (), Ordering::SeqCst);
180 /// Unregisters the current allocation error hook, returning it.
182 /// *See also the function [`set_alloc_error_hook`].*
184 /// If no custom hook is registered, the default hook will be returned.
185 #[unstable(feature = "alloc_error_hook", issue = "51245")]
186 pub fn take_alloc_error_hook() -> fn(Layout) {
187 let hook = HOOK.swap(ptr::null_mut(), Ordering::SeqCst);
189 default_alloc_error_hook
191 unsafe { mem::transmute(hook) }
195 fn default_alloc_error_hook(layout: Layout) {
196 dumb_print(format_args!("memory allocation of {} bytes failed", layout.size()));
201 #[alloc_error_handler]
202 #[unstable(feature = "alloc_internals", issue = "0")]
203 pub fn rust_oom(layout: Layout) -> ! {
204 let hook = HOOK.load(Ordering::SeqCst);
205 let hook: fn(Layout) = if hook.is_null() {
206 default_alloc_error_hook
208 unsafe { mem::transmute(hook) }
211 unsafe { ::sys::abort_internal(); }
216 #[allow(unused_attributes)]
217 #[unstable(feature = "alloc_internals", issue = "0")]
218 pub mod __default_lib_allocator {
219 use super::{System, Layout, GlobalAlloc};
220 // These magic symbol names are used as a fallback for implementing the
221 // `__rust_alloc` etc symbols (see `src/liballoc/alloc.rs) when there is
222 // no `#[global_allocator]` attribute.
224 // for symbol names src/librustc/middle/allocator.rs
225 // for signatures src/librustc_allocator/lib.rs
227 // linkage directives are provided as part of the current compiler allocator
230 #[rustc_std_internal_symbol]
231 pub unsafe extern fn __rdl_alloc(size: usize, align: usize) -> *mut u8 {
232 let layout = Layout::from_size_align_unchecked(size, align);
236 #[rustc_std_internal_symbol]
237 pub unsafe extern fn __rdl_dealloc(ptr: *mut u8,
240 System.dealloc(ptr, Layout::from_size_align_unchecked(size, align))
243 #[rustc_std_internal_symbol]
244 pub unsafe extern fn __rdl_realloc(ptr: *mut u8,
247 new_size: usize) -> *mut u8 {
248 let old_layout = Layout::from_size_align_unchecked(old_size, align);
249 System.realloc(ptr, old_layout, new_size)
252 #[rustc_std_internal_symbol]
253 pub unsafe extern fn __rdl_alloc_zeroed(size: usize, align: usize) -> *mut u8 {
254 let layout = Layout::from_size_align_unchecked(size, align);
255 System.alloc_zeroed(layout)