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::{self, NonNull, Unique};
8 #[stable(feature = "alloc_module", since = "1.28.0")]
10 pub use core::alloc::*;
16 // These are the magic symbols to call the global allocator. rustc generates
17 // them to call `__rg_alloc` etc. if there is a `#[global_allocator]` attribute
18 // (the code expanding that attribute macro generates those functions), or to call
19 // the default implementations in libstd (`__rdl_alloc` etc. in `library/std/src/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`](self#functions).
40 #[unstable(feature = "allocator_api", issue = "32838")]
41 #[derive(Copy, Clone, Default, Debug)]
44 /// Allocate memory with the global allocator.
46 /// This function forwards calls to the [`GlobalAlloc::alloc`] method
47 /// of the allocator registered with the `#[global_allocator]` attribute
48 /// if there is one, or the `std` crate’s default.
50 /// This function is expected to be deprecated in favor of the `alloc` method
51 /// of the [`Global`] type when it and the [`AllocRef`] trait become stable.
55 /// See [`GlobalAlloc::alloc`].
60 /// use std::alloc::{alloc, dealloc, Layout};
63 /// let layout = Layout::new::<u16>();
64 /// let ptr = alloc(layout);
66 /// *(ptr as *mut u16) = 42;
67 /// assert_eq!(*(ptr as *mut u16), 42);
69 /// dealloc(ptr, layout);
72 #[stable(feature = "global_alloc", since = "1.28.0")]
74 pub unsafe fn alloc(layout: Layout) -> *mut u8 {
75 unsafe { __rust_alloc(layout.size(), layout.align()) }
78 /// Deallocate memory with the global allocator.
80 /// This function forwards calls to the [`GlobalAlloc::dealloc`] method
81 /// of the allocator registered with the `#[global_allocator]` attribute
82 /// if there is one, or the `std` crate’s default.
84 /// This function is expected to be deprecated in favor of the `dealloc` method
85 /// of the [`Global`] type when it and the [`AllocRef`] trait become stable.
89 /// See [`GlobalAlloc::dealloc`].
90 #[stable(feature = "global_alloc", since = "1.28.0")]
92 pub unsafe fn dealloc(ptr: *mut u8, layout: Layout) {
93 unsafe { __rust_dealloc(ptr, layout.size(), layout.align()) }
96 /// Reallocate memory with the global allocator.
98 /// This function forwards calls to the [`GlobalAlloc::realloc`] method
99 /// of the allocator registered with the `#[global_allocator]` attribute
100 /// if there is one, or the `std` crate’s default.
102 /// This function is expected to be deprecated in favor of the `realloc` method
103 /// of the [`Global`] type when it and the [`AllocRef`] trait become stable.
107 /// See [`GlobalAlloc::realloc`].
108 #[stable(feature = "global_alloc", since = "1.28.0")]
110 pub unsafe fn realloc(ptr: *mut u8, layout: Layout, new_size: usize) -> *mut u8 {
111 unsafe { __rust_realloc(ptr, layout.size(), layout.align(), new_size) }
114 /// Allocate zero-initialized memory with the global allocator.
116 /// This function forwards calls to the [`GlobalAlloc::alloc_zeroed`] method
117 /// of the allocator registered with the `#[global_allocator]` attribute
118 /// if there is one, or the `std` crate’s default.
120 /// This function is expected to be deprecated in favor of the `alloc_zeroed` method
121 /// of the [`Global`] type when it and the [`AllocRef`] trait become stable.
125 /// See [`GlobalAlloc::alloc_zeroed`].
130 /// use std::alloc::{alloc_zeroed, dealloc, Layout};
133 /// let layout = Layout::new::<u16>();
134 /// let ptr = alloc_zeroed(layout);
136 /// assert_eq!(*(ptr as *mut u16), 0);
138 /// dealloc(ptr, layout);
141 #[stable(feature = "global_alloc", since = "1.28.0")]
143 pub unsafe fn alloc_zeroed(layout: Layout) -> *mut u8 {
144 unsafe { __rust_alloc_zeroed(layout.size(), layout.align()) }
149 fn alloc_impl(&self, layout: Layout, zeroed: bool) -> Result<NonNull<[u8]>, AllocError> {
150 match layout.size() {
151 0 => Ok(NonNull::slice_from_raw_parts(layout.dangling(), 0)),
152 // SAFETY: `layout` is non-zero in size,
154 let raw_ptr = if zeroed { alloc_zeroed(layout) } else { alloc(layout) };
155 let ptr = NonNull::new(raw_ptr).ok_or(AllocError)?;
156 Ok(NonNull::slice_from_raw_parts(ptr, size))
161 // SAFETY: Same as `AllocRef::grow`
169 ) -> Result<NonNull<[u8]>, AllocError> {
171 new_layout.size() >= old_layout.size(),
172 "`new_layout.size()` must be greater than or equal to `old_layout.size()`"
175 match old_layout.size() {
176 0 => self.alloc_impl(new_layout, zeroed),
178 // SAFETY: `new_size` is non-zero as `old_size` is greater than or equal to `new_size`
179 // as required by safety conditions. Other conditions must be upheld by the caller
180 old_size if old_layout.align() == new_layout.align() => unsafe {
181 let new_size = new_layout.size();
183 // `realloc` probably checks for `new_size >= old_layout.size()` or something similar.
184 intrinsics::assume(new_size >= old_layout.size());
186 let raw_ptr = realloc(ptr.as_ptr(), old_layout, new_size);
187 let ptr = NonNull::new(raw_ptr).ok_or(AllocError)?;
189 raw_ptr.add(old_size).write_bytes(0, new_size - old_size);
191 Ok(NonNull::slice_from_raw_parts(ptr, new_size))
194 // SAFETY: because `new_layout.size()` must be greater than or equal to `old_size`,
195 // both the old and new memory allocation are valid for reads and writes for `old_size`
196 // bytes. Also, because the old allocation wasn't yet deallocated, it cannot overlap
197 // `new_ptr`. Thus, the call to `copy_nonoverlapping` is safe. The safety contract
198 // for `dealloc` must be upheld by the caller.
200 let new_ptr = self.alloc_impl(new_layout, zeroed)?;
201 ptr::copy_nonoverlapping(ptr.as_ptr(), new_ptr.as_mut_ptr(), old_size);
202 self.dealloc(ptr, old_layout);
209 #[unstable(feature = "allocator_api", issue = "32838")]
210 unsafe impl AllocRef for Global {
212 fn alloc(&self, layout: Layout) -> Result<NonNull<[u8]>, AllocError> {
213 self.alloc_impl(layout, false)
217 fn alloc_zeroed(&self, layout: Layout) -> Result<NonNull<[u8]>, AllocError> {
218 self.alloc_impl(layout, true)
222 unsafe fn dealloc(&self, ptr: NonNull<u8>, layout: Layout) {
223 if layout.size() != 0 {
224 // SAFETY: `layout` is non-zero in size,
225 // other conditions must be upheld by the caller
226 unsafe { dealloc(ptr.as_ptr(), layout) }
236 ) -> Result<NonNull<[u8]>, AllocError> {
237 // SAFETY: all conditions must be upheld by the caller
238 unsafe { self.grow_impl(ptr, old_layout, new_layout, false) }
242 unsafe fn grow_zeroed(
247 ) -> Result<NonNull<[u8]>, AllocError> {
248 // SAFETY: all conditions must be upheld by the caller
249 unsafe { self.grow_impl(ptr, old_layout, new_layout, true) }
258 ) -> Result<NonNull<[u8]>, AllocError> {
260 new_layout.size() <= old_layout.size(),
261 "`new_layout.size()` must be smaller than or equal to `old_layout.size()`"
264 match new_layout.size() {
265 // SAFETY: conditions must be upheld by the caller
267 self.dealloc(ptr, old_layout);
268 Ok(NonNull::slice_from_raw_parts(new_layout.dangling(), 0))
271 // SAFETY: `new_size` is non-zero. Other conditions must be upheld by the caller
272 new_size if old_layout.align() == new_layout.align() => unsafe {
273 // `realloc` probably checks for `new_size <= old_layout.size()` or something similar.
274 intrinsics::assume(new_size <= old_layout.size());
276 let raw_ptr = realloc(ptr.as_ptr(), old_layout, new_size);
277 let ptr = NonNull::new(raw_ptr).ok_or(AllocError)?;
278 Ok(NonNull::slice_from_raw_parts(ptr, new_size))
281 // SAFETY: because `new_size` must be smaller than or equal to `old_layout.size()`,
282 // both the old and new memory allocation are valid for reads and writes for `new_size`
283 // bytes. Also, because the old allocation wasn't yet deallocated, it cannot overlap
284 // `new_ptr`. Thus, the call to `copy_nonoverlapping` is safe. The safety contract
285 // for `dealloc` must be upheld by the caller.
287 let new_ptr = self.alloc(new_layout)?;
288 ptr::copy_nonoverlapping(ptr.as_ptr(), new_ptr.as_mut_ptr(), new_size);
289 self.dealloc(ptr, old_layout);
296 /// The allocator for unique pointers.
297 // This function must not unwind. If it does, MIR codegen will fail.
299 #[lang = "exchange_malloc"]
301 unsafe fn exchange_malloc(size: usize, align: usize) -> *mut u8 {
302 let layout = unsafe { Layout::from_size_align_unchecked(size, align) };
303 match Global.alloc(layout) {
304 Ok(ptr) => ptr.as_mut_ptr(),
305 Err(_) => handle_alloc_error(layout),
309 #[cfg_attr(not(test), lang = "box_free")]
311 // This signature has to be the same as `Box`, otherwise an ICE will happen.
312 // When an additional parameter to `Box` is added (like `A: AllocRef`), this has to be added here as
314 // For example if `Box` is changed to `struct Box<T: ?Sized, A: AllocRef>(Unique<T>, A)`,
315 // this function has to be changed to `fn box_free<T: ?Sized, A: AllocRef>(Unique<T>, A)` as well.
316 pub(crate) unsafe fn box_free<T: ?Sized>(ptr: Unique<T>) {
318 let size = size_of_val(ptr.as_ref());
319 let align = min_align_of_val(ptr.as_ref());
320 let layout = Layout::from_size_align_unchecked(size, align);
321 Global.dealloc(ptr.cast().into(), layout)
325 // # Allocation error handler
328 // This is the magic symbol to call the global alloc error handler. rustc generates
329 // it to call `__rg_oom` if there is a `#[alloc_error_handler]`, or to call the
330 // default implementations below (`__rdl_oom`) otherwise.
331 #[rustc_allocator_nounwind]
332 fn __rust_alloc_error_handler(size: usize, align: usize) -> !;
335 /// Abort on memory allocation error or failure.
337 /// Callers of memory allocation APIs wishing to abort computation
338 /// in response to an allocation error are encouraged to call this function,
339 /// rather than directly invoking `panic!` or similar.
341 /// The default behavior of this function is to print a message to standard error
342 /// and abort the process.
343 /// It can be replaced with [`set_alloc_error_hook`] and [`take_alloc_error_hook`].
345 /// [`set_alloc_error_hook`]: ../../std/alloc/fn.set_alloc_error_hook.html
346 /// [`take_alloc_error_hook`]: ../../std/alloc/fn.take_alloc_error_hook.html
347 #[stable(feature = "global_alloc", since = "1.28.0")]
348 #[cfg(not(any(test, bootstrap)))]
349 #[rustc_allocator_nounwind]
350 pub fn handle_alloc_error(layout: Layout) -> ! {
352 __rust_alloc_error_handler(layout.size(), layout.align());
356 // For alloc test `std::alloc::handle_alloc_error` can be used directly.
358 pub use std::alloc::handle_alloc_error;
360 // In stage0 (bootstrap) `__rust_alloc_error_handler`,
361 // might not be generated yet, because an old compiler is used,
362 // so use the old direct call.
363 #[cfg(all(bootstrap, not(test)))]
364 #[stable(feature = "global_alloc", since = "1.28.0")]
366 #[rustc_allocator_nounwind]
367 pub fn handle_alloc_error(layout: Layout) -> ! {
370 fn oom_impl(layout: Layout) -> !;
372 unsafe { oom_impl(layout) }
375 #[cfg(not(any(target_os = "hermit", test, bootstrap)))]
377 #[allow(unused_attributes)]
378 #[unstable(feature = "alloc_internals", issue = "none")]
379 pub mod __alloc_error_handler {
380 use crate::alloc::Layout;
382 // called via generated `__rust_alloc_error_handler`
384 // if there is no `#[alloc_error_handler]`
385 #[rustc_std_internal_symbol]
386 pub unsafe extern "C" fn __rdl_oom(size: usize, _align: usize) -> ! {
387 panic!("memory allocation of {} bytes failed", size)
390 // if there is a `#[alloc_error_handler]`
391 #[rustc_std_internal_symbol]
392 pub unsafe extern "C" fn __rg_oom(size: usize, align: usize) -> ! {
393 let layout = unsafe { Layout::from_size_align_unchecked(size, align) };
396 fn oom_impl(layout: Layout) -> !;
398 unsafe { oom_impl(layout) }