alloc/
alloc.rs

1//! Memory allocation APIs
2
3#![stable(feature = "alloc_module", since = "1.28.0")]
4
5#[stable(feature = "alloc_module", since = "1.28.0")]
6#[doc(inline)]
7pub use core::alloc::*;
8#[cfg(not(test))]
9use core::hint;
10#[cfg(not(test))]
11use core::ptr::{self, NonNull};
12
13unsafe extern "Rust" {
14    // These are the magic symbols to call the global allocator. rustc generates
15    // them to call `__rg_alloc` etc. if there is a `#[global_allocator]` attribute
16    // (the code expanding that attribute macro generates those functions), or to call
17    // the default implementations in std (`__rdl_alloc` etc. in `library/std/src/alloc.rs`)
18    // otherwise.
19    // The rustc fork of LLVM 14 and earlier also special-cases these function names to be able to optimize them
20    // like `malloc`, `realloc`, and `free`, respectively.
21    #[rustc_allocator]
22    #[rustc_nounwind]
23    fn __rust_alloc(size: usize, align: usize) -> *mut u8;
24    #[rustc_deallocator]
25    #[rustc_nounwind]
26    fn __rust_dealloc(ptr: *mut u8, size: usize, align: usize);
27    #[rustc_reallocator]
28    #[rustc_nounwind]
29    fn __rust_realloc(ptr: *mut u8, old_size: usize, align: usize, new_size: usize) -> *mut u8;
30    #[rustc_allocator_zeroed]
31    #[rustc_nounwind]
32    fn __rust_alloc_zeroed(size: usize, align: usize) -> *mut u8;
33
34    static __rust_no_alloc_shim_is_unstable: u8;
35}
36
37/// The global memory allocator.
38///
39/// This type implements the [`Allocator`] trait by forwarding calls
40/// to the allocator registered with the `#[global_allocator]` attribute
41/// if there is one, or the `std` crate’s default.
42///
43/// Note: while this type is unstable, the functionality it provides can be
44/// accessed through the [free functions in `alloc`](self#functions).
45#[unstable(feature = "allocator_api", issue = "32838")]
46#[derive(Copy, Clone, Default, Debug)]
47#[cfg(not(test))]
48// the compiler needs to know when a Box uses the global allocator vs a custom one
49#[lang = "global_alloc_ty"]
50pub struct Global;
51
52#[cfg(test)]
53pub use std::alloc::Global;
54
55/// Allocates memory with the global allocator.
56///
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.
60///
61/// This function is expected to be deprecated in favor of the `allocate` method
62/// of the [`Global`] type when it and the [`Allocator`] trait become stable.
63///
64/// # Safety
65///
66/// See [`GlobalAlloc::alloc`].
67///
68/// # Examples
69///
70/// ```
71/// use std::alloc::{alloc, dealloc, handle_alloc_error, Layout};
72///
73/// unsafe {
74///     let layout = Layout::new::<u16>();
75///     let ptr = alloc(layout);
76///     if ptr.is_null() {
77///         handle_alloc_error(layout);
78///     }
79///
80///     *(ptr as *mut u16) = 42;
81///     assert_eq!(*(ptr as *mut u16), 42);
82///
83///     dealloc(ptr, layout);
84/// }
85/// ```
86#[stable(feature = "global_alloc", since = "1.28.0")]
87#[must_use = "losing the pointer will leak memory"]
88#[inline]
89#[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces
90pub unsafe fn alloc(layout: Layout) -> *mut u8 {
91    unsafe {
92        // Make sure we don't accidentally allow omitting the allocator shim in
93        // stable code until it is actually stabilized.
94        core::ptr::read_volatile(&__rust_no_alloc_shim_is_unstable);
95
96        __rust_alloc(layout.size(), layout.align())
97    }
98}
99
100/// Deallocates memory with the global allocator.
101///
102/// This function forwards calls to the [`GlobalAlloc::dealloc`] method
103/// of the allocator registered with the `#[global_allocator]` attribute
104/// if there is one, or the `std` crate’s default.
105///
106/// This function is expected to be deprecated in favor of the `deallocate` method
107/// of the [`Global`] type when it and the [`Allocator`] trait become stable.
108///
109/// # Safety
110///
111/// See [`GlobalAlloc::dealloc`].
112#[stable(feature = "global_alloc", since = "1.28.0")]
113#[inline]
114#[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces
115pub unsafe fn dealloc(ptr: *mut u8, layout: Layout) {
116    unsafe { __rust_dealloc(ptr, layout.size(), layout.align()) }
117}
118
119/// Reallocates memory with the global allocator.
120///
121/// This function forwards calls to the [`GlobalAlloc::realloc`] method
122/// of the allocator registered with the `#[global_allocator]` attribute
123/// if there is one, or the `std` crate’s default.
124///
125/// This function is expected to be deprecated in favor of the `grow` and `shrink` methods
126/// of the [`Global`] type when it and the [`Allocator`] trait become stable.
127///
128/// # Safety
129///
130/// See [`GlobalAlloc::realloc`].
131#[stable(feature = "global_alloc", since = "1.28.0")]
132#[must_use = "losing the pointer will leak memory"]
133#[inline]
134#[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces
135pub unsafe fn realloc(ptr: *mut u8, layout: Layout, new_size: usize) -> *mut u8 {
136    unsafe { __rust_realloc(ptr, layout.size(), layout.align(), new_size) }
137}
138
139/// Allocates zero-initialized memory with the global allocator.
140///
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.
144///
145/// This function is expected to be deprecated in favor of the `allocate_zeroed` method
146/// of the [`Global`] type when it and the [`Allocator`] trait become stable.
147///
148/// # Safety
149///
150/// See [`GlobalAlloc::alloc_zeroed`].
151///
152/// # Examples
153///
154/// ```
155/// use std::alloc::{alloc_zeroed, dealloc, handle_alloc_error, Layout};
156///
157/// unsafe {
158///     let layout = Layout::new::<u16>();
159///     let ptr = alloc_zeroed(layout);
160///     if ptr.is_null() {
161///         handle_alloc_error(layout);
162///     }
163///
164///     assert_eq!(*(ptr as *mut u16), 0);
165///
166///     dealloc(ptr, layout);
167/// }
168/// ```
169#[stable(feature = "global_alloc", since = "1.28.0")]
170#[must_use = "losing the pointer will leak memory"]
171#[inline]
172#[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces
173pub unsafe fn alloc_zeroed(layout: Layout) -> *mut u8 {
174    unsafe {
175        // Make sure we don't accidentally allow omitting the allocator shim in
176        // stable code until it is actually stabilized.
177        core::ptr::read_volatile(&__rust_no_alloc_shim_is_unstable);
178
179        __rust_alloc_zeroed(layout.size(), layout.align())
180    }
181}
182
183#[cfg(not(test))]
184impl Global {
185    #[inline]
186    #[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces
187    fn alloc_impl(&self, layout: Layout, zeroed: bool) -> Result<NonNull<[u8]>, AllocError> {
188        match layout.size() {
189            0 => Ok(NonNull::slice_from_raw_parts(layout.dangling(), 0)),
190            // SAFETY: `layout` is non-zero in size,
191            size => unsafe {
192                let raw_ptr = if zeroed { alloc_zeroed(layout) } else { alloc(layout) };
193                let ptr = NonNull::new(raw_ptr).ok_or(AllocError)?;
194                Ok(NonNull::slice_from_raw_parts(ptr, size))
195            },
196        }
197    }
198
199    // SAFETY: Same as `Allocator::grow`
200    #[inline]
201    #[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces
202    unsafe fn grow_impl(
203        &self,
204        ptr: NonNull<u8>,
205        old_layout: Layout,
206        new_layout: Layout,
207        zeroed: bool,
208    ) -> Result<NonNull<[u8]>, AllocError> {
209        debug_assert!(
210            new_layout.size() >= old_layout.size(),
211            "`new_layout.size()` must be greater than or equal to `old_layout.size()`"
212        );
213
214        match old_layout.size() {
215            0 => self.alloc_impl(new_layout, zeroed),
216
217            // SAFETY: `new_size` is non-zero as `old_size` is greater than or equal to `new_size`
218            // as required by safety conditions. Other conditions must be upheld by the caller
219            old_size if old_layout.align() == new_layout.align() => unsafe {
220                let new_size = new_layout.size();
221
222                // `realloc` probably checks for `new_size >= old_layout.size()` or something similar.
223                hint::assert_unchecked(new_size >= old_layout.size());
224
225                let raw_ptr = realloc(ptr.as_ptr(), old_layout, new_size);
226                let ptr = NonNull::new(raw_ptr).ok_or(AllocError)?;
227                if zeroed {
228                    raw_ptr.add(old_size).write_bytes(0, new_size - old_size);
229                }
230                Ok(NonNull::slice_from_raw_parts(ptr, new_size))
231            },
232
233            // SAFETY: because `new_layout.size()` must be greater than or equal to `old_size`,
234            // both the old and new memory allocation are valid for reads and writes for `old_size`
235            // bytes. Also, because the old allocation wasn't yet deallocated, it cannot overlap
236            // `new_ptr`. Thus, the call to `copy_nonoverlapping` is safe. The safety contract
237            // for `dealloc` must be upheld by the caller.
238            old_size => unsafe {
239                let new_ptr = self.alloc_impl(new_layout, zeroed)?;
240                ptr::copy_nonoverlapping(ptr.as_ptr(), new_ptr.as_mut_ptr(), old_size);
241                self.deallocate(ptr, old_layout);
242                Ok(new_ptr)
243            },
244        }
245    }
246}
247
248#[unstable(feature = "allocator_api", issue = "32838")]
249#[cfg(not(test))]
250unsafe impl Allocator for Global {
251    #[inline]
252    #[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces
253    fn allocate(&self, layout: Layout) -> Result<NonNull<[u8]>, AllocError> {
254        self.alloc_impl(layout, false)
255    }
256
257    #[inline]
258    #[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces
259    fn allocate_zeroed(&self, layout: Layout) -> Result<NonNull<[u8]>, AllocError> {
260        self.alloc_impl(layout, true)
261    }
262
263    #[inline]
264    #[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces
265    unsafe fn deallocate(&self, ptr: NonNull<u8>, layout: Layout) {
266        if layout.size() != 0 {
267            // SAFETY: `layout` is non-zero in size,
268            // other conditions must be upheld by the caller
269            unsafe { dealloc(ptr.as_ptr(), layout) }
270        }
271    }
272
273    #[inline]
274    #[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces
275    unsafe fn grow(
276        &self,
277        ptr: NonNull<u8>,
278        old_layout: Layout,
279        new_layout: Layout,
280    ) -> Result<NonNull<[u8]>, AllocError> {
281        // SAFETY: all conditions must be upheld by the caller
282        unsafe { self.grow_impl(ptr, old_layout, new_layout, false) }
283    }
284
285    #[inline]
286    #[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces
287    unsafe fn grow_zeroed(
288        &self,
289        ptr: NonNull<u8>,
290        old_layout: Layout,
291        new_layout: Layout,
292    ) -> Result<NonNull<[u8]>, AllocError> {
293        // SAFETY: all conditions must be upheld by the caller
294        unsafe { self.grow_impl(ptr, old_layout, new_layout, true) }
295    }
296
297    #[inline]
298    #[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces
299    unsafe fn shrink(
300        &self,
301        ptr: NonNull<u8>,
302        old_layout: Layout,
303        new_layout: Layout,
304    ) -> Result<NonNull<[u8]>, AllocError> {
305        debug_assert!(
306            new_layout.size() <= old_layout.size(),
307            "`new_layout.size()` must be smaller than or equal to `old_layout.size()`"
308        );
309
310        match new_layout.size() {
311            // SAFETY: conditions must be upheld by the caller
312            0 => unsafe {
313                self.deallocate(ptr, old_layout);
314                Ok(NonNull::slice_from_raw_parts(new_layout.dangling(), 0))
315            },
316
317            // SAFETY: `new_size` is non-zero. Other conditions must be upheld by the caller
318            new_size if old_layout.align() == new_layout.align() => unsafe {
319                // `realloc` probably checks for `new_size <= old_layout.size()` or something similar.
320                hint::assert_unchecked(new_size <= old_layout.size());
321
322                let raw_ptr = realloc(ptr.as_ptr(), old_layout, new_size);
323                let ptr = NonNull::new(raw_ptr).ok_or(AllocError)?;
324                Ok(NonNull::slice_from_raw_parts(ptr, new_size))
325            },
326
327            // SAFETY: because `new_size` must be smaller than or equal to `old_layout.size()`,
328            // both the old and new memory allocation are valid for reads and writes for `new_size`
329            // bytes. Also, because the old allocation wasn't yet deallocated, it cannot overlap
330            // `new_ptr`. Thus, the call to `copy_nonoverlapping` is safe. The safety contract
331            // for `dealloc` must be upheld by the caller.
332            new_size => unsafe {
333                let new_ptr = self.allocate(new_layout)?;
334                ptr::copy_nonoverlapping(ptr.as_ptr(), new_ptr.as_mut_ptr(), new_size);
335                self.deallocate(ptr, old_layout);
336                Ok(new_ptr)
337            },
338        }
339    }
340}
341
342/// The allocator for `Box`.
343#[cfg(all(not(no_global_oom_handling), not(test)))]
344#[lang = "exchange_malloc"]
345#[inline]
346#[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces
347unsafe fn exchange_malloc(size: usize, align: usize) -> *mut u8 {
348    let layout = unsafe { Layout::from_size_align_unchecked(size, align) };
349    match Global.allocate(layout) {
350        Ok(ptr) => ptr.as_mut_ptr(),
351        Err(_) => handle_alloc_error(layout),
352    }
353}
354
355// # Allocation error handler
356
357#[cfg(not(no_global_oom_handling))]
358unsafe extern "Rust" {
359    // This is the magic symbol to call the global alloc error handler. rustc generates
360    // it to call `__rg_oom` if there is a `#[alloc_error_handler]`, or to call the
361    // default implementations below (`__rdl_oom`) otherwise.
362    fn __rust_alloc_error_handler(size: usize, align: usize) -> !;
363}
364
365/// Signals a memory allocation error.
366///
367/// Callers of memory allocation APIs wishing to cease execution
368/// in response to an allocation error are encouraged to call this function,
369/// rather than directly invoking [`panic!`] or similar.
370///
371/// This function is guaranteed to diverge (not return normally with a value), but depending on
372/// global configuration, it may either panic (resulting in unwinding or aborting as per
373/// configuration for all panics), or abort the process (with no unwinding).
374///
375/// The default behavior is:
376///
377///  * If the binary links against `std` (typically the case), then
378///   print a message to standard error and abort the process.
379///   This behavior can be replaced with [`set_alloc_error_hook`] and [`take_alloc_error_hook`].
380///   Future versions of Rust may panic by default instead.
381///
382/// * If the binary does not link against `std` (all of its crates are marked
383///   [`#![no_std]`][no_std]), then call [`panic!`] with a message.
384///   [The panic handler] applies as to any panic.
385///
386/// [`set_alloc_error_hook`]: ../../std/alloc/fn.set_alloc_error_hook.html
387/// [`take_alloc_error_hook`]: ../../std/alloc/fn.take_alloc_error_hook.html
388/// [The panic handler]: https://doc.rust-lang.org/reference/runtime.html#the-panic_handler-attribute
389/// [no_std]: https://doc.rust-lang.org/reference/names/preludes.html#the-no_std-attribute
390#[stable(feature = "global_alloc", since = "1.28.0")]
391#[rustc_const_unstable(feature = "const_alloc_error", issue = "92523")]
392#[cfg(all(not(no_global_oom_handling), not(test)))]
393#[cold]
394#[optimize(size)]
395pub const fn handle_alloc_error(layout: Layout) -> ! {
396    const fn ct_error(_: Layout) -> ! {
397        panic!("allocation failed");
398    }
399
400    #[inline]
401    fn rt_error(layout: Layout) -> ! {
402        unsafe {
403            __rust_alloc_error_handler(layout.size(), layout.align());
404        }
405    }
406
407    #[cfg(not(feature = "panic_immediate_abort"))]
408    {
409        core::intrinsics::const_eval_select((layout,), ct_error, rt_error)
410    }
411
412    #[cfg(feature = "panic_immediate_abort")]
413    ct_error(layout)
414}
415
416// For alloc test `std::alloc::handle_alloc_error` can be used directly.
417#[cfg(all(not(no_global_oom_handling), test))]
418pub use std::alloc::handle_alloc_error;
419
420#[cfg(all(not(no_global_oom_handling), not(test)))]
421#[doc(hidden)]
422#[allow(unused_attributes)]
423#[unstable(feature = "alloc_internals", issue = "none")]
424pub mod __alloc_error_handler {
425    // called via generated `__rust_alloc_error_handler` if there is no
426    // `#[alloc_error_handler]`.
427    #[rustc_std_internal_symbol]
428    pub unsafe fn __rdl_oom(size: usize, _align: usize) -> ! {
429        unsafe extern "Rust" {
430            // This symbol is emitted by rustc next to __rust_alloc_error_handler.
431            // Its value depends on the -Zoom={panic,abort} compiler option.
432            static __rust_alloc_error_handler_should_panic: u8;
433        }
434
435        if unsafe { __rust_alloc_error_handler_should_panic != 0 } {
436            panic!("memory allocation of {size} bytes failed")
437        } else {
438            core::panicking::panic_nounwind_fmt(
439                format_args!("memory allocation of {size} bytes failed"),
440                /* force_no_backtrace */ false,
441            )
442        }
443    }
444}