1 // SPDX-License-Identifier: Apache-2.0 OR MIT
3 //! Memory allocation APIs
5 #![stable(feature = "alloc_module", since = "1.28.0")]
9 use core::intrinsics::{min_align_of_val, size_of_val};
11 use core::ptr::Unique;
13 use core::ptr::{self, NonNull};
15 #[stable(feature = "alloc_module", since = "1.28.0")]
17 pub use core::alloc::*;
23 // These are the magic symbols to call the global allocator. rustc generates
24 // them to call `__rg_alloc` etc. if there is a `#[global_allocator]` attribute
25 // (the code expanding that attribute macro generates those functions), or to call
26 // the default implementations in std (`__rdl_alloc` etc. in `library/std/src/alloc.rs`)
28 // The rustc fork of LLVM 14 and earlier also special-cases these function names to be able to optimize them
29 // like `malloc`, `realloc`, and `free`, respectively.
32 fn __rust_alloc(size: usize, align: usize) -> *mut u8;
35 fn __rust_dealloc(ptr: *mut u8, size: usize, align: usize);
38 fn __rust_realloc(ptr: *mut u8, old_size: usize, align: usize, new_size: usize) -> *mut u8;
39 #[rustc_allocator_zeroed]
41 fn __rust_alloc_zeroed(size: usize, align: usize) -> *mut u8;
43 #[cfg(not(bootstrap))]
44 static __rust_no_alloc_shim_is_unstable: u8;
47 /// The global memory allocator.
49 /// This type implements the [`Allocator`] trait by forwarding calls
50 /// to the allocator registered with the `#[global_allocator]` attribute
51 /// if there is one, or the `std` crate’s default.
53 /// Note: while this type is unstable, the functionality it provides can be
54 /// accessed through the [free functions in `alloc`](self#functions).
55 #[unstable(feature = "allocator_api", issue = "32838")]
56 #[derive(Copy, Clone, Default, Debug)]
61 pub use std::alloc::Global;
63 /// Allocate memory with the global allocator.
65 /// This function forwards calls to the [`GlobalAlloc::alloc`] method
66 /// of the allocator registered with the `#[global_allocator]` attribute
67 /// if there is one, or the `std` crate’s default.
69 /// This function is expected to be deprecated in favor of the `alloc` method
70 /// of the [`Global`] type when it and the [`Allocator`] trait become stable.
74 /// See [`GlobalAlloc::alloc`].
79 /// use std::alloc::{alloc, dealloc, handle_alloc_error, Layout};
82 /// let layout = Layout::new::<u16>();
83 /// let ptr = alloc(layout);
84 /// if ptr.is_null() {
85 /// handle_alloc_error(layout);
88 /// *(ptr as *mut u16) = 42;
89 /// assert_eq!(*(ptr as *mut u16), 42);
91 /// dealloc(ptr, layout);
94 #[stable(feature = "global_alloc", since = "1.28.0")]
95 #[must_use = "losing the pointer will leak memory"]
97 pub unsafe fn alloc(layout: Layout) -> *mut u8 {
99 // Make sure we don't accidentally allow omitting the allocator shim in
100 // stable code until it is actually stabilized.
101 #[cfg(not(bootstrap))]
102 core::ptr::read_volatile(&__rust_no_alloc_shim_is_unstable);
104 __rust_alloc(layout.size(), layout.align())
108 /// Deallocate memory with the global allocator.
110 /// This function forwards calls to the [`GlobalAlloc::dealloc`] method
111 /// of the allocator registered with the `#[global_allocator]` attribute
112 /// if there is one, or the `std` crate’s default.
114 /// This function is expected to be deprecated in favor of the `dealloc` method
115 /// of the [`Global`] type when it and the [`Allocator`] trait become stable.
119 /// See [`GlobalAlloc::dealloc`].
120 #[stable(feature = "global_alloc", since = "1.28.0")]
122 pub unsafe fn dealloc(ptr: *mut u8, layout: Layout) {
123 unsafe { __rust_dealloc(ptr, layout.size(), layout.align()) }
126 /// Reallocate memory with the global allocator.
128 /// This function forwards calls to the [`GlobalAlloc::realloc`] method
129 /// of the allocator registered with the `#[global_allocator]` attribute
130 /// if there is one, or the `std` crate’s default.
132 /// This function is expected to be deprecated in favor of the `realloc` method
133 /// of the [`Global`] type when it and the [`Allocator`] trait become stable.
137 /// See [`GlobalAlloc::realloc`].
138 #[stable(feature = "global_alloc", since = "1.28.0")]
139 #[must_use = "losing the pointer will leak memory"]
141 pub unsafe fn realloc(ptr: *mut u8, layout: Layout, new_size: usize) -> *mut u8 {
142 unsafe { __rust_realloc(ptr, layout.size(), layout.align(), new_size) }
145 /// Allocate zero-initialized memory with the global allocator.
147 /// This function forwards calls to the [`GlobalAlloc::alloc_zeroed`] method
148 /// of the allocator registered with the `#[global_allocator]` attribute
149 /// if there is one, or the `std` crate’s default.
151 /// This function is expected to be deprecated in favor of the `alloc_zeroed` method
152 /// of the [`Global`] type when it and the [`Allocator`] trait become stable.
156 /// See [`GlobalAlloc::alloc_zeroed`].
161 /// use std::alloc::{alloc_zeroed, dealloc, Layout};
164 /// let layout = Layout::new::<u16>();
165 /// let ptr = alloc_zeroed(layout);
167 /// assert_eq!(*(ptr as *mut u16), 0);
169 /// dealloc(ptr, layout);
172 #[stable(feature = "global_alloc", since = "1.28.0")]
173 #[must_use = "losing the pointer will leak memory"]
175 pub unsafe fn alloc_zeroed(layout: Layout) -> *mut u8 {
176 unsafe { __rust_alloc_zeroed(layout.size(), layout.align()) }
182 fn alloc_impl(&self, layout: Layout, zeroed: bool) -> Result<NonNull<[u8]>, AllocError> {
183 match layout.size() {
184 0 => Ok(NonNull::slice_from_raw_parts(layout.dangling(), 0)),
185 // SAFETY: `layout` is non-zero in size,
187 let raw_ptr = if zeroed { alloc_zeroed(layout) } else { alloc(layout) };
188 let ptr = NonNull::new(raw_ptr).ok_or(AllocError)?;
189 Ok(NonNull::slice_from_raw_parts(ptr, size))
194 // SAFETY: Same as `Allocator::grow`
202 ) -> Result<NonNull<[u8]>, AllocError> {
204 new_layout.size() >= old_layout.size(),
205 "`new_layout.size()` must be greater than or equal to `old_layout.size()`"
208 match old_layout.size() {
209 0 => self.alloc_impl(new_layout, zeroed),
211 // SAFETY: `new_size` is non-zero as `old_size` is greater than or equal to `new_size`
212 // as required by safety conditions. Other conditions must be upheld by the caller
213 old_size if old_layout.align() == new_layout.align() => unsafe {
214 let new_size = new_layout.size();
216 // `realloc` probably checks for `new_size >= old_layout.size()` or something similar.
217 intrinsics::assume(new_size >= old_layout.size());
219 let raw_ptr = realloc(ptr.as_ptr(), old_layout, new_size);
220 let ptr = NonNull::new(raw_ptr).ok_or(AllocError)?;
222 raw_ptr.add(old_size).write_bytes(0, new_size - old_size);
224 Ok(NonNull::slice_from_raw_parts(ptr, new_size))
227 // SAFETY: because `new_layout.size()` must be greater than or equal to `old_size`,
228 // both the old and new memory allocation are valid for reads and writes for `old_size`
229 // bytes. Also, because the old allocation wasn't yet deallocated, it cannot overlap
230 // `new_ptr`. Thus, the call to `copy_nonoverlapping` is safe. The safety contract
231 // for `dealloc` must be upheld by the caller.
233 let new_ptr = self.alloc_impl(new_layout, zeroed)?;
234 ptr::copy_nonoverlapping(ptr.as_ptr(), new_ptr.as_mut_ptr(), old_size);
235 self.deallocate(ptr, old_layout);
242 #[unstable(feature = "allocator_api", issue = "32838")]
244 unsafe impl Allocator for Global {
246 fn allocate(&self, layout: Layout) -> Result<NonNull<[u8]>, AllocError> {
247 self.alloc_impl(layout, false)
251 fn allocate_zeroed(&self, layout: Layout) -> Result<NonNull<[u8]>, AllocError> {
252 self.alloc_impl(layout, true)
256 unsafe fn deallocate(&self, ptr: NonNull<u8>, layout: Layout) {
257 if layout.size() != 0 {
258 // SAFETY: `layout` is non-zero in size,
259 // other conditions must be upheld by the caller
260 unsafe { dealloc(ptr.as_ptr(), layout) }
270 ) -> Result<NonNull<[u8]>, AllocError> {
271 // SAFETY: all conditions must be upheld by the caller
272 unsafe { self.grow_impl(ptr, old_layout, new_layout, false) }
276 unsafe fn grow_zeroed(
281 ) -> Result<NonNull<[u8]>, AllocError> {
282 // SAFETY: all conditions must be upheld by the caller
283 unsafe { self.grow_impl(ptr, old_layout, new_layout, true) }
292 ) -> Result<NonNull<[u8]>, AllocError> {
294 new_layout.size() <= old_layout.size(),
295 "`new_layout.size()` must be smaller than or equal to `old_layout.size()`"
298 match new_layout.size() {
299 // SAFETY: conditions must be upheld by the caller
301 self.deallocate(ptr, old_layout);
302 Ok(NonNull::slice_from_raw_parts(new_layout.dangling(), 0))
305 // SAFETY: `new_size` is non-zero. Other conditions must be upheld by the caller
306 new_size if old_layout.align() == new_layout.align() => unsafe {
307 // `realloc` probably checks for `new_size <= old_layout.size()` or something similar.
308 intrinsics::assume(new_size <= old_layout.size());
310 let raw_ptr = realloc(ptr.as_ptr(), old_layout, new_size);
311 let ptr = NonNull::new(raw_ptr).ok_or(AllocError)?;
312 Ok(NonNull::slice_from_raw_parts(ptr, new_size))
315 // SAFETY: because `new_size` must be smaller than or equal to `old_layout.size()`,
316 // both the old and new memory allocation are valid for reads and writes for `new_size`
317 // bytes. Also, because the old allocation wasn't yet deallocated, it cannot overlap
318 // `new_ptr`. Thus, the call to `copy_nonoverlapping` is safe. The safety contract
319 // for `dealloc` must be upheld by the caller.
321 let new_ptr = self.allocate(new_layout)?;
322 ptr::copy_nonoverlapping(ptr.as_ptr(), new_ptr.as_mut_ptr(), new_size);
323 self.deallocate(ptr, old_layout);
330 /// The allocator for unique pointers.
331 #[cfg(all(not(no_global_oom_handling), not(test)))]
332 #[lang = "exchange_malloc"]
334 unsafe fn exchange_malloc(size: usize, align: usize) -> *mut u8 {
335 let layout = unsafe { Layout::from_size_align_unchecked(size, align) };
336 match Global.allocate(layout) {
337 Ok(ptr) => ptr.as_mut_ptr(),
338 Err(_) => handle_alloc_error(layout),
342 #[cfg_attr(not(test), lang = "box_free")]
344 // This signature has to be the same as `Box`, otherwise an ICE will happen.
345 // When an additional parameter to `Box` is added (like `A: Allocator`), this has to be added here as
347 // For example if `Box` is changed to `struct Box<T: ?Sized, A: Allocator>(Unique<T>, A)`,
348 // this function has to be changed to `fn box_free<T: ?Sized, A: Allocator>(Unique<T>, A)` as well.
349 pub(crate) unsafe fn box_free<T: ?Sized, A: Allocator>(ptr: Unique<T>, alloc: A) {
351 let size = size_of_val(ptr.as_ref());
352 let align = min_align_of_val(ptr.as_ref());
353 let layout = Layout::from_size_align_unchecked(size, align);
354 alloc.deallocate(From::from(ptr.cast()), layout)
358 // # Allocation error handler
360 #[cfg(not(no_global_oom_handling))]
362 // This is the magic symbol to call the global alloc error handler. rustc generates
363 // it to call `__rg_oom` if there is a `#[alloc_error_handler]`, or to call the
364 // default implementations below (`__rdl_oom`) otherwise.
365 fn __rust_alloc_error_handler(size: usize, align: usize) -> !;
368 /// Abort on memory allocation error or failure.
370 /// Callers of memory allocation APIs wishing to abort computation
371 /// in response to an allocation error are encouraged to call this function,
372 /// rather than directly invoking `panic!` or similar.
374 /// The default behavior of this function is to print a message to standard error
375 /// and abort the process.
376 /// It can be replaced with [`set_alloc_error_hook`] and [`take_alloc_error_hook`].
378 /// [`set_alloc_error_hook`]: ../../std/alloc/fn.set_alloc_error_hook.html
379 /// [`take_alloc_error_hook`]: ../../std/alloc/fn.take_alloc_error_hook.html
380 #[stable(feature = "global_alloc", since = "1.28.0")]
381 #[rustc_const_unstable(feature = "const_alloc_error", issue = "92523")]
382 #[cfg(all(not(no_global_oom_handling), not(test)))]
384 pub const fn handle_alloc_error(layout: Layout) -> ! {
385 const fn ct_error(_: Layout) -> ! {
386 panic!("allocation failed");
389 fn rt_error(layout: Layout) -> ! {
391 __rust_alloc_error_handler(layout.size(), layout.align());
395 unsafe { core::intrinsics::const_eval_select((layout,), ct_error, rt_error) }
398 // For alloc test `std::alloc::handle_alloc_error` can be used directly.
399 #[cfg(all(not(no_global_oom_handling), test))]
400 pub use std::alloc::handle_alloc_error;
402 #[cfg(all(not(no_global_oom_handling), not(test)))]
404 #[allow(unused_attributes)]
405 #[unstable(feature = "alloc_internals", issue = "none")]
406 pub mod __alloc_error_handler {
407 // called via generated `__rust_alloc_error_handler` if there is no
408 // `#[alloc_error_handler]`.
409 #[rustc_std_internal_symbol]
410 pub unsafe fn __rdl_oom(size: usize, _align: usize) -> ! {
412 // This symbol is emitted by rustc next to __rust_alloc_error_handler.
413 // Its value depends on the -Zoom={panic,abort} compiler option.
414 static __rust_alloc_error_handler_should_panic: u8;
417 #[allow(unused_unsafe)]
418 if unsafe { __rust_alloc_error_handler_should_panic != 0 } {
419 panic!("memory allocation of {size} bytes failed")
421 core::panicking::panic_nounwind_fmt(format_args!(
422 "memory allocation of {size} bytes failed"
428 /// Specialize clones into pre-allocated, uninitialized memory.
429 /// Used by `Box::clone` and `Rc`/`Arc::make_mut`.
430 pub(crate) trait WriteCloneIntoRaw: Sized {
431 unsafe fn write_clone_into_raw(&self, target: *mut Self);
434 impl<T: Clone> WriteCloneIntoRaw for T {
436 default unsafe fn write_clone_into_raw(&self, target: *mut Self) {
437 // Having allocated *first* may allow the optimizer to create
438 // the cloned value in-place, skipping the local and move.
439 unsafe { target.write(self.clone()) };
443 impl<T: Copy> WriteCloneIntoRaw for T {
445 unsafe fn write_clone_into_raw(&self, target: *mut Self) {
446 // We can always copy in-place, without ever involving a local value.
447 unsafe { target.copy_from_nonoverlapping(self, 1) };