1 //! Memory allocation APIs
3 #![stable(feature = "alloc_module", since = "1.28.0")]
7 use core::intrinsics::{min_align_of_val, size_of_val};
11 use core::ptr::{self, NonNull};
13 #[stable(feature = "alloc_module", since = "1.28.0")]
15 pub use core::alloc::*;
17 use core::marker::Destruct;
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 libstd (`__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;
44 /// The global memory allocator.
46 /// This type implements the [`Allocator`] trait by forwarding calls
47 /// to the allocator registered with the `#[global_allocator]` attribute
48 /// if there is one, or the `std` crate’s default.
50 /// Note: while this type is unstable, the functionality it provides can be
51 /// accessed through the [free functions in `alloc`](self#functions).
52 #[unstable(feature = "allocator_api", issue = "32838")]
53 #[derive(Copy, Clone, Default, Debug)]
58 pub use std::alloc::Global;
60 /// Allocate memory with the global allocator.
62 /// This function forwards calls to the [`GlobalAlloc::alloc`] method
63 /// of the allocator registered with the `#[global_allocator]` attribute
64 /// if there is one, or the `std` crate’s default.
66 /// This function is expected to be deprecated in favor of the `alloc` method
67 /// of the [`Global`] type when it and the [`Allocator`] trait become stable.
71 /// See [`GlobalAlloc::alloc`].
76 /// use std::alloc::{alloc, dealloc, handle_alloc_error, Layout};
79 /// let layout = Layout::new::<u16>();
80 /// let ptr = alloc(layout);
81 /// if ptr.is_null() {
82 /// handle_alloc_error(layout);
85 /// *(ptr as *mut u16) = 42;
86 /// assert_eq!(*(ptr as *mut u16), 42);
88 /// dealloc(ptr, layout);
91 #[stable(feature = "global_alloc", since = "1.28.0")]
92 #[must_use = "losing the pointer will leak memory"]
94 pub unsafe fn alloc(layout: Layout) -> *mut u8 {
95 unsafe { __rust_alloc(layout.size(), layout.align()) }
98 /// Deallocate memory with the global allocator.
100 /// This function forwards calls to the [`GlobalAlloc::dealloc`] method
101 /// of the allocator registered with the `#[global_allocator]` attribute
102 /// if there is one, or the `std` crate’s default.
104 /// This function is expected to be deprecated in favor of the `dealloc` method
105 /// of the [`Global`] type when it and the [`Allocator`] trait become stable.
109 /// See [`GlobalAlloc::dealloc`].
110 #[stable(feature = "global_alloc", since = "1.28.0")]
112 pub unsafe fn dealloc(ptr: *mut u8, layout: Layout) {
113 unsafe { __rust_dealloc(ptr, layout.size(), layout.align()) }
116 /// Reallocate memory with the global allocator.
118 /// This function forwards calls to the [`GlobalAlloc::realloc`] method
119 /// of the allocator registered with the `#[global_allocator]` attribute
120 /// if there is one, or the `std` crate’s default.
122 /// This function is expected to be deprecated in favor of the `realloc` method
123 /// of the [`Global`] type when it and the [`Allocator`] trait become stable.
127 /// See [`GlobalAlloc::realloc`].
128 #[stable(feature = "global_alloc", since = "1.28.0")]
129 #[must_use = "losing the pointer will leak memory"]
131 pub unsafe fn realloc(ptr: *mut u8, layout: Layout, new_size: usize) -> *mut u8 {
132 unsafe { __rust_realloc(ptr, layout.size(), layout.align(), new_size) }
135 /// Allocate zero-initialized memory with the global allocator.
137 /// This function forwards calls to the [`GlobalAlloc::alloc_zeroed`] method
138 /// of the allocator registered with the `#[global_allocator]` attribute
139 /// if there is one, or the `std` crate’s default.
141 /// This function is expected to be deprecated in favor of the `alloc_zeroed` method
142 /// of the [`Global`] type when it and the [`Allocator`] trait become stable.
146 /// See [`GlobalAlloc::alloc_zeroed`].
151 /// use std::alloc::{alloc_zeroed, dealloc, Layout};
154 /// let layout = Layout::new::<u16>();
155 /// let ptr = alloc_zeroed(layout);
157 /// assert_eq!(*(ptr as *mut u16), 0);
159 /// dealloc(ptr, layout);
162 #[stable(feature = "global_alloc", since = "1.28.0")]
163 #[must_use = "losing the pointer will leak memory"]
165 pub unsafe fn alloc_zeroed(layout: Layout) -> *mut u8 {
166 unsafe { __rust_alloc_zeroed(layout.size(), layout.align()) }
172 fn alloc_impl(&self, layout: Layout, zeroed: bool) -> Result<NonNull<[u8]>, AllocError> {
173 match layout.size() {
174 0 => Ok(NonNull::slice_from_raw_parts(layout.dangling(), 0)),
175 // SAFETY: `layout` is non-zero in size,
177 let raw_ptr = if zeroed { alloc_zeroed(layout) } else { alloc(layout) };
178 let ptr = NonNull::new(raw_ptr).ok_or(AllocError)?;
179 Ok(NonNull::slice_from_raw_parts(ptr, size))
184 // SAFETY: Same as `Allocator::grow`
192 ) -> Result<NonNull<[u8]>, AllocError> {
194 new_layout.size() >= old_layout.size(),
195 "`new_layout.size()` must be greater than or equal to `old_layout.size()`"
198 match old_layout.size() {
199 0 => self.alloc_impl(new_layout, zeroed),
201 // SAFETY: `new_size` is non-zero as `old_size` is greater than or equal to `new_size`
202 // as required by safety conditions. Other conditions must be upheld by the caller
203 old_size if old_layout.align() == new_layout.align() => unsafe {
204 let new_size = new_layout.size();
206 // `realloc` probably checks for `new_size >= old_layout.size()` or something similar.
207 intrinsics::assume(new_size >= old_layout.size());
209 let raw_ptr = realloc(ptr.as_ptr(), old_layout, new_size);
210 let ptr = NonNull::new(raw_ptr).ok_or(AllocError)?;
212 raw_ptr.add(old_size).write_bytes(0, new_size - old_size);
214 Ok(NonNull::slice_from_raw_parts(ptr, new_size))
217 // SAFETY: because `new_layout.size()` must be greater than or equal to `old_size`,
218 // both the old and new memory allocation are valid for reads and writes for `old_size`
219 // bytes. Also, because the old allocation wasn't yet deallocated, it cannot overlap
220 // `new_ptr`. Thus, the call to `copy_nonoverlapping` is safe. The safety contract
221 // for `dealloc` must be upheld by the caller.
223 let new_ptr = self.alloc_impl(new_layout, zeroed)?;
224 ptr::copy_nonoverlapping(ptr.as_ptr(), new_ptr.as_mut_ptr(), old_size);
225 self.deallocate(ptr, old_layout);
232 #[unstable(feature = "allocator_api", issue = "32838")]
234 unsafe impl Allocator for Global {
236 fn allocate(&self, layout: Layout) -> Result<NonNull<[u8]>, AllocError> {
237 self.alloc_impl(layout, false)
241 fn allocate_zeroed(&self, layout: Layout) -> Result<NonNull<[u8]>, AllocError> {
242 self.alloc_impl(layout, true)
246 unsafe fn deallocate(&self, ptr: NonNull<u8>, layout: Layout) {
247 if layout.size() != 0 {
248 // SAFETY: `layout` is non-zero in size,
249 // other conditions must be upheld by the caller
250 unsafe { dealloc(ptr.as_ptr(), layout) }
260 ) -> Result<NonNull<[u8]>, AllocError> {
261 // SAFETY: all conditions must be upheld by the caller
262 unsafe { self.grow_impl(ptr, old_layout, new_layout, false) }
266 unsafe fn grow_zeroed(
271 ) -> Result<NonNull<[u8]>, AllocError> {
272 // SAFETY: all conditions must be upheld by the caller
273 unsafe { self.grow_impl(ptr, old_layout, new_layout, true) }
282 ) -> Result<NonNull<[u8]>, AllocError> {
284 new_layout.size() <= old_layout.size(),
285 "`new_layout.size()` must be smaller than or equal to `old_layout.size()`"
288 match new_layout.size() {
289 // SAFETY: conditions must be upheld by the caller
291 self.deallocate(ptr, old_layout);
292 Ok(NonNull::slice_from_raw_parts(new_layout.dangling(), 0))
295 // SAFETY: `new_size` is non-zero. Other conditions must be upheld by the caller
296 new_size if old_layout.align() == new_layout.align() => unsafe {
297 // `realloc` probably checks for `new_size <= old_layout.size()` or something similar.
298 intrinsics::assume(new_size <= old_layout.size());
300 let raw_ptr = realloc(ptr.as_ptr(), old_layout, new_size);
301 let ptr = NonNull::new(raw_ptr).ok_or(AllocError)?;
302 Ok(NonNull::slice_from_raw_parts(ptr, new_size))
305 // SAFETY: because `new_size` must be smaller than or equal to `old_layout.size()`,
306 // both the old and new memory allocation are valid for reads and writes for `new_size`
307 // bytes. Also, because the old allocation wasn't yet deallocated, it cannot overlap
308 // `new_ptr`. Thus, the call to `copy_nonoverlapping` is safe. The safety contract
309 // for `dealloc` must be upheld by the caller.
311 let new_ptr = self.allocate(new_layout)?;
312 ptr::copy_nonoverlapping(ptr.as_ptr(), new_ptr.as_mut_ptr(), new_size);
313 self.deallocate(ptr, old_layout);
320 /// The allocator for unique pointers.
321 #[cfg(all(not(no_global_oom_handling), not(test)))]
322 #[lang = "exchange_malloc"]
324 unsafe fn exchange_malloc(size: usize, align: usize) -> *mut u8 {
325 let layout = unsafe { Layout::from_size_align_unchecked(size, align) };
326 match Global.allocate(layout) {
327 Ok(ptr) => ptr.as_mut_ptr(),
328 Err(_) => handle_alloc_error(layout),
332 #[cfg_attr(not(test), lang = "box_free")]
334 #[rustc_const_unstable(feature = "const_box", issue = "92521")]
335 // This signature has to be the same as `Box`, otherwise an ICE will happen.
336 // When an additional parameter to `Box` is added (like `A: Allocator`), this has to be added here as
338 // For example if `Box` is changed to `struct Box<T: ?Sized, A: Allocator>(Unique<T>, A)`,
339 // this function has to be changed to `fn box_free<T: ?Sized, A: Allocator>(Unique<T>, A)` as well.
340 pub(crate) const unsafe fn box_free<T: ?Sized, A: ~const Allocator + ~const Destruct>(
345 let size = size_of_val(ptr.as_ref());
346 let align = min_align_of_val(ptr.as_ref());
347 let layout = Layout::from_size_align_unchecked(size, align);
348 alloc.deallocate(From::from(ptr.cast()), layout)
352 // # Allocation error handler
354 #[cfg(not(no_global_oom_handling))]
356 // This is the magic symbol to call the global alloc error handler. rustc generates
357 // it to call `__rg_oom` if there is a `#[alloc_error_handler]`, or to call the
358 // default implementations below (`__rdl_oom`) otherwise.
359 fn __rust_alloc_error_handler(size: usize, align: usize) -> !;
362 /// Abort on memory allocation error or failure.
364 /// Callers of memory allocation APIs wishing to abort computation
365 /// in response to an allocation error are encouraged to call this function,
366 /// rather than directly invoking `panic!` or similar.
368 /// The default behavior of this function is to print a message to standard error
369 /// and abort the process.
370 /// It can be replaced with [`set_alloc_error_hook`] and [`take_alloc_error_hook`].
372 /// [`set_alloc_error_hook`]: ../../std/alloc/fn.set_alloc_error_hook.html
373 /// [`take_alloc_error_hook`]: ../../std/alloc/fn.take_alloc_error_hook.html
374 #[stable(feature = "global_alloc", since = "1.28.0")]
375 #[rustc_const_unstable(feature = "const_alloc_error", issue = "92523")]
376 #[cfg(all(not(no_global_oom_handling), not(test)))]
378 pub const fn handle_alloc_error(layout: Layout) -> ! {
379 const fn ct_error(_: Layout) -> ! {
380 panic!("allocation failed");
383 fn rt_error(layout: Layout) -> ! {
385 __rust_alloc_error_handler(layout.size(), layout.align());
389 unsafe { core::intrinsics::const_eval_select((layout,), ct_error, rt_error) }
392 // For alloc test `std::alloc::handle_alloc_error` can be used directly.
393 #[cfg(all(not(no_global_oom_handling), test))]
394 pub use std::alloc::handle_alloc_error;
396 #[cfg(all(not(no_global_oom_handling), not(test)))]
398 #[allow(unused_attributes)]
399 #[unstable(feature = "alloc_internals", issue = "none")]
400 pub mod __alloc_error_handler {
401 // called via generated `__rust_alloc_error_handler` if there is no
402 // `#[alloc_error_handler]`.
403 #[rustc_std_internal_symbol]
404 pub unsafe fn __rdl_oom(size: usize, _align: usize) -> ! {
405 panic!("memory allocation of {size} bytes failed")
409 #[rustc_std_internal_symbol]
410 pub unsafe fn __rg_oom(size: usize, align: usize) -> ! {
411 use crate::alloc::Layout;
413 let layout = unsafe { Layout::from_size_align_unchecked(size, align) };
416 fn oom_impl(layout: Layout) -> !;
418 unsafe { oom_impl(layout) }
422 /// Specialize clones into pre-allocated, uninitialized memory.
423 /// Used by `Box::clone` and `Rc`/`Arc::make_mut`.
424 pub(crate) trait WriteCloneIntoRaw: Sized {
425 unsafe fn write_clone_into_raw(&self, target: *mut Self);
428 impl<T: Clone> WriteCloneIntoRaw for T {
430 default unsafe fn write_clone_into_raw(&self, target: *mut Self) {
431 // Having allocated *first* may allow the optimizer to create
432 // the cloned value in-place, skipping the local and move.
433 unsafe { target.write(self.clone()) };
437 impl<T: Copy> WriteCloneIntoRaw for T {
439 unsafe fn write_clone_into_raw(&self, target: *mut Self) {
440 // We can always copy in-place, without ever involving a local value.
441 unsafe { target.copy_from_nonoverlapping(self, 1) };