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 also special-cases these function names to be able to optimize them
29 // like `malloc`, `realloc`, and `free`, respectively.
31 #[rustc_allocator_nounwind]
32 fn __rust_alloc(size: usize, align: usize) -> *mut u8;
33 #[rustc_allocator_nounwind]
34 fn __rust_dealloc(ptr: *mut u8, size: usize, align: usize);
35 #[rustc_allocator_nounwind]
36 fn __rust_realloc(ptr: *mut u8, old_size: usize, align: usize, new_size: usize) -> *mut u8;
37 #[rustc_allocator_nounwind]
38 fn __rust_alloc_zeroed(size: usize, align: usize) -> *mut u8;
41 /// The global memory allocator.
43 /// This type implements the [`Allocator`] trait by forwarding calls
44 /// to the allocator registered with the `#[global_allocator]` attribute
45 /// if there is one, or the `std` crate’s default.
47 /// Note: while this type is unstable, the functionality it provides can be
48 /// accessed through the [free functions in `alloc`](self#functions).
49 #[unstable(feature = "allocator_api", issue = "32838")]
50 #[derive(Copy, Clone, Default, Debug)]
55 pub use std::alloc::Global;
57 /// Allocate memory with the global allocator.
59 /// This function forwards calls to the [`GlobalAlloc::alloc`] method
60 /// of the allocator registered with the `#[global_allocator]` attribute
61 /// if there is one, or the `std` crate’s default.
63 /// This function is expected to be deprecated in favor of the `alloc` method
64 /// of the [`Global`] type when it and the [`Allocator`] trait become stable.
68 /// See [`GlobalAlloc::alloc`].
73 /// use std::alloc::{alloc, dealloc, Layout};
76 /// let layout = Layout::new::<u16>();
77 /// let ptr = alloc(layout);
79 /// *(ptr as *mut u16) = 42;
80 /// assert_eq!(*(ptr as *mut u16), 42);
82 /// dealloc(ptr, layout);
85 #[stable(feature = "global_alloc", since = "1.28.0")]
86 #[must_use = "losing the pointer will leak memory"]
88 pub unsafe fn alloc(layout: Layout) -> *mut u8 {
89 unsafe { __rust_alloc(layout.size(), layout.align()) }
92 /// Deallocate memory with the global allocator.
94 /// This function forwards calls to the [`GlobalAlloc::dealloc`] method
95 /// of the allocator registered with the `#[global_allocator]` attribute
96 /// if there is one, or the `std` crate’s default.
98 /// This function is expected to be deprecated in favor of the `dealloc` method
99 /// of the [`Global`] type when it and the [`Allocator`] trait become stable.
103 /// See [`GlobalAlloc::dealloc`].
104 #[stable(feature = "global_alloc", since = "1.28.0")]
106 pub unsafe fn dealloc(ptr: *mut u8, layout: Layout) {
107 unsafe { __rust_dealloc(ptr, layout.size(), layout.align()) }
110 /// Reallocate memory with the global allocator.
112 /// This function forwards calls to the [`GlobalAlloc::realloc`] method
113 /// of the allocator registered with the `#[global_allocator]` attribute
114 /// if there is one, or the `std` crate’s default.
116 /// This function is expected to be deprecated in favor of the `realloc` method
117 /// of the [`Global`] type when it and the [`Allocator`] trait become stable.
121 /// See [`GlobalAlloc::realloc`].
122 #[stable(feature = "global_alloc", since = "1.28.0")]
123 #[must_use = "losing the pointer will leak memory"]
125 pub unsafe fn realloc(ptr: *mut u8, layout: Layout, new_size: usize) -> *mut u8 {
126 unsafe { __rust_realloc(ptr, layout.size(), layout.align(), new_size) }
129 /// Allocate zero-initialized memory with the global allocator.
131 /// This function forwards calls to the [`GlobalAlloc::alloc_zeroed`] method
132 /// of the allocator registered with the `#[global_allocator]` attribute
133 /// if there is one, or the `std` crate’s default.
135 /// This function is expected to be deprecated in favor of the `alloc_zeroed` method
136 /// of the [`Global`] type when it and the [`Allocator`] trait become stable.
140 /// See [`GlobalAlloc::alloc_zeroed`].
145 /// use std::alloc::{alloc_zeroed, dealloc, Layout};
148 /// let layout = Layout::new::<u16>();
149 /// let ptr = alloc_zeroed(layout);
151 /// assert_eq!(*(ptr as *mut u16), 0);
153 /// dealloc(ptr, layout);
156 #[stable(feature = "global_alloc", since = "1.28.0")]
157 #[must_use = "losing the pointer will leak memory"]
159 pub unsafe fn alloc_zeroed(layout: Layout) -> *mut u8 {
160 unsafe { __rust_alloc_zeroed(layout.size(), layout.align()) }
166 fn alloc_impl(&self, layout: Layout, zeroed: bool) -> Result<NonNull<[u8]>, AllocError> {
167 match layout.size() {
168 0 => Ok(NonNull::slice_from_raw_parts(layout.dangling(), 0)),
169 // SAFETY: `layout` is non-zero in size,
171 let raw_ptr = if zeroed { alloc_zeroed(layout) } else { alloc(layout) };
172 let ptr = NonNull::new(raw_ptr).ok_or(AllocError)?;
173 Ok(NonNull::slice_from_raw_parts(ptr, size))
178 // SAFETY: Same as `Allocator::grow`
186 ) -> Result<NonNull<[u8]>, AllocError> {
188 new_layout.size() >= old_layout.size(),
189 "`new_layout.size()` must be greater than or equal to `old_layout.size()`"
192 match old_layout.size() {
193 0 => self.alloc_impl(new_layout, zeroed),
195 // SAFETY: `new_size` is non-zero as `old_size` is greater than or equal to `new_size`
196 // as required by safety conditions. Other conditions must be upheld by the caller
197 old_size if old_layout.align() == new_layout.align() => unsafe {
198 let new_size = new_layout.size();
200 // `realloc` probably checks for `new_size >= old_layout.size()` or something similar.
201 intrinsics::assume(new_size >= old_layout.size());
203 let raw_ptr = realloc(ptr.as_ptr(), old_layout, new_size);
204 let ptr = NonNull::new(raw_ptr).ok_or(AllocError)?;
206 raw_ptr.add(old_size).write_bytes(0, new_size - old_size);
208 Ok(NonNull::slice_from_raw_parts(ptr, new_size))
211 // SAFETY: because `new_layout.size()` must be greater than or equal to `old_size`,
212 // both the old and new memory allocation are valid for reads and writes for `old_size`
213 // bytes. Also, because the old allocation wasn't yet deallocated, it cannot overlap
214 // `new_ptr`. Thus, the call to `copy_nonoverlapping` is safe. The safety contract
215 // for `dealloc` must be upheld by the caller.
217 let new_ptr = self.alloc_impl(new_layout, zeroed)?;
218 ptr::copy_nonoverlapping(ptr.as_ptr(), new_ptr.as_mut_ptr(), old_size);
219 self.deallocate(ptr, old_layout);
226 #[unstable(feature = "allocator_api", issue = "32838")]
228 unsafe impl Allocator for Global {
230 fn allocate(&self, layout: Layout) -> Result<NonNull<[u8]>, AllocError> {
231 self.alloc_impl(layout, false)
235 fn allocate_zeroed(&self, layout: Layout) -> Result<NonNull<[u8]>, AllocError> {
236 self.alloc_impl(layout, true)
240 unsafe fn deallocate(&self, ptr: NonNull<u8>, layout: Layout) {
241 if layout.size() != 0 {
242 // SAFETY: `layout` is non-zero in size,
243 // other conditions must be upheld by the caller
244 unsafe { dealloc(ptr.as_ptr(), layout) }
254 ) -> Result<NonNull<[u8]>, AllocError> {
255 // SAFETY: all conditions must be upheld by the caller
256 unsafe { self.grow_impl(ptr, old_layout, new_layout, false) }
260 unsafe fn grow_zeroed(
265 ) -> Result<NonNull<[u8]>, AllocError> {
266 // SAFETY: all conditions must be upheld by the caller
267 unsafe { self.grow_impl(ptr, old_layout, new_layout, true) }
276 ) -> Result<NonNull<[u8]>, AllocError> {
278 new_layout.size() <= old_layout.size(),
279 "`new_layout.size()` must be smaller than or equal to `old_layout.size()`"
282 match new_layout.size() {
283 // SAFETY: conditions must be upheld by the caller
285 self.deallocate(ptr, old_layout);
286 Ok(NonNull::slice_from_raw_parts(new_layout.dangling(), 0))
289 // SAFETY: `new_size` is non-zero. Other conditions must be upheld by the caller
290 new_size if old_layout.align() == new_layout.align() => unsafe {
291 // `realloc` probably checks for `new_size <= old_layout.size()` or something similar.
292 intrinsics::assume(new_size <= old_layout.size());
294 let raw_ptr = realloc(ptr.as_ptr(), old_layout, new_size);
295 let ptr = NonNull::new(raw_ptr).ok_or(AllocError)?;
296 Ok(NonNull::slice_from_raw_parts(ptr, new_size))
299 // SAFETY: because `new_size` must be smaller than or equal to `old_layout.size()`,
300 // both the old and new memory allocation are valid for reads and writes for `new_size`
301 // bytes. Also, because the old allocation wasn't yet deallocated, it cannot overlap
302 // `new_ptr`. Thus, the call to `copy_nonoverlapping` is safe. The safety contract
303 // for `dealloc` must be upheld by the caller.
305 let new_ptr = self.allocate(new_layout)?;
306 ptr::copy_nonoverlapping(ptr.as_ptr(), new_ptr.as_mut_ptr(), new_size);
307 self.deallocate(ptr, old_layout);
314 /// The allocator for unique pointers.
315 #[cfg(all(not(no_global_oom_handling), not(test)))]
316 #[lang = "exchange_malloc"]
318 unsafe fn exchange_malloc(size: usize, align: usize) -> *mut u8 {
319 let layout = unsafe { Layout::from_size_align_unchecked(size, align) };
320 match Global.allocate(layout) {
321 Ok(ptr) => ptr.as_mut_ptr(),
322 Err(_) => handle_alloc_error(layout),
326 #[cfg_attr(not(test), lang = "box_free")]
328 #[rustc_const_unstable(feature = "const_box", issue = "92521")]
329 // This signature has to be the same as `Box`, otherwise an ICE will happen.
330 // When an additional parameter to `Box` is added (like `A: Allocator`), this has to be added here as
332 // For example if `Box` is changed to `struct Box<T: ?Sized, A: Allocator>(Unique<T>, A)`,
333 // this function has to be changed to `fn box_free<T: ?Sized, A: Allocator>(Unique<T>, A)` as well.
334 pub(crate) const unsafe fn box_free<T: ?Sized, A: ~const Allocator + ~const Destruct>(
339 let size = size_of_val(ptr.as_ref());
340 let align = min_align_of_val(ptr.as_ref());
341 let layout = Layout::from_size_align_unchecked(size, align);
342 alloc.deallocate(From::from(ptr.cast()), layout)
346 // # Allocation error handler
348 #[cfg(not(no_global_oom_handling))]
350 // This is the magic symbol to call the global alloc error handler. rustc generates
351 // it to call `__rg_oom` if there is a `#[alloc_error_handler]`, or to call the
352 // default implementations below (`__rdl_oom`) otherwise.
353 fn __rust_alloc_error_handler(size: usize, align: usize) -> !;
356 /// Abort on memory allocation error or failure.
358 /// Callers of memory allocation APIs wishing to abort computation
359 /// in response to an allocation error are encouraged to call this function,
360 /// rather than directly invoking `panic!` or similar.
362 /// The default behavior of this function is to print a message to standard error
363 /// and abort the process.
364 /// It can be replaced with [`set_alloc_error_hook`] and [`take_alloc_error_hook`].
366 /// [`set_alloc_error_hook`]: ../../std/alloc/fn.set_alloc_error_hook.html
367 /// [`take_alloc_error_hook`]: ../../std/alloc/fn.take_alloc_error_hook.html
368 #[stable(feature = "global_alloc", since = "1.28.0")]
369 #[rustc_const_unstable(feature = "const_alloc_error", issue = "92523")]
370 #[cfg(all(not(no_global_oom_handling), not(test)))]
372 pub const fn handle_alloc_error(layout: Layout) -> ! {
373 const fn ct_error(_: Layout) -> ! {
374 panic!("allocation failed");
377 fn rt_error(layout: Layout) -> ! {
379 __rust_alloc_error_handler(layout.size(), layout.align());
383 unsafe { core::intrinsics::const_eval_select((layout,), ct_error, rt_error) }
386 // For alloc test `std::alloc::handle_alloc_error` can be used directly.
387 #[cfg(all(not(no_global_oom_handling), test))]
388 pub use std::alloc::handle_alloc_error;
390 #[cfg(all(not(no_global_oom_handling), not(any(target_os = "hermit", test))))]
392 #[allow(unused_attributes)]
393 #[unstable(feature = "alloc_internals", issue = "none")]
394 pub mod __alloc_error_handler {
395 use crate::alloc::Layout;
397 // called via generated `__rust_alloc_error_handler`
399 // if there is no `#[alloc_error_handler]`
400 #[rustc_std_internal_symbol]
401 pub unsafe extern "C-unwind" fn __rdl_oom(size: usize, _align: usize) -> ! {
402 panic!("memory allocation of {size} bytes failed")
405 // if there is an `#[alloc_error_handler]`
406 #[rustc_std_internal_symbol]
407 pub unsafe extern "C-unwind" fn __rg_oom(size: usize, align: usize) -> ! {
408 let layout = unsafe { Layout::from_size_align_unchecked(size, align) };
411 fn oom_impl(layout: Layout) -> !;
413 unsafe { oom_impl(layout) }
417 /// Specialize clones into pre-allocated, uninitialized memory.
418 /// Used by `Box::clone` and `Rc`/`Arc::make_mut`.
419 pub(crate) trait WriteCloneIntoRaw: Sized {
420 unsafe fn write_clone_into_raw(&self, target: *mut Self);
423 impl<T: Clone> WriteCloneIntoRaw for T {
425 default unsafe fn write_clone_into_raw(&self, target: *mut Self) {
426 // Having allocated *first* may allow the optimizer to create
427 // the cloned value in-place, skipping the local and move.
428 unsafe { target.write(self.clone()) };
432 impl<T: Copy> WriteCloneIntoRaw for T {
434 unsafe fn write_clone_into_raw(&self, target: *mut Self) {
435 // We can always copy in-place, without ever involving a local value.
436 unsafe { target.copy_from_nonoverlapping(self, 1) };