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 // The AllocRef impl checks the layout size to be non-zero and forwards to the GlobalAlloc impl,
138 // which is in `std::sys::*::alloc`.
139 #[unstable(feature = "allocator_api", issue = "32838")]
140 unsafe impl AllocRef for System {
142 fn alloc(&mut self, layout: Layout, init: AllocInit) -> Result<MemoryBlock, AllocErr> {
144 let size = layout.size();
146 Ok(MemoryBlock { ptr: layout.dangling(), size: 0 })
148 let raw_ptr = match init {
149 AllocInit::Uninitialized => GlobalAlloc::alloc(self, layout),
150 AllocInit::Zeroed => GlobalAlloc::alloc_zeroed(self, layout),
152 let ptr = NonNull::new(raw_ptr).ok_or(AllocErr)?;
153 Ok(MemoryBlock { ptr, size })
159 unsafe fn dealloc(&mut self, ptr: NonNull<u8>, layout: Layout) {
160 if layout.size() != 0 {
161 GlobalAlloc::dealloc(self, ptr.as_ptr(), layout)
171 placement: ReallocPlacement,
173 ) -> Result<MemoryBlock, AllocErr> {
174 let size = layout.size();
177 "`new_size` must be greater than or equal to `memory.size()`"
180 if size == new_size {
181 return Ok(MemoryBlock { ptr, size });
185 ReallocPlacement::InPlace => Err(AllocErr),
186 ReallocPlacement::MayMove if layout.size() == 0 => {
187 let new_layout = Layout::from_size_align_unchecked(new_size, layout.align());
188 self.alloc(new_layout, init)
190 ReallocPlacement::MayMove => {
191 // `realloc` probably checks for `new_size > size` or something similar.
192 intrinsics::assume(new_size > size);
193 let ptr = GlobalAlloc::realloc(self, ptr.as_ptr(), layout, new_size);
195 MemoryBlock { ptr: NonNull::new(ptr).ok_or(AllocErr)?, size: new_size };
196 init.init_offset(memory, size);
208 placement: ReallocPlacement,
209 ) -> Result<MemoryBlock, AllocErr> {
210 let size = layout.size();
213 "`new_size` must be smaller than or equal to `memory.size()`"
216 if size == new_size {
217 return Ok(MemoryBlock { ptr, size });
221 ReallocPlacement::InPlace => Err(AllocErr),
222 ReallocPlacement::MayMove if new_size == 0 => {
223 self.dealloc(ptr, layout);
224 Ok(MemoryBlock { ptr: layout.dangling(), size: 0 })
226 ReallocPlacement::MayMove => {
227 // `realloc` probably checks for `new_size < size` or something similar.
228 intrinsics::assume(new_size < size);
229 let ptr = GlobalAlloc::realloc(self, ptr.as_ptr(), layout, new_size);
230 Ok(MemoryBlock { ptr: NonNull::new(ptr).ok_or(AllocErr)?, size: new_size })
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 crate::process::abort()
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_ast/expand/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)