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