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::*;
21 // These are the magic symbols to call the global allocator. rustc generates
22 // them to call `__rg_alloc` etc. if there is a `#[global_allocator]` attribute
23 // (the code expanding that attribute macro generates those functions), or to call
24 // the default implementations in libstd (`__rdl_alloc` etc. in `library/std/src/alloc.rs`)
26 // The rustc fork of LLVM also special-cases these function names to be able to optimize them
27 // like `malloc`, `realloc`, and `free`, respectively.
29 #[rustc_allocator_nounwind]
30 fn __rust_alloc(size: usize, align: usize) -> *mut u8;
31 #[rustc_allocator_nounwind]
32 fn __rust_dealloc(ptr: *mut u8, size: usize, align: usize);
33 #[rustc_allocator_nounwind]
34 fn __rust_realloc(ptr: *mut u8, old_size: usize, align: usize, new_size: usize) -> *mut u8;
35 #[rustc_allocator_nounwind]
36 fn __rust_alloc_zeroed(size: usize, align: usize) -> *mut u8;
39 /// The global memory allocator.
41 /// This type implements the [`Allocator`] trait by forwarding calls
42 /// to the allocator registered with the `#[global_allocator]` attribute
43 /// if there is one, or the `std` crate’s default.
45 /// Note: while this type is unstable, the functionality it provides can be
46 /// accessed through the [free functions in `alloc`](self#functions).
47 #[unstable(feature = "allocator_api", issue = "32838")]
48 #[derive(Copy, Clone, Default, Debug)]
53 pub use std::alloc::Global;
55 /// Allocate memory with the global allocator.
57 /// This function forwards calls to the [`GlobalAlloc::alloc`] method
58 /// of the allocator registered with the `#[global_allocator]` attribute
59 /// if there is one, or the `std` crate’s default.
61 /// This function is expected to be deprecated in favor of the `alloc` method
62 /// of the [`Global`] type when it and the [`Allocator`] trait become stable.
66 /// See [`GlobalAlloc::alloc`].
71 /// use std::alloc::{alloc, dealloc, Layout};
74 /// let layout = Layout::new::<u16>();
75 /// let ptr = alloc(layout);
77 /// *(ptr as *mut u16) = 42;
78 /// assert_eq!(*(ptr as *mut u16), 42);
80 /// dealloc(ptr, layout);
83 #[stable(feature = "global_alloc", since = "1.28.0")]
84 #[must_use = "losing the pointer will leak memory"]
86 pub unsafe fn alloc(layout: Layout) -> *mut u8 {
87 unsafe { __rust_alloc(layout.size(), layout.align()) }
90 /// Deallocate memory with the global allocator.
92 /// This function forwards calls to the [`GlobalAlloc::dealloc`] method
93 /// of the allocator registered with the `#[global_allocator]` attribute
94 /// if there is one, or the `std` crate’s default.
96 /// This function is expected to be deprecated in favor of the `dealloc` method
97 /// of the [`Global`] type when it and the [`Allocator`] trait become stable.
101 /// See [`GlobalAlloc::dealloc`].
102 #[stable(feature = "global_alloc", since = "1.28.0")]
104 pub unsafe fn dealloc(ptr: *mut u8, layout: Layout) {
105 unsafe { __rust_dealloc(ptr, layout.size(), layout.align()) }
108 /// Reallocate memory with the global allocator.
110 /// This function forwards calls to the [`GlobalAlloc::realloc`] 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 `realloc` method
115 /// of the [`Global`] type when it and the [`Allocator`] trait become stable.
119 /// See [`GlobalAlloc::realloc`].
120 #[stable(feature = "global_alloc", since = "1.28.0")]
121 #[must_use = "losing the pointer will leak memory"]
123 pub unsafe fn realloc(ptr: *mut u8, layout: Layout, new_size: usize) -> *mut u8 {
124 unsafe { __rust_realloc(ptr, layout.size(), layout.align(), new_size) }
127 /// Allocate zero-initialized memory with the global allocator.
129 /// This function forwards calls to the [`GlobalAlloc::alloc_zeroed`] method
130 /// of the allocator registered with the `#[global_allocator]` attribute
131 /// if there is one, or the `std` crate’s default.
133 /// This function is expected to be deprecated in favor of the `alloc_zeroed` method
134 /// of the [`Global`] type when it and the [`Allocator`] trait become stable.
138 /// See [`GlobalAlloc::alloc_zeroed`].
143 /// use std::alloc::{alloc_zeroed, dealloc, Layout};
146 /// let layout = Layout::new::<u16>();
147 /// let ptr = alloc_zeroed(layout);
149 /// assert_eq!(*(ptr as *mut u16), 0);
151 /// dealloc(ptr, layout);
154 #[stable(feature = "global_alloc", since = "1.28.0")]
155 #[must_use = "losing the pointer will leak memory"]
157 pub unsafe fn alloc_zeroed(layout: Layout) -> *mut u8 {
158 unsafe { __rust_alloc_zeroed(layout.size(), layout.align()) }
164 fn alloc_impl(&self, layout: Layout, zeroed: bool) -> Result<NonNull<[u8]>, AllocError> {
165 match layout.size() {
166 0 => Ok(NonNull::slice_from_raw_parts(layout.dangling(), 0)),
167 // SAFETY: `layout` is non-zero in size,
169 let raw_ptr = if zeroed { alloc_zeroed(layout) } else { alloc(layout) };
170 let ptr = NonNull::new(raw_ptr).ok_or(AllocError)?;
171 Ok(NonNull::slice_from_raw_parts(ptr, size))
176 // SAFETY: Same as `Allocator::grow`
184 ) -> Result<NonNull<[u8]>, AllocError> {
186 new_layout.size() >= old_layout.size(),
187 "`new_layout.size()` must be greater than or equal to `old_layout.size()`"
190 match old_layout.size() {
191 0 => self.alloc_impl(new_layout, zeroed),
193 // SAFETY: `new_size` is non-zero as `old_size` is greater than or equal to `new_size`
194 // as required by safety conditions. Other conditions must be upheld by the caller
195 old_size if old_layout.align() == new_layout.align() => unsafe {
196 let new_size = new_layout.size();
198 // `realloc` probably checks for `new_size >= old_layout.size()` or something similar.
199 intrinsics::assume(new_size >= old_layout.size());
201 let raw_ptr = realloc(ptr.as_ptr(), old_layout, new_size);
202 let ptr = NonNull::new(raw_ptr).ok_or(AllocError)?;
204 raw_ptr.add(old_size).write_bytes(0, new_size - old_size);
206 Ok(NonNull::slice_from_raw_parts(ptr, new_size))
209 // SAFETY: because `new_layout.size()` must be greater than or equal to `old_size`,
210 // both the old and new memory allocation are valid for reads and writes for `old_size`
211 // bytes. Also, because the old allocation wasn't yet deallocated, it cannot overlap
212 // `new_ptr`. Thus, the call to `copy_nonoverlapping` is safe. The safety contract
213 // for `dealloc` must be upheld by the caller.
215 let new_ptr = self.alloc_impl(new_layout, zeroed)?;
216 ptr::copy_nonoverlapping(ptr.as_ptr(), new_ptr.as_mut_ptr(), old_size);
217 self.deallocate(ptr, old_layout);
224 #[unstable(feature = "allocator_api", issue = "32838")]
226 unsafe impl Allocator for Global {
228 fn allocate(&self, layout: Layout) -> Result<NonNull<[u8]>, AllocError> {
229 self.alloc_impl(layout, false)
233 fn allocate_zeroed(&self, layout: Layout) -> Result<NonNull<[u8]>, AllocError> {
234 self.alloc_impl(layout, true)
238 unsafe fn deallocate(&self, ptr: NonNull<u8>, layout: Layout) {
239 if layout.size() != 0 {
240 // SAFETY: `layout` is non-zero in size,
241 // other conditions must be upheld by the caller
242 unsafe { dealloc(ptr.as_ptr(), layout) }
252 ) -> Result<NonNull<[u8]>, AllocError> {
253 // SAFETY: all conditions must be upheld by the caller
254 unsafe { self.grow_impl(ptr, old_layout, new_layout, false) }
258 unsafe fn grow_zeroed(
263 ) -> Result<NonNull<[u8]>, AllocError> {
264 // SAFETY: all conditions must be upheld by the caller
265 unsafe { self.grow_impl(ptr, old_layout, new_layout, true) }
274 ) -> Result<NonNull<[u8]>, AllocError> {
276 new_layout.size() <= old_layout.size(),
277 "`new_layout.size()` must be smaller than or equal to `old_layout.size()`"
280 match new_layout.size() {
281 // SAFETY: conditions must be upheld by the caller
283 self.deallocate(ptr, old_layout);
284 Ok(NonNull::slice_from_raw_parts(new_layout.dangling(), 0))
287 // SAFETY: `new_size` is non-zero. Other conditions must be upheld by the caller
288 new_size if old_layout.align() == new_layout.align() => unsafe {
289 // `realloc` probably checks for `new_size <= old_layout.size()` or something similar.
290 intrinsics::assume(new_size <= old_layout.size());
292 let raw_ptr = realloc(ptr.as_ptr(), old_layout, new_size);
293 let ptr = NonNull::new(raw_ptr).ok_or(AllocError)?;
294 Ok(NonNull::slice_from_raw_parts(ptr, new_size))
297 // SAFETY: because `new_size` must be smaller than or equal to `old_layout.size()`,
298 // both the old and new memory allocation are valid for reads and writes for `new_size`
299 // bytes. Also, because the old allocation wasn't yet deallocated, it cannot overlap
300 // `new_ptr`. Thus, the call to `copy_nonoverlapping` is safe. The safety contract
301 // for `dealloc` must be upheld by the caller.
303 let new_ptr = self.allocate(new_layout)?;
304 ptr::copy_nonoverlapping(ptr.as_ptr(), new_ptr.as_mut_ptr(), new_size);
305 self.deallocate(ptr, old_layout);
312 /// The allocator for unique pointers.
313 #[cfg(all(not(no_global_oom_handling), not(test)))]
314 #[lang = "exchange_malloc"]
316 unsafe fn exchange_malloc(size: usize, align: usize) -> *mut u8 {
317 let layout = unsafe { Layout::from_size_align_unchecked(size, align) };
318 match Global.allocate(layout) {
319 Ok(ptr) => ptr.as_mut_ptr(),
320 Err(_) => handle_alloc_error(layout),
324 #[cfg_attr(not(test), lang = "box_free")]
326 // This signature has to be the same as `Box`, otherwise an ICE will happen.
327 // When an additional parameter to `Box` is added (like `A: Allocator`), this has to be added here as
329 // For example if `Box` is changed to `struct Box<T: ?Sized, A: Allocator>(Unique<T>, A)`,
330 // this function has to be changed to `fn box_free<T: ?Sized, A: Allocator>(Unique<T>, A)` as well.
331 pub(crate) unsafe fn box_free<T: ?Sized, A: Allocator>(ptr: Unique<T>, alloc: A) {
333 let size = size_of_val(ptr.as_ref());
334 let align = min_align_of_val(ptr.as_ref());
335 let layout = Layout::from_size_align_unchecked(size, align);
336 alloc.deallocate(ptr.cast().into(), layout)
340 // # Allocation error handler
342 #[cfg(not(no_global_oom_handling))]
344 // This is the magic symbol to call the global alloc error handler. rustc generates
345 // it to call `__rg_oom` if there is a `#[alloc_error_handler]`, or to call the
346 // default implementations below (`__rdl_oom`) otherwise.
347 #[rustc_allocator_nounwind]
348 fn __rust_alloc_error_handler(size: usize, align: usize) -> !;
351 /// Abort on memory allocation error or failure.
353 /// Callers of memory allocation APIs wishing to abort computation
354 /// in response to an allocation error are encouraged to call this function,
355 /// rather than directly invoking `panic!` or similar.
357 /// The default behavior of this function is to print a message to standard error
358 /// and abort the process.
359 /// It can be replaced with [`set_alloc_error_hook`] and [`take_alloc_error_hook`].
361 /// [`set_alloc_error_hook`]: ../../std/alloc/fn.set_alloc_error_hook.html
362 /// [`take_alloc_error_hook`]: ../../std/alloc/fn.take_alloc_error_hook.html
363 #[stable(feature = "global_alloc", since = "1.28.0")]
364 #[cfg(all(not(no_global_oom_handling), not(test)))]
365 #[rustc_allocator_nounwind]
367 pub fn handle_alloc_error(layout: Layout) -> ! {
369 __rust_alloc_error_handler(layout.size(), layout.align());
373 // For alloc test `std::alloc::handle_alloc_error` can be used directly.
374 #[cfg(all(not(no_global_oom_handling), test))]
375 pub use std::alloc::handle_alloc_error;
377 #[cfg(all(not(no_global_oom_handling), not(any(target_os = "hermit", test))))]
379 #[allow(unused_attributes)]
380 #[unstable(feature = "alloc_internals", issue = "none")]
381 pub mod __alloc_error_handler {
382 use crate::alloc::Layout;
384 // called via generated `__rust_alloc_error_handler`
386 // if there is no `#[alloc_error_handler]`
387 #[rustc_std_internal_symbol]
388 pub unsafe extern "C" fn __rdl_oom(size: usize, _align: usize) -> ! {
389 panic!("memory allocation of {} bytes failed", size)
392 // if there is an `#[alloc_error_handler]`
393 #[rustc_std_internal_symbol]
394 pub unsafe extern "C" fn __rg_oom(size: usize, align: usize) -> ! {
395 let layout = unsafe { Layout::from_size_align_unchecked(size, align) };
398 fn oom_impl(layout: Layout) -> !;
400 unsafe { oom_impl(layout) }
404 /// Specialize clones into pre-allocated, uninitialized memory.
405 /// Used by `Box::clone` and `Rc`/`Arc::make_mut`.
406 pub(crate) trait WriteCloneIntoRaw: Sized {
407 unsafe fn write_clone_into_raw(&self, target: *mut Self);
410 impl<T: Clone> WriteCloneIntoRaw for T {
412 default unsafe fn write_clone_into_raw(&self, target: *mut Self) {
413 // Having allocated *first* may allow the optimizer to create
414 // the cloned value in-place, skipping the local and move.
415 unsafe { target.write(self.clone()) };
419 impl<T: Copy> WriteCloneIntoRaw for T {
421 unsafe fn write_clone_into_raw(&self, target: *mut Self) {
422 // We can always copy in-place, without ever involving a local value.
423 unsafe { target.copy_from_nonoverlapping(self, 1) };