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.
31 #[cfg_attr(not(bootstrap), rustc_nounwind)]
32 #[cfg_attr(bootstrap, rustc_allocator_nounwind)]
33 fn __rust_alloc(size: usize, align: usize) -> *mut u8;
35 #[cfg_attr(not(bootstrap), rustc_nounwind)]
36 #[cfg_attr(bootstrap, rustc_allocator_nounwind)]
37 fn __rust_dealloc(ptr: *mut u8, size: usize, align: usize);
39 #[cfg_attr(not(bootstrap), rustc_nounwind)]
40 #[cfg_attr(bootstrap, rustc_allocator_nounwind)]
41 fn __rust_realloc(ptr: *mut u8, old_size: usize, align: usize, new_size: usize) -> *mut u8;
42 #[rustc_allocator_zeroed]
43 #[cfg_attr(not(bootstrap), rustc_nounwind)]
44 #[cfg_attr(bootstrap, rustc_allocator_nounwind)]
45 fn __rust_alloc_zeroed(size: usize, align: usize) -> *mut u8;
48 /// The global memory allocator.
50 /// This type implements the [`Allocator`] trait by forwarding calls
51 /// to the allocator registered with the `#[global_allocator]` attribute
52 /// if there is one, or the `std` crate’s default.
54 /// Note: while this type is unstable, the functionality it provides can be
55 /// accessed through the [free functions in `alloc`](self#functions).
56 #[unstable(feature = "allocator_api", issue = "32838")]
57 #[derive(Copy, Clone, Default, Debug)]
62 pub use std::alloc::Global;
64 /// Allocate memory with the global allocator.
66 /// This function forwards calls to the [`GlobalAlloc::alloc`] method
67 /// of the allocator registered with the `#[global_allocator]` attribute
68 /// if there is one, or the `std` crate’s default.
70 /// This function is expected to be deprecated in favor of the `alloc` method
71 /// of the [`Global`] type when it and the [`Allocator`] trait become stable.
75 /// See [`GlobalAlloc::alloc`].
80 /// use std::alloc::{alloc, dealloc, handle_alloc_error, Layout};
83 /// let layout = Layout::new::<u16>();
84 /// let ptr = alloc(layout);
85 /// if ptr.is_null() {
86 /// handle_alloc_error(layout);
89 /// *(ptr as *mut u16) = 42;
90 /// assert_eq!(*(ptr as *mut u16), 42);
92 /// dealloc(ptr, layout);
95 #[stable(feature = "global_alloc", since = "1.28.0")]
96 #[must_use = "losing the pointer will leak memory"]
98 pub unsafe fn alloc(layout: Layout) -> *mut u8 {
99 unsafe { __rust_alloc(layout.size(), layout.align()) }
102 /// Deallocate memory with the global allocator.
104 /// This function forwards calls to the [`GlobalAlloc::dealloc`] method
105 /// of the allocator registered with the `#[global_allocator]` attribute
106 /// if there is one, or the `std` crate’s default.
108 /// This function is expected to be deprecated in favor of the `dealloc` method
109 /// of the [`Global`] type when it and the [`Allocator`] trait become stable.
113 /// See [`GlobalAlloc::dealloc`].
114 #[stable(feature = "global_alloc", since = "1.28.0")]
116 pub unsafe fn dealloc(ptr: *mut u8, layout: Layout) {
117 unsafe { __rust_dealloc(ptr, layout.size(), layout.align()) }
120 /// Reallocate memory with the global allocator.
122 /// This function forwards calls to the [`GlobalAlloc::realloc`] method
123 /// of the allocator registered with the `#[global_allocator]` attribute
124 /// if there is one, or the `std` crate’s default.
126 /// This function is expected to be deprecated in favor of the `realloc` method
127 /// of the [`Global`] type when it and the [`Allocator`] trait become stable.
131 /// See [`GlobalAlloc::realloc`].
132 #[stable(feature = "global_alloc", since = "1.28.0")]
133 #[must_use = "losing the pointer will leak memory"]
135 pub unsafe fn realloc(ptr: *mut u8, layout: Layout, new_size: usize) -> *mut u8 {
136 unsafe { __rust_realloc(ptr, layout.size(), layout.align(), new_size) }
139 /// Allocate zero-initialized memory with the global allocator.
141 /// This function forwards calls to the [`GlobalAlloc::alloc_zeroed`] method
142 /// of the allocator registered with the `#[global_allocator]` attribute
143 /// if there is one, or the `std` crate’s default.
145 /// This function is expected to be deprecated in favor of the `alloc_zeroed` method
146 /// of the [`Global`] type when it and the [`Allocator`] trait become stable.
150 /// See [`GlobalAlloc::alloc_zeroed`].
155 /// use std::alloc::{alloc_zeroed, dealloc, Layout};
158 /// let layout = Layout::new::<u16>();
159 /// let ptr = alloc_zeroed(layout);
161 /// assert_eq!(*(ptr as *mut u16), 0);
163 /// dealloc(ptr, layout);
166 #[stable(feature = "global_alloc", since = "1.28.0")]
167 #[must_use = "losing the pointer will leak memory"]
169 pub unsafe fn alloc_zeroed(layout: Layout) -> *mut u8 {
170 unsafe { __rust_alloc_zeroed(layout.size(), layout.align()) }
176 fn alloc_impl(&self, layout: Layout, zeroed: bool) -> Result<NonNull<[u8]>, AllocError> {
177 match layout.size() {
178 0 => Ok(NonNull::slice_from_raw_parts(layout.dangling(), 0)),
179 // SAFETY: `layout` is non-zero in size,
181 let raw_ptr = if zeroed { alloc_zeroed(layout) } else { alloc(layout) };
182 let ptr = NonNull::new(raw_ptr).ok_or(AllocError)?;
183 Ok(NonNull::slice_from_raw_parts(ptr, size))
188 // SAFETY: Same as `Allocator::grow`
196 ) -> Result<NonNull<[u8]>, AllocError> {
198 new_layout.size() >= old_layout.size(),
199 "`new_layout.size()` must be greater than or equal to `old_layout.size()`"
202 match old_layout.size() {
203 0 => self.alloc_impl(new_layout, zeroed),
205 // SAFETY: `new_size` is non-zero as `old_size` is greater than or equal to `new_size`
206 // as required by safety conditions. Other conditions must be upheld by the caller
207 old_size if old_layout.align() == new_layout.align() => unsafe {
208 let new_size = new_layout.size();
210 // `realloc` probably checks for `new_size >= old_layout.size()` or something similar.
211 intrinsics::assume(new_size >= old_layout.size());
213 let raw_ptr = realloc(ptr.as_ptr(), old_layout, new_size);
214 let ptr = NonNull::new(raw_ptr).ok_or(AllocError)?;
216 raw_ptr.add(old_size).write_bytes(0, new_size - old_size);
218 Ok(NonNull::slice_from_raw_parts(ptr, new_size))
221 // SAFETY: because `new_layout.size()` must be greater than or equal to `old_size`,
222 // both the old and new memory allocation are valid for reads and writes for `old_size`
223 // bytes. Also, because the old allocation wasn't yet deallocated, it cannot overlap
224 // `new_ptr`. Thus, the call to `copy_nonoverlapping` is safe. The safety contract
225 // for `dealloc` must be upheld by the caller.
227 let new_ptr = self.alloc_impl(new_layout, zeroed)?;
228 ptr::copy_nonoverlapping(ptr.as_ptr(), new_ptr.as_mut_ptr(), old_size);
229 self.deallocate(ptr, old_layout);
236 #[unstable(feature = "allocator_api", issue = "32838")]
238 unsafe impl Allocator for Global {
240 fn allocate(&self, layout: Layout) -> Result<NonNull<[u8]>, AllocError> {
241 self.alloc_impl(layout, false)
245 fn allocate_zeroed(&self, layout: Layout) -> Result<NonNull<[u8]>, AllocError> {
246 self.alloc_impl(layout, true)
250 unsafe fn deallocate(&self, ptr: NonNull<u8>, layout: Layout) {
251 if layout.size() != 0 {
252 // SAFETY: `layout` is non-zero in size,
253 // other conditions must be upheld by the caller
254 unsafe { dealloc(ptr.as_ptr(), layout) }
264 ) -> Result<NonNull<[u8]>, AllocError> {
265 // SAFETY: all conditions must be upheld by the caller
266 unsafe { self.grow_impl(ptr, old_layout, new_layout, false) }
270 unsafe fn grow_zeroed(
275 ) -> Result<NonNull<[u8]>, AllocError> {
276 // SAFETY: all conditions must be upheld by the caller
277 unsafe { self.grow_impl(ptr, old_layout, new_layout, true) }
286 ) -> Result<NonNull<[u8]>, AllocError> {
288 new_layout.size() <= old_layout.size(),
289 "`new_layout.size()` must be smaller than or equal to `old_layout.size()`"
292 match new_layout.size() {
293 // SAFETY: conditions must be upheld by the caller
295 self.deallocate(ptr, old_layout);
296 Ok(NonNull::slice_from_raw_parts(new_layout.dangling(), 0))
299 // SAFETY: `new_size` is non-zero. Other conditions must be upheld by the caller
300 new_size if old_layout.align() == new_layout.align() => unsafe {
301 // `realloc` probably checks for `new_size <= old_layout.size()` or something similar.
302 intrinsics::assume(new_size <= old_layout.size());
304 let raw_ptr = realloc(ptr.as_ptr(), old_layout, new_size);
305 let ptr = NonNull::new(raw_ptr).ok_or(AllocError)?;
306 Ok(NonNull::slice_from_raw_parts(ptr, new_size))
309 // SAFETY: because `new_size` must be smaller than or equal to `old_layout.size()`,
310 // both the old and new memory allocation are valid for reads and writes for `new_size`
311 // bytes. Also, because the old allocation wasn't yet deallocated, it cannot overlap
312 // `new_ptr`. Thus, the call to `copy_nonoverlapping` is safe. The safety contract
313 // for `dealloc` must be upheld by the caller.
315 let new_ptr = self.allocate(new_layout)?;
316 ptr::copy_nonoverlapping(ptr.as_ptr(), new_ptr.as_mut_ptr(), new_size);
317 self.deallocate(ptr, old_layout);
324 /// The allocator for unique pointers.
325 #[cfg(all(not(no_global_oom_handling), not(test)))]
326 #[lang = "exchange_malloc"]
328 unsafe fn exchange_malloc(size: usize, align: usize) -> *mut u8 {
329 let layout = unsafe { Layout::from_size_align_unchecked(size, align) };
330 match Global.allocate(layout) {
331 Ok(ptr) => ptr.as_mut_ptr(),
332 Err(_) => handle_alloc_error(layout),
336 #[cfg_attr(not(test), lang = "box_free")]
338 #[rustc_const_unstable(feature = "const_box", issue = "92521")]
339 // This signature has to be the same as `Box`, otherwise an ICE will happen.
340 // When an additional parameter to `Box` is added (like `A: Allocator`), this has to be added here as
342 // For example if `Box` is changed to `struct Box<T: ?Sized, A: Allocator>(Unique<T>, A)`,
343 // this function has to be changed to `fn box_free<T: ?Sized, A: Allocator>(Unique<T>, A)` as well.
344 pub(crate) const unsafe fn box_free<T: ?Sized, A: ~const Allocator + ~const Destruct>(
349 let size = size_of_val(ptr.as_ref());
350 let align = min_align_of_val(ptr.as_ref());
351 let layout = Layout::from_size_align_unchecked(size, align);
352 alloc.deallocate(From::from(ptr.cast()), layout)
356 // # Allocation error handler
358 #[cfg(not(no_global_oom_handling))]
360 // This is the magic symbol to call the global alloc error handler. rustc generates
361 // it to call `__rg_oom` if there is a `#[alloc_error_handler]`, or to call the
362 // default implementations below (`__rdl_oom`) otherwise.
363 fn __rust_alloc_error_handler(size: usize, align: usize) -> !;
366 /// Abort on memory allocation error or failure.
368 /// Callers of memory allocation APIs wishing to abort computation
369 /// in response to an allocation error are encouraged to call this function,
370 /// rather than directly invoking `panic!` or similar.
372 /// The default behavior of this function is to print a message to standard error
373 /// and abort the process.
374 /// It can be replaced with [`set_alloc_error_hook`] and [`take_alloc_error_hook`].
376 /// [`set_alloc_error_hook`]: ../../std/alloc/fn.set_alloc_error_hook.html
377 /// [`take_alloc_error_hook`]: ../../std/alloc/fn.take_alloc_error_hook.html
378 #[stable(feature = "global_alloc", since = "1.28.0")]
379 #[rustc_const_unstable(feature = "const_alloc_error", issue = "92523")]
380 #[cfg(all(not(no_global_oom_handling), not(test)))]
382 pub const fn handle_alloc_error(layout: Layout) -> ! {
383 const fn ct_error(_: Layout) -> ! {
384 panic!("allocation failed");
387 fn rt_error(layout: Layout) -> ! {
389 __rust_alloc_error_handler(layout.size(), layout.align());
393 unsafe { core::intrinsics::const_eval_select((layout,), ct_error, rt_error) }
396 // For alloc test `std::alloc::handle_alloc_error` can be used directly.
397 #[cfg(all(not(no_global_oom_handling), test))]
398 pub use std::alloc::handle_alloc_error;
400 #[cfg(all(not(no_global_oom_handling), not(test)))]
402 #[allow(unused_attributes)]
403 #[unstable(feature = "alloc_internals", issue = "none")]
404 pub mod __alloc_error_handler {
405 // called via generated `__rust_alloc_error_handler` if there is no
406 // `#[alloc_error_handler]`.
407 #[rustc_std_internal_symbol]
408 pub unsafe fn __rdl_oom(size: usize, _align: usize) -> ! {
409 panic!("memory allocation of {size} bytes failed")
413 #[rustc_std_internal_symbol]
414 pub unsafe fn __rg_oom(size: usize, align: usize) -> ! {
415 use crate::alloc::Layout;
417 let layout = unsafe { Layout::from_size_align_unchecked(size, align) };
420 fn oom_impl(layout: Layout) -> !;
422 unsafe { oom_impl(layout) }
426 /// Specialize clones into pre-allocated, uninitialized memory.
427 /// Used by `Box::clone` and `Rc`/`Arc::make_mut`.
428 pub(crate) trait WriteCloneIntoRaw: Sized {
429 unsafe fn write_clone_into_raw(&self, target: *mut Self);
432 impl<T: Clone> WriteCloneIntoRaw for T {
434 default unsafe fn write_clone_into_raw(&self, target: *mut Self) {
435 // Having allocated *first* may allow the optimizer to create
436 // the cloned value in-place, skipping the local and move.
437 unsafe { target.write(self.clone()) };
441 impl<T: Copy> WriteCloneIntoRaw for T {
443 unsafe fn write_clone_into_raw(&self, target: *mut Self) {
444 // We can always copy in-place, without ever involving a local value.
445 unsafe { target.copy_from_nonoverlapping(self, 1) };