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