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")]
65 use core::ptr::NonNull;
66 use core::sync::atomic::{AtomicPtr, Ordering};
69 use crate::sys_common::util::dumb_print;
71 #[stable(feature = "alloc_module", since = "1.28.0")]
73 pub use alloc_crate::alloc::*;
75 /// The default memory allocator provided by the operating system.
77 /// This is based on `malloc` on Unix platforms and `HeapAlloc` on Windows,
78 /// plus related functions.
80 /// This type implements the `GlobalAlloc` trait and Rust programs by default
81 /// work as if they had this definition:
84 /// use std::alloc::System;
86 /// #[global_allocator]
87 /// static A: System = System;
90 /// let a = Box::new(4); // Allocates from the system allocator.
91 /// println!("{}", a);
95 /// You can also define your own wrapper around `System` if you'd like, such as
96 /// keeping track of the number of all bytes allocated:
99 /// use std::alloc::{System, GlobalAlloc, Layout};
100 /// use std::sync::atomic::{AtomicUsize, Ordering::SeqCst};
104 /// static ALLOCATED: AtomicUsize = AtomicUsize::new(0);
106 /// unsafe impl GlobalAlloc for Counter {
107 /// unsafe fn alloc(&self, layout: Layout) -> *mut u8 {
108 /// let ret = System.alloc(layout);
109 /// if !ret.is_null() {
110 /// ALLOCATED.fetch_add(layout.size(), SeqCst);
115 /// unsafe fn dealloc(&self, ptr: *mut u8, layout: Layout) {
116 /// System.dealloc(ptr, layout);
117 /// ALLOCATED.fetch_sub(layout.size(), SeqCst);
121 /// #[global_allocator]
122 /// static A: Counter = Counter;
125 /// println!("allocated bytes before main: {}", ALLOCATED.load(SeqCst));
129 /// It can also be used directly to allocate memory independently of whatever
130 /// global allocator has been selected for a Rust program. For example if a Rust
131 /// program opts in to using jemalloc as the global allocator, `System` will
132 /// still allocate memory using `malloc` and `HeapAlloc`.
133 #[stable(feature = "alloc_system_type", since = "1.28.0")]
134 #[derive(Debug, Default, Copy, Clone)]
137 #[unstable(feature = "allocator_api", issue = "32838")]
138 unsafe impl AllocRef for System {
140 fn alloc(&mut self, layout: Layout, init: AllocInit) -> Result<MemoryBlock, AllocErr> {
142 if layout.size() == 0 {
143 Ok(MemoryBlock::new(layout.dangling(), layout))
145 let raw_ptr = match init {
146 AllocInit::Uninitialized => GlobalAlloc::alloc(self, layout),
147 AllocInit::Zeroed => GlobalAlloc::alloc_zeroed(self, layout),
149 let ptr = NonNull::new(raw_ptr).ok_or(AllocErr)?;
150 Ok(MemoryBlock::new(ptr, layout))
156 unsafe fn dealloc(&mut self, memory: MemoryBlock) {
157 if memory.size() != 0 {
158 GlobalAlloc::dealloc(self, memory.ptr().as_ptr(), memory.layout())
165 memory: &mut MemoryBlock,
167 placement: ReallocPlacement,
169 ) -> Result<(), AllocErr> {
170 let old_size = memory.size();
172 new_size >= old_size,
173 "`new_size` must be greater than or equal to `memory.size()`"
176 if old_size == new_size {
180 let new_layout = Layout::from_size_align_unchecked(new_size, memory.align());
182 ReallocPlacement::InPlace => return Err(AllocErr),
183 ReallocPlacement::MayMove if memory.size() == 0 => {
184 *memory = self.alloc(new_layout, init)?
186 ReallocPlacement::MayMove => {
187 // `realloc` probably checks for `new_size > old_size` or something similar.
188 intrinsics::assume(new_size > old_size);
190 GlobalAlloc::realloc(self, memory.ptr().as_ptr(), memory.layout(), new_size);
191 *memory = MemoryBlock::new(NonNull::new(ptr).ok_or(AllocErr)?, new_layout);
192 memory.init_offset(init, old_size);
201 memory: &mut MemoryBlock,
203 placement: ReallocPlacement,
204 ) -> Result<(), AllocErr> {
205 let old_size = memory.size();
207 new_size <= old_size,
208 "`new_size` must be smaller than or equal to `memory.size()`"
211 if old_size == new_size {
215 let new_layout = Layout::from_size_align_unchecked(new_size, memory.align());
217 ReallocPlacement::InPlace => return Err(AllocErr),
218 ReallocPlacement::MayMove if new_size == 0 => {
219 let new_memory = MemoryBlock::new(new_layout.dangling(), new_layout);
220 let old_memory = mem::replace(memory, new_memory);
221 self.dealloc(old_memory)
223 ReallocPlacement::MayMove => {
224 // `realloc` probably checks for `new_size < old_size` or something similar.
225 intrinsics::assume(new_size < old_size);
227 GlobalAlloc::realloc(self, memory.ptr().as_ptr(), memory.layout(), new_size);
228 *memory = MemoryBlock::new(NonNull::new(ptr).ok_or(AllocErr)?, new_layout);
235 static HOOK: AtomicPtr<()> = AtomicPtr::new(ptr::null_mut());
237 /// Registers a custom allocation error hook, replacing any that was previously registered.
239 /// The allocation error hook is invoked when an infallible memory allocation fails, before
240 /// the runtime aborts. The default hook prints a message to standard error,
241 /// but this behavior can be customized with the [`set_alloc_error_hook`] and
242 /// [`take_alloc_error_hook`] functions.
244 /// The hook is provided with a `Layout` struct which contains information
245 /// about the allocation that failed.
247 /// The allocation error hook is a global resource.
249 /// [`set_alloc_error_hook`]: fn.set_alloc_error_hook.html
250 /// [`take_alloc_error_hook`]: fn.take_alloc_error_hook.html
251 #[unstable(feature = "alloc_error_hook", issue = "51245")]
252 pub fn set_alloc_error_hook(hook: fn(Layout)) {
253 HOOK.store(hook as *mut (), Ordering::SeqCst);
256 /// Unregisters the current allocation error hook, returning it.
258 /// *See also the function [`set_alloc_error_hook`].*
260 /// If no custom hook is registered, the default hook will be returned.
262 /// [`set_alloc_error_hook`]: fn.set_alloc_error_hook.html
263 #[unstable(feature = "alloc_error_hook", issue = "51245")]
264 pub fn take_alloc_error_hook() -> fn(Layout) {
265 let hook = HOOK.swap(ptr::null_mut(), Ordering::SeqCst);
266 if hook.is_null() { default_alloc_error_hook } else { unsafe { mem::transmute(hook) } }
269 fn default_alloc_error_hook(layout: Layout) {
270 dumb_print(format_args!("memory allocation of {} bytes failed", layout.size()));
275 #[alloc_error_handler]
276 #[unstable(feature = "alloc_internals", issue = "none")]
277 pub fn rust_oom(layout: Layout) -> ! {
278 let hook = HOOK.load(Ordering::SeqCst);
279 let hook: fn(Layout) =
280 if hook.is_null() { default_alloc_error_hook } else { unsafe { mem::transmute(hook) } };
282 unsafe { crate::sys::abort_internal() }
287 #[allow(unused_attributes)]
288 #[unstable(feature = "alloc_internals", issue = "none")]
289 pub mod __default_lib_allocator {
290 use super::{GlobalAlloc, Layout, System};
291 // These magic symbol names are used as a fallback for implementing the
292 // `__rust_alloc` etc symbols (see `src/liballoc/alloc.rs) when there is
293 // no `#[global_allocator]` attribute.
295 // for symbol names src/librustc/middle/allocator.rs
296 // for signatures src/librustc_allocator/lib.rs
298 // linkage directives are provided as part of the current compiler allocator
301 #[rustc_std_internal_symbol]
302 pub unsafe extern "C" fn __rdl_alloc(size: usize, align: usize) -> *mut u8 {
303 let layout = Layout::from_size_align_unchecked(size, align);
307 #[rustc_std_internal_symbol]
308 pub unsafe extern "C" fn __rdl_dealloc(ptr: *mut u8, size: usize, align: usize) {
309 System.dealloc(ptr, Layout::from_size_align_unchecked(size, align))
312 #[rustc_std_internal_symbol]
313 pub unsafe extern "C" fn __rdl_realloc(
319 let old_layout = Layout::from_size_align_unchecked(old_size, align);
320 System.realloc(ptr, old_layout, new_size)
323 #[rustc_std_internal_symbol]
324 pub unsafe extern "C" fn __rdl_alloc_zeroed(size: usize, align: usize) -> *mut u8 {
325 let layout = Layout::from_size_align_unchecked(size, align);
326 System.alloc_zeroed(layout)