1 //! Memory allocation APIs
3 #![stable(feature = "alloc_module", since = "1.28.0")]
5 use core::intrinsics::{self, min_align_of_val, size_of_val};
6 use core::ptr::{NonNull, Unique};
7 use core::{mem, usize};
9 #[stable(feature = "alloc_module", since = "1.28.0")]
11 pub use core::alloc::*;
17 // These are the magic symbols to call the global allocator. rustc generates
18 // them from the `#[global_allocator]` attribute if there is one, or uses the
19 // default implementations in libstd (`__rdl_alloc` etc in `src/libstd/alloc.rs`)
22 #[rustc_allocator_nounwind]
23 fn __rust_alloc(size: usize, align: usize) -> *mut u8;
24 #[rustc_allocator_nounwind]
25 fn __rust_dealloc(ptr: *mut u8, size: usize, align: usize);
26 #[rustc_allocator_nounwind]
27 fn __rust_realloc(ptr: *mut u8, old_size: usize, align: usize, new_size: usize) -> *mut u8;
28 #[rustc_allocator_nounwind]
29 fn __rust_alloc_zeroed(size: usize, align: usize) -> *mut u8;
32 /// The global memory allocator.
34 /// This type implements the [`AllocRef`] trait by forwarding calls
35 /// to the allocator registered with the `#[global_allocator]` attribute
36 /// if there is one, or the `std` crate’s default.
38 /// Note: while this type is unstable, the functionality it provides can be
39 /// accessed through the [free functions in `alloc`](index.html#functions).
41 /// [`AllocRef`]: trait.AllocRef.html
42 #[unstable(feature = "allocator_api", issue = "32838")]
43 #[derive(Copy, Clone, Default, Debug)]
46 /// Allocate memory with the global allocator.
48 /// This function forwards calls to the [`GlobalAlloc::alloc`] method
49 /// of the allocator registered with the `#[global_allocator]` attribute
50 /// if there is one, or the `std` crate’s default.
52 /// This function is expected to be deprecated in favor of the `alloc` method
53 /// of the [`Global`] type when it and the [`AllocRef`] trait become stable.
57 /// See [`GlobalAlloc::alloc`].
59 /// [`Global`]: struct.Global.html
60 /// [`AllocRef`]: trait.AllocRef.html
61 /// [`GlobalAlloc::alloc`]: trait.GlobalAlloc.html#tymethod.alloc
66 /// use std::alloc::{alloc, dealloc, Layout};
69 /// let layout = Layout::new::<u16>();
70 /// let ptr = alloc(layout);
72 /// *(ptr as *mut u16) = 42;
73 /// assert_eq!(*(ptr as *mut u16), 42);
75 /// dealloc(ptr, layout);
78 #[stable(feature = "global_alloc", since = "1.28.0")]
80 pub unsafe fn alloc(layout: Layout) -> *mut u8 {
81 __rust_alloc(layout.size(), layout.align())
84 /// Deallocate memory with the global allocator.
86 /// This function forwards calls to the [`GlobalAlloc::dealloc`] method
87 /// of the allocator registered with the `#[global_allocator]` attribute
88 /// if there is one, or the `std` crate’s default.
90 /// This function is expected to be deprecated in favor of the `dealloc` method
91 /// of the [`Global`] type when it and the [`AllocRef`] trait become stable.
95 /// See [`GlobalAlloc::dealloc`].
97 /// [`Global`]: struct.Global.html
98 /// [`AllocRef`]: trait.AllocRef.html
99 /// [`GlobalAlloc::dealloc`]: trait.GlobalAlloc.html#tymethod.dealloc
100 #[stable(feature = "global_alloc", since = "1.28.0")]
102 pub unsafe fn dealloc(ptr: *mut u8, layout: Layout) {
103 __rust_dealloc(ptr, layout.size(), layout.align())
106 /// Reallocate memory with the global allocator.
108 /// This function forwards calls to the [`GlobalAlloc::realloc`] method
109 /// of the allocator registered with the `#[global_allocator]` attribute
110 /// if there is one, or the `std` crate’s default.
112 /// This function is expected to be deprecated in favor of the `realloc` method
113 /// of the [`Global`] type when it and the [`AllocRef`] trait become stable.
117 /// See [`GlobalAlloc::realloc`].
119 /// [`Global`]: struct.Global.html
120 /// [`AllocRef`]: trait.AllocRef.html
121 /// [`GlobalAlloc::realloc`]: trait.GlobalAlloc.html#method.realloc
122 #[stable(feature = "global_alloc", since = "1.28.0")]
124 pub unsafe fn realloc(ptr: *mut u8, layout: Layout, new_size: usize) -> *mut u8 {
125 __rust_realloc(ptr, layout.size(), layout.align(), new_size)
128 /// Allocate zero-initialized memory with the global allocator.
130 /// This function forwards calls to the [`GlobalAlloc::alloc_zeroed`] method
131 /// of the allocator registered with the `#[global_allocator]` attribute
132 /// if there is one, or the `std` crate’s default.
134 /// This function is expected to be deprecated in favor of the `alloc_zeroed` method
135 /// of the [`Global`] type when it and the [`AllocRef`] trait become stable.
139 /// See [`GlobalAlloc::alloc_zeroed`].
141 /// [`Global`]: struct.Global.html
142 /// [`AllocRef`]: trait.AllocRef.html
143 /// [`GlobalAlloc::alloc_zeroed`]: trait.GlobalAlloc.html#method.alloc_zeroed
148 /// use std::alloc::{alloc_zeroed, dealloc, Layout};
151 /// let layout = Layout::new::<u16>();
152 /// let ptr = alloc_zeroed(layout);
154 /// assert_eq!(*(ptr as *mut u16), 0);
156 /// dealloc(ptr, layout);
159 #[stable(feature = "global_alloc", since = "1.28.0")]
161 pub unsafe fn alloc_zeroed(layout: Layout) -> *mut u8 {
162 __rust_alloc_zeroed(layout.size(), layout.align())
165 #[unstable(feature = "allocator_api", issue = "32838")]
166 unsafe impl AllocRef for Global {
168 fn alloc(&mut self, layout: Layout, init: AllocInit) -> Result<MemoryBlock, AllocErr> {
170 if layout.size() == 0 {
171 Ok(MemoryBlock::new(layout.dangling(), layout))
173 let raw_ptr = match init {
174 AllocInit::Uninitialized => alloc(layout),
175 AllocInit::Zeroed => alloc_zeroed(layout),
177 let ptr = NonNull::new(raw_ptr).ok_or(AllocErr)?;
178 Ok(MemoryBlock::new(ptr, layout))
184 unsafe fn dealloc(&mut self, memory: MemoryBlock) {
185 if memory.size() != 0 {
186 dealloc(memory.ptr().as_ptr(), memory.layout())
193 memory: &mut MemoryBlock,
195 placement: ReallocPlacement,
197 ) -> Result<(), AllocErr> {
198 let old_size = memory.size();
200 new_size >= old_size,
201 "`new_size` must be greater than or equal to `memory.size()`"
204 if old_size == new_size {
208 let new_layout = Layout::from_size_align_unchecked(new_size, memory.align());
210 ReallocPlacement::InPlace => return Err(AllocErr),
211 ReallocPlacement::MayMove if memory.size() == 0 => {
212 *memory = self.alloc(new_layout, init)?
214 ReallocPlacement::MayMove => {
215 // `realloc` probably checks for `new_size > old_size` or something similar.
216 intrinsics::assume(new_size > old_size);
217 let ptr = realloc(memory.ptr().as_ptr(), memory.layout(), new_size);
218 *memory = MemoryBlock::new(NonNull::new(ptr).ok_or(AllocErr)?, new_layout);
219 memory.init_offset(init, old_size);
228 memory: &mut MemoryBlock,
230 placement: ReallocPlacement,
231 ) -> Result<(), AllocErr> {
232 let old_size = memory.size();
234 new_size <= old_size,
235 "`new_size` must be smaller than or equal to `memory.size()`"
238 if old_size == new_size {
242 let new_layout = Layout::from_size_align_unchecked(new_size, memory.align());
244 ReallocPlacement::InPlace => return Err(AllocErr),
245 ReallocPlacement::MayMove if new_size == 0 => {
246 let new_memory = MemoryBlock::new(new_layout.dangling(), new_layout);
247 let old_memory = mem::replace(memory, new_memory);
248 self.dealloc(old_memory)
250 ReallocPlacement::MayMove => {
251 // `realloc` probably checks for `new_size < old_size` or something similar.
252 intrinsics::assume(new_size < old_size);
253 let ptr = realloc(memory.ptr().as_ptr(), memory.layout(), new_size);
254 *memory = MemoryBlock::new(NonNull::new(ptr).ok_or(AllocErr)?, new_layout);
261 /// The allocator for unique pointers.
262 // This function must not unwind. If it does, MIR codegen will fail.
264 #[lang = "exchange_malloc"]
266 unsafe fn exchange_malloc(size: usize, align: usize) -> *mut u8 {
267 let layout = Layout::from_size_align_unchecked(size, align);
268 match Global.alloc(layout, AllocInit::Uninitialized) {
269 Ok(memory) => memory.ptr().as_ptr(),
270 Err(_) => handle_alloc_error(layout),
274 #[cfg_attr(not(test), lang = "box_free")]
276 // This signature has to be the same as `Box`, otherwise an ICE will happen.
277 // When an additional parameter to `Box` is added (like `A: AllocRef`), this has to be added here as
279 // For example if `Box` is changed to `struct Box<T: ?Sized, A: AllocRef>(Unique<T>, A)`,
280 // this function has to be changed to `fn box_free<T: ?Sized, A: AllocRef>(Unique<T>, A)` as well.
281 pub(crate) unsafe fn box_free<T: ?Sized>(ptr: Unique<T>) {
282 let size = size_of_val(ptr.as_ref());
283 let align = min_align_of_val(ptr.as_ref());
284 let layout = Layout::from_size_align_unchecked(size, align);
285 Global.dealloc(MemoryBlock::new(ptr.cast().into(), layout))
288 /// Abort on memory allocation error or failure.
290 /// Callers of memory allocation APIs wishing to abort computation
291 /// in response to an allocation error are encouraged to call this function,
292 /// rather than directly invoking `panic!` or similar.
294 /// The default behavior of this function is to print a message to standard error
295 /// and abort the process.
296 /// It can be replaced with [`set_alloc_error_hook`] and [`take_alloc_error_hook`].
298 /// [`set_alloc_error_hook`]: ../../std/alloc/fn.set_alloc_error_hook.html
299 /// [`take_alloc_error_hook`]: ../../std/alloc/fn.take_alloc_error_hook.html
300 #[stable(feature = "global_alloc", since = "1.28.0")]
301 #[rustc_allocator_nounwind]
302 pub fn handle_alloc_error(layout: Layout) -> ! {
305 fn oom_impl(layout: Layout) -> !;
307 unsafe { oom_impl(layout) }