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 #![deny(unsafe_op_in_unsafe_fn)]
63 #![stable(feature = "alloc_module", since = "1.28.0")]
66 use core::ptr::NonNull;
67 use core::sync::atomic::{AtomicPtr, Ordering};
70 use crate::sys_common::util::dumb_print;
72 #[stable(feature = "alloc_module", since = "1.28.0")]
74 pub use alloc_crate::alloc::*;
76 /// The default memory allocator provided by the operating system.
78 /// This is based on `malloc` on Unix platforms and `HeapAlloc` on Windows,
79 /// plus related functions.
81 /// This type implements the `GlobalAlloc` trait and Rust programs by default
82 /// work as if they had this definition:
85 /// use std::alloc::System;
87 /// #[global_allocator]
88 /// static A: System = System;
91 /// let a = Box::new(4); // Allocates from the system allocator.
92 /// println!("{}", a);
96 /// You can also define your own wrapper around `System` if you'd like, such as
97 /// keeping track of the number of all bytes allocated:
100 /// use std::alloc::{System, GlobalAlloc, Layout};
101 /// use std::sync::atomic::{AtomicUsize, Ordering::SeqCst};
105 /// static ALLOCATED: AtomicUsize = AtomicUsize::new(0);
107 /// unsafe impl GlobalAlloc for Counter {
108 /// unsafe fn alloc(&self, layout: Layout) -> *mut u8 {
109 /// let ret = System.alloc(layout);
110 /// if !ret.is_null() {
111 /// ALLOCATED.fetch_add(layout.size(), SeqCst);
116 /// unsafe fn dealloc(&self, ptr: *mut u8, layout: Layout) {
117 /// System.dealloc(ptr, layout);
118 /// ALLOCATED.fetch_sub(layout.size(), SeqCst);
122 /// #[global_allocator]
123 /// static A: Counter = Counter;
126 /// println!("allocated bytes before main: {}", ALLOCATED.load(SeqCst));
130 /// It can also be used directly to allocate memory independently of whatever
131 /// global allocator has been selected for a Rust program. For example if a Rust
132 /// program opts in to using jemalloc as the global allocator, `System` will
133 /// still allocate memory using `malloc` and `HeapAlloc`.
134 #[stable(feature = "alloc_system_type", since = "1.28.0")]
135 #[derive(Debug, Default, Copy, Clone)]
138 // The AllocRef impl checks the layout size to be non-zero and forwards to the GlobalAlloc impl,
139 // which is in `std::sys::*::alloc`.
140 #[unstable(feature = "allocator_api", issue = "32838")]
141 unsafe impl AllocRef for System {
143 fn alloc(&mut self, layout: Layout) -> Result<NonNull<[u8]>, AllocErr> {
144 let size = layout.size();
145 let ptr = if size == 0 {
148 // SAFETY: `layout` is non-zero in size,
149 unsafe { NonNull::new(GlobalAlloc::alloc(&System, layout)).ok_or(AllocErr)? }
151 Ok(NonNull::slice_from_raw_parts(ptr, size))
155 fn alloc_zeroed(&mut self, layout: Layout) -> Result<NonNull<[u8]>, AllocErr> {
156 let size = layout.size();
157 let ptr = if size == 0 {
160 // SAFETY: `layout` is non-zero in size,
161 unsafe { NonNull::new(GlobalAlloc::alloc_zeroed(&System, layout)).ok_or(AllocErr)? }
163 Ok(NonNull::slice_from_raw_parts(ptr, size))
167 unsafe fn dealloc(&mut self, ptr: NonNull<u8>, layout: Layout) {
168 if layout.size() != 0 {
169 // SAFETY: `layout` is non-zero in size,
170 // other conditions must be upheld by the caller
171 unsafe { GlobalAlloc::dealloc(&System, ptr.as_ptr(), layout) }
181 ) -> Result<NonNull<[u8]>, AllocErr> {
183 new_size >= layout.size(),
184 "`new_size` must be greater than or equal to `layout.size()`"
187 // SAFETY: `new_size` must be non-zero, which is checked in the match expression.
188 // Other conditions must be upheld by the caller
190 match layout.size() {
191 old_size if old_size == new_size => {
192 Ok(NonNull::slice_from_raw_parts(ptr, new_size))
194 0 => self.alloc(Layout::from_size_align_unchecked(new_size, layout.align())),
196 // `realloc` probably checks for `new_size > size` or something similar.
197 intrinsics::assume(new_size > old_size);
198 let raw_ptr = GlobalAlloc::realloc(&System, ptr.as_ptr(), layout, new_size);
199 let ptr = NonNull::new(raw_ptr).ok_or(AllocErr)?;
200 Ok(NonNull::slice_from_raw_parts(ptr, new_size))
207 unsafe fn grow_zeroed(
212 ) -> Result<NonNull<[u8]>, AllocErr> {
214 new_size >= layout.size(),
215 "`new_size` must be greater than or equal to `layout.size()`"
218 // SAFETY: `new_size` must be non-zero, which is checked in the match expression.
219 // Other conditions must be upheld by the caller
221 match layout.size() {
222 old_size if old_size == new_size => {
223 Ok(NonNull::slice_from_raw_parts(ptr, new_size))
225 0 => self.alloc_zeroed(Layout::from_size_align_unchecked(new_size, layout.align())),
227 // `realloc` probably checks for `new_size > size` or something similar.
228 intrinsics::assume(new_size > old_size);
229 let raw_ptr = GlobalAlloc::realloc(&System, ptr.as_ptr(), layout, new_size);
230 raw_ptr.add(old_size).write_bytes(0, new_size - old_size);
231 let ptr = NonNull::new(raw_ptr).ok_or(AllocErr)?;
232 Ok(NonNull::slice_from_raw_parts(ptr, new_size))
244 ) -> Result<NonNull<[u8]>, AllocErr> {
245 let old_size = layout.size();
247 new_size <= old_size,
248 "`new_size` must be smaller than or equal to `layout.size()`"
251 let ptr = if new_size == old_size {
253 } else if new_size == 0 {
254 // SAFETY: `layout` is non-zero in size as `old_size` != `new_size`
255 // Other conditions must be upheld by the caller
257 self.dealloc(ptr, layout);
261 // SAFETY: new_size is not zero,
262 // Other conditions must be upheld by the caller
263 let raw_ptr = unsafe {
264 // `realloc` probably checks for `new_size < old_size` or something similar.
265 intrinsics::assume(new_size < old_size);
266 GlobalAlloc::realloc(&System, ptr.as_ptr(), layout, new_size)
268 NonNull::new(raw_ptr).ok_or(AllocErr)?
271 Ok(NonNull::slice_from_raw_parts(ptr, new_size))
274 static HOOK: AtomicPtr<()> = AtomicPtr::new(ptr::null_mut());
276 /// Registers a custom allocation error hook, replacing any that was previously registered.
278 /// The allocation error hook is invoked when an infallible memory allocation fails, before
279 /// the runtime aborts. The default hook prints a message to standard error,
280 /// but this behavior can be customized with the [`set_alloc_error_hook`] and
281 /// [`take_alloc_error_hook`] functions.
283 /// The hook is provided with a `Layout` struct which contains information
284 /// about the allocation that failed.
286 /// The allocation error hook is a global resource.
288 /// [`set_alloc_error_hook`]: fn.set_alloc_error_hook.html
289 /// [`take_alloc_error_hook`]: fn.take_alloc_error_hook.html
290 #[unstable(feature = "alloc_error_hook", issue = "51245")]
291 pub fn set_alloc_error_hook(hook: fn(Layout)) {
292 HOOK.store(hook as *mut (), Ordering::SeqCst);
295 /// Unregisters the current allocation error hook, returning it.
297 /// *See also the function [`set_alloc_error_hook`].*
299 /// If no custom hook is registered, the default hook will be returned.
301 /// [`set_alloc_error_hook`]: fn.set_alloc_error_hook.html
302 #[unstable(feature = "alloc_error_hook", issue = "51245")]
303 pub fn take_alloc_error_hook() -> fn(Layout) {
304 let hook = HOOK.swap(ptr::null_mut(), Ordering::SeqCst);
305 if hook.is_null() { default_alloc_error_hook } else { unsafe { mem::transmute(hook) } }
308 fn default_alloc_error_hook(layout: Layout) {
309 dumb_print(format_args!("memory allocation of {} bytes failed", layout.size()));
314 #[alloc_error_handler]
315 #[unstable(feature = "alloc_internals", issue = "none")]
316 pub fn rust_oom(layout: Layout) -> ! {
317 let hook = HOOK.load(Ordering::SeqCst);
318 let hook: fn(Layout) =
319 if hook.is_null() { default_alloc_error_hook } else { unsafe { mem::transmute(hook) } };
321 crate::process::abort()
326 #[allow(unused_attributes)]
327 #[unstable(feature = "alloc_internals", issue = "none")]
328 pub mod __default_lib_allocator {
329 use super::{GlobalAlloc, Layout, System};
330 // These magic symbol names are used as a fallback for implementing the
331 // `__rust_alloc` etc symbols (see `src/liballoc/alloc.rs`) when there is
332 // no `#[global_allocator]` attribute.
334 // for symbol names src/librustc_ast/expand/allocator.rs
335 // for signatures src/librustc_allocator/lib.rs
337 // linkage directives are provided as part of the current compiler allocator
340 #[rustc_std_internal_symbol]
341 pub unsafe extern "C" fn __rdl_alloc(size: usize, align: usize) -> *mut u8 {
342 // SAFETY: see the guarantees expected by `Layout::from_size_align` and
343 // `GlobalAlloc::alloc`.
345 let layout = Layout::from_size_align_unchecked(size, align);
350 #[rustc_std_internal_symbol]
351 pub unsafe extern "C" fn __rdl_dealloc(ptr: *mut u8, size: usize, align: usize) {
352 // SAFETY: see the guarantees expected by `Layout::from_size_align` and
353 // `GlobalAlloc::dealloc`.
354 unsafe { System.dealloc(ptr, Layout::from_size_align_unchecked(size, align)) }
357 #[rustc_std_internal_symbol]
358 pub unsafe extern "C" fn __rdl_realloc(
364 // SAFETY: see the guarantees expected by `Layout::from_size_align` and
365 // `GlobalAlloc::realloc`.
367 let old_layout = Layout::from_size_align_unchecked(old_size, align);
368 System.realloc(ptr, old_layout, new_size)
372 #[rustc_std_internal_symbol]
373 pub unsafe extern "C" fn __rdl_alloc_zeroed(size: usize, align: usize) -> *mut u8 {
374 // SAFETY: see the guarantees expected by `Layout::from_size_align` and
375 // `GlobalAlloc::alloc_zeroed`.
377 let layout = Layout::from_size_align_unchecked(size, align);
378 System.alloc_zeroed(layout)