1 //! Memory allocation APIs
3 #![stable(feature = "alloc_module", since = "1.28.0")]
5 use core::intrinsics::{min_align_of_val, size_of_val};
6 use core::ptr::{NonNull, Unique};
9 #[stable(feature = "alloc_module", since = "1.28.0")]
11 pub use core::alloc::*;
14 // These are the magic symbols to call the global allocator. rustc generates
15 // them from the `#[global_allocator]` attribute if there is one, or uses the
16 // default implementations in libstd (`__rdl_alloc` etc in `src/libstd/alloc.rs`)
18 #[cfg_attr(bootstrap, allocator)]
19 #[cfg_attr(not(bootstrap), rustc_allocator)]
20 #[rustc_allocator_nounwind]
21 fn __rust_alloc(size: usize, align: usize) -> *mut u8;
22 #[rustc_allocator_nounwind]
23 fn __rust_dealloc(ptr: *mut u8, size: usize, align: usize);
24 #[rustc_allocator_nounwind]
25 fn __rust_realloc(ptr: *mut u8,
28 new_size: usize) -> *mut u8;
29 #[rustc_allocator_nounwind]
30 fn __rust_alloc_zeroed(size: usize, align: usize) -> *mut u8;
33 /// The global memory allocator.
35 /// This type implements the [`Alloc`] trait by forwarding calls
36 /// to the allocator registered with the `#[global_allocator]` attribute
37 /// if there is one, or the `std` crate’s default.
39 /// Note: while this type is unstable, the functionality it provides can be
40 /// accessed through the [free functions in `alloc`](index.html#functions).
42 /// [`Alloc`]: trait.Alloc.html
43 #[unstable(feature = "allocator_api", issue = "32838")]
44 #[derive(Copy, Clone, Default, Debug)]
47 /// Allocate memory with the global allocator.
49 /// This function forwards calls to the [`GlobalAlloc::alloc`] method
50 /// of the allocator registered with the `#[global_allocator]` attribute
51 /// if there is one, or the `std` crate’s default.
53 /// This function is expected to be deprecated in favor of the `alloc` method
54 /// of the [`Global`] type when it and the [`Alloc`] trait become stable.
58 /// See [`GlobalAlloc::alloc`].
60 /// [`Global`]: struct.Global.html
61 /// [`Alloc`]: trait.Alloc.html
62 /// [`GlobalAlloc::alloc`]: trait.GlobalAlloc.html#tymethod.alloc
67 /// use std::alloc::{alloc, dealloc, Layout};
70 /// let layout = Layout::new::<u16>();
71 /// let ptr = alloc(layout);
73 /// *(ptr as *mut u16) = 42;
74 /// assert_eq!(*(ptr as *mut u16), 42);
76 /// dealloc(ptr, layout);
79 #[stable(feature = "global_alloc", since = "1.28.0")]
81 pub unsafe fn alloc(layout: Layout) -> *mut u8 {
82 __rust_alloc(layout.size(), layout.align())
85 /// Deallocate memory with the global allocator.
87 /// This function forwards calls to the [`GlobalAlloc::dealloc`] method
88 /// of the allocator registered with the `#[global_allocator]` attribute
89 /// if there is one, or the `std` crate’s default.
91 /// This function is expected to be deprecated in favor of the `dealloc` method
92 /// of the [`Global`] type when it and the [`Alloc`] trait become stable.
96 /// See [`GlobalAlloc::dealloc`].
98 /// [`Global`]: struct.Global.html
99 /// [`Alloc`]: trait.Alloc.html
100 /// [`GlobalAlloc::dealloc`]: trait.GlobalAlloc.html#tymethod.dealloc
101 #[stable(feature = "global_alloc", since = "1.28.0")]
103 pub unsafe fn dealloc(ptr: *mut u8, layout: Layout) {
104 __rust_dealloc(ptr, layout.size(), layout.align())
107 /// Reallocate memory with the global allocator.
109 /// This function forwards calls to the [`GlobalAlloc::realloc`] method
110 /// of the allocator registered with the `#[global_allocator]` attribute
111 /// if there is one, or the `std` crate’s default.
113 /// This function is expected to be deprecated in favor of the `realloc` method
114 /// of the [`Global`] type when it and the [`Alloc`] trait become stable.
118 /// See [`GlobalAlloc::realloc`].
120 /// [`Global`]: struct.Global.html
121 /// [`Alloc`]: trait.Alloc.html
122 /// [`GlobalAlloc::realloc`]: trait.GlobalAlloc.html#method.realloc
123 #[stable(feature = "global_alloc", since = "1.28.0")]
125 pub unsafe fn realloc(ptr: *mut u8, layout: Layout, new_size: usize) -> *mut u8 {
126 __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 [`Alloc`] trait become stable.
140 /// See [`GlobalAlloc::alloc_zeroed`].
142 /// [`Global`]: struct.Global.html
143 /// [`Alloc`]: trait.Alloc.html
144 /// [`GlobalAlloc::alloc_zeroed`]: trait.GlobalAlloc.html#method.alloc_zeroed
149 /// use std::alloc::{alloc_zeroed, dealloc, Layout};
152 /// let layout = Layout::new::<u16>();
153 /// let ptr = alloc_zeroed(layout);
155 /// assert_eq!(*(ptr as *mut u16), 0);
157 /// dealloc(ptr, layout);
160 #[stable(feature = "global_alloc", since = "1.28.0")]
162 pub unsafe fn alloc_zeroed(layout: Layout) -> *mut u8 {
163 __rust_alloc_zeroed(layout.size(), layout.align())
166 #[unstable(feature = "allocator_api", issue = "32838")]
167 unsafe impl Alloc for Global {
169 unsafe fn alloc(&mut self, layout: Layout) -> Result<NonNull<u8>, AllocErr> {
170 NonNull::new(alloc(layout)).ok_or(AllocErr)
174 unsafe fn dealloc(&mut self, ptr: NonNull<u8>, layout: Layout) {
175 dealloc(ptr.as_ptr(), layout)
179 unsafe fn realloc(&mut self,
183 -> Result<NonNull<u8>, AllocErr>
185 NonNull::new(realloc(ptr.as_ptr(), layout, new_size)).ok_or(AllocErr)
189 unsafe fn alloc_zeroed(&mut self, layout: Layout) -> Result<NonNull<u8>, AllocErr> {
190 NonNull::new(alloc_zeroed(layout)).ok_or(AllocErr)
194 /// The allocator for unique pointers.
195 // This function must not unwind. If it does, MIR codegen will fail.
197 #[lang = "exchange_malloc"]
199 unsafe fn exchange_malloc(size: usize, align: usize) -> *mut u8 {
203 let layout = Layout::from_size_align_unchecked(size, align);
204 let ptr = alloc(layout);
208 handle_alloc_error(layout)
213 #[cfg_attr(not(test), lang = "box_free")]
215 pub(crate) unsafe fn box_free<T: ?Sized>(ptr: Unique<T>) {
216 let ptr = ptr.as_ptr();
217 let size = size_of_val(&*ptr);
218 let align = min_align_of_val(&*ptr);
219 // We do not allocate for Box<T> when T is ZST, so deallocation is also not necessary.
221 let layout = Layout::from_size_align_unchecked(size, align);
222 dealloc(ptr as *mut u8, layout);
226 /// Abort on memory allocation error or failure.
228 /// Callers of memory allocation APIs wishing to abort computation
229 /// in response to an allocation error are encouraged to call this function,
230 /// rather than directly invoking `panic!` or similar.
232 /// The default behavior of this function is to print a message to standard error
233 /// and abort the process.
234 /// It can be replaced with [`set_alloc_error_hook`] and [`take_alloc_error_hook`].
236 /// [`set_alloc_error_hook`]: ../../std/alloc/fn.set_alloc_error_hook.html
237 /// [`take_alloc_error_hook`]: ../../std/alloc/fn.take_alloc_error_hook.html
238 #[stable(feature = "global_alloc", since = "1.28.0")]
239 #[rustc_allocator_nounwind]
240 pub fn handle_alloc_error(layout: Layout) -> ! {
241 #[allow(improper_ctypes)]
244 fn oom_impl(layout: Layout) -> !;
246 unsafe { oom_impl(layout) }
253 use crate::boxed::Box;
254 use crate::alloc::{Global, Alloc, Layout, handle_alloc_error};
257 fn allocate_zeroed() {
259 let layout = Layout::from_size_align(1024, 1).unwrap();
260 let ptr = Global.alloc_zeroed(layout.clone())
261 .unwrap_or_else(|_| handle_alloc_error(layout));
263 let mut i = ptr.cast::<u8>().as_ptr();
264 let end = i.add(layout.size());
269 Global.dealloc(ptr, layout);
274 #[cfg(not(miri))] // Miri does not support benchmarks
275 fn alloc_owned_small(b: &mut Bencher) {
277 let _: Box<_> = box 10;