xref: /openbmc/linux/rust/alloc/alloc.rs (revision 695c312ec5a68e4373d063ee649c7b925ffb5da7)
1057b8d25SMiguel Ojeda // SPDX-License-Identifier: Apache-2.0 OR MIT
2057b8d25SMiguel Ojeda 
3753dece8SMiguel Ojeda //! Memory allocation APIs
4753dece8SMiguel Ojeda 
5753dece8SMiguel Ojeda #![stable(feature = "alloc_module", since = "1.28.0")]
6753dece8SMiguel Ojeda 
7753dece8SMiguel Ojeda #[cfg(not(test))]
8753dece8SMiguel Ojeda use core::intrinsics;
9753dece8SMiguel Ojeda 
10753dece8SMiguel Ojeda #[cfg(not(test))]
11753dece8SMiguel Ojeda use core::ptr::{self, NonNull};
12753dece8SMiguel Ojeda 
13753dece8SMiguel Ojeda #[stable(feature = "alloc_module", since = "1.28.0")]
14753dece8SMiguel Ojeda #[doc(inline)]
15753dece8SMiguel Ojeda pub use core::alloc::*;
16753dece8SMiguel Ojeda 
17753dece8SMiguel Ojeda #[cfg(test)]
18753dece8SMiguel Ojeda mod tests;
19753dece8SMiguel Ojeda 
20753dece8SMiguel Ojeda extern "Rust" {
21753dece8SMiguel Ojeda     // These are the magic symbols to call the global allocator. rustc generates
22753dece8SMiguel Ojeda     // them to call `__rg_alloc` etc. if there is a `#[global_allocator]` attribute
23753dece8SMiguel Ojeda     // (the code expanding that attribute macro generates those functions), or to call
243ed03f4dSMiguel Ojeda     // the default implementations in std (`__rdl_alloc` etc. in `library/std/src/alloc.rs`)
25753dece8SMiguel Ojeda     // otherwise.
263ed03f4dSMiguel Ojeda     // The rustc fork of LLVM 14 and earlier also special-cases these function names to be able to optimize them
27753dece8SMiguel Ojeda     // like `malloc`, `realloc`, and `free`, respectively.
28753dece8SMiguel Ojeda     #[rustc_allocator]
293ed03f4dSMiguel Ojeda     #[rustc_nounwind]
__rust_alloc(size: usize, align: usize) -> *mut u830753dece8SMiguel Ojeda     fn __rust_alloc(size: usize, align: usize) -> *mut u8;
313ed03f4dSMiguel Ojeda     #[rustc_deallocator]
323ed03f4dSMiguel Ojeda     #[rustc_nounwind]
__rust_dealloc(ptr: *mut u8, size: usize, align: usize)33753dece8SMiguel Ojeda     fn __rust_dealloc(ptr: *mut u8, size: usize, align: usize);
343ed03f4dSMiguel Ojeda     #[rustc_reallocator]
353ed03f4dSMiguel Ojeda     #[rustc_nounwind]
__rust_realloc(ptr: *mut u8, old_size: usize, align: usize, new_size: usize) -> *mut u836753dece8SMiguel Ojeda     fn __rust_realloc(ptr: *mut u8, old_size: usize, align: usize, new_size: usize) -> *mut u8;
373ed03f4dSMiguel Ojeda     #[rustc_allocator_zeroed]
383ed03f4dSMiguel Ojeda     #[rustc_nounwind]
__rust_alloc_zeroed(size: usize, align: usize) -> *mut u839753dece8SMiguel Ojeda     fn __rust_alloc_zeroed(size: usize, align: usize) -> *mut u8;
40*89eed1abSMiguel Ojeda 
41*89eed1abSMiguel Ojeda     static __rust_no_alloc_shim_is_unstable: u8;
42753dece8SMiguel Ojeda }
43753dece8SMiguel Ojeda 
44753dece8SMiguel Ojeda /// The global memory allocator.
45753dece8SMiguel Ojeda ///
46753dece8SMiguel Ojeda /// This type implements the [`Allocator`] trait by forwarding calls
47753dece8SMiguel Ojeda /// to the allocator registered with the `#[global_allocator]` attribute
48753dece8SMiguel Ojeda /// if there is one, or the `std` crate’s default.
49753dece8SMiguel Ojeda ///
50753dece8SMiguel Ojeda /// Note: while this type is unstable, the functionality it provides can be
51753dece8SMiguel Ojeda /// accessed through the [free functions in `alloc`](self#functions).
52753dece8SMiguel Ojeda #[unstable(feature = "allocator_api", issue = "32838")]
53753dece8SMiguel Ojeda #[derive(Copy, Clone, Default, Debug)]
54753dece8SMiguel Ojeda #[cfg(not(test))]
55753dece8SMiguel Ojeda pub struct Global;
56753dece8SMiguel Ojeda 
57753dece8SMiguel Ojeda #[cfg(test)]
58753dece8SMiguel Ojeda pub use std::alloc::Global;
59753dece8SMiguel Ojeda 
60753dece8SMiguel Ojeda /// Allocate memory with the global allocator.
61753dece8SMiguel Ojeda ///
62753dece8SMiguel Ojeda /// This function forwards calls to the [`GlobalAlloc::alloc`] method
63753dece8SMiguel Ojeda /// of the allocator registered with the `#[global_allocator]` attribute
64753dece8SMiguel Ojeda /// if there is one, or the `std` crate’s default.
65753dece8SMiguel Ojeda ///
66753dece8SMiguel Ojeda /// This function is expected to be deprecated in favor of the `alloc` method
67753dece8SMiguel Ojeda /// of the [`Global`] type when it and the [`Allocator`] trait become stable.
68753dece8SMiguel Ojeda ///
69753dece8SMiguel Ojeda /// # Safety
70753dece8SMiguel Ojeda ///
71753dece8SMiguel Ojeda /// See [`GlobalAlloc::alloc`].
72753dece8SMiguel Ojeda ///
73753dece8SMiguel Ojeda /// # Examples
74753dece8SMiguel Ojeda ///
75753dece8SMiguel Ojeda /// ```
763ed03f4dSMiguel Ojeda /// use std::alloc::{alloc, dealloc, handle_alloc_error, Layout};
77753dece8SMiguel Ojeda ///
78753dece8SMiguel Ojeda /// unsafe {
79753dece8SMiguel Ojeda ///     let layout = Layout::new::<u16>();
80753dece8SMiguel Ojeda ///     let ptr = alloc(layout);
813ed03f4dSMiguel Ojeda ///     if ptr.is_null() {
823ed03f4dSMiguel Ojeda ///         handle_alloc_error(layout);
833ed03f4dSMiguel Ojeda ///     }
84753dece8SMiguel Ojeda ///
85753dece8SMiguel Ojeda ///     *(ptr as *mut u16) = 42;
86753dece8SMiguel Ojeda ///     assert_eq!(*(ptr as *mut u16), 42);
87753dece8SMiguel Ojeda ///
88753dece8SMiguel Ojeda ///     dealloc(ptr, layout);
89753dece8SMiguel Ojeda /// }
90753dece8SMiguel Ojeda /// ```
91753dece8SMiguel Ojeda #[stable(feature = "global_alloc", since = "1.28.0")]
92753dece8SMiguel Ojeda #[must_use = "losing the pointer will leak memory"]
93753dece8SMiguel Ojeda #[inline]
alloc(layout: Layout) -> *mut u894753dece8SMiguel Ojeda pub unsafe fn alloc(layout: Layout) -> *mut u8 {
95*89eed1abSMiguel Ojeda     unsafe {
96*89eed1abSMiguel Ojeda         // Make sure we don't accidentally allow omitting the allocator shim in
97*89eed1abSMiguel Ojeda         // stable code until it is actually stabilized.
98*89eed1abSMiguel Ojeda         core::ptr::read_volatile(&__rust_no_alloc_shim_is_unstable);
99*89eed1abSMiguel Ojeda 
100*89eed1abSMiguel Ojeda         __rust_alloc(layout.size(), layout.align())
101*89eed1abSMiguel Ojeda     }
102753dece8SMiguel Ojeda }
103753dece8SMiguel Ojeda 
104753dece8SMiguel Ojeda /// Deallocate memory with the global allocator.
105753dece8SMiguel Ojeda ///
106753dece8SMiguel Ojeda /// This function forwards calls to the [`GlobalAlloc::dealloc`] method
107753dece8SMiguel Ojeda /// of the allocator registered with the `#[global_allocator]` attribute
108753dece8SMiguel Ojeda /// if there is one, or the `std` crate’s default.
109753dece8SMiguel Ojeda ///
110753dece8SMiguel Ojeda /// This function is expected to be deprecated in favor of the `dealloc` method
111753dece8SMiguel Ojeda /// of the [`Global`] type when it and the [`Allocator`] trait become stable.
112753dece8SMiguel Ojeda ///
113753dece8SMiguel Ojeda /// # Safety
114753dece8SMiguel Ojeda ///
115753dece8SMiguel Ojeda /// See [`GlobalAlloc::dealloc`].
116753dece8SMiguel Ojeda #[stable(feature = "global_alloc", since = "1.28.0")]
117753dece8SMiguel Ojeda #[inline]
dealloc(ptr: *mut u8, layout: Layout)118753dece8SMiguel Ojeda pub unsafe fn dealloc(ptr: *mut u8, layout: Layout) {
119753dece8SMiguel Ojeda     unsafe { __rust_dealloc(ptr, layout.size(), layout.align()) }
120753dece8SMiguel Ojeda }
121753dece8SMiguel Ojeda 
122753dece8SMiguel Ojeda /// Reallocate memory with the global allocator.
123753dece8SMiguel Ojeda ///
124753dece8SMiguel Ojeda /// This function forwards calls to the [`GlobalAlloc::realloc`] method
125753dece8SMiguel Ojeda /// of the allocator registered with the `#[global_allocator]` attribute
126753dece8SMiguel Ojeda /// if there is one, or the `std` crate’s default.
127753dece8SMiguel Ojeda ///
128753dece8SMiguel Ojeda /// This function is expected to be deprecated in favor of the `realloc` method
129753dece8SMiguel Ojeda /// of the [`Global`] type when it and the [`Allocator`] trait become stable.
130753dece8SMiguel Ojeda ///
131753dece8SMiguel Ojeda /// # Safety
132753dece8SMiguel Ojeda ///
133753dece8SMiguel Ojeda /// See [`GlobalAlloc::realloc`].
134753dece8SMiguel Ojeda #[stable(feature = "global_alloc", since = "1.28.0")]
135753dece8SMiguel Ojeda #[must_use = "losing the pointer will leak memory"]
136753dece8SMiguel Ojeda #[inline]
realloc(ptr: *mut u8, layout: Layout, new_size: usize) -> *mut u8137753dece8SMiguel Ojeda pub unsafe fn realloc(ptr: *mut u8, layout: Layout, new_size: usize) -> *mut u8 {
138753dece8SMiguel Ojeda     unsafe { __rust_realloc(ptr, layout.size(), layout.align(), new_size) }
139753dece8SMiguel Ojeda }
140753dece8SMiguel Ojeda 
141753dece8SMiguel Ojeda /// Allocate zero-initialized memory with the global allocator.
142753dece8SMiguel Ojeda ///
143753dece8SMiguel Ojeda /// This function forwards calls to the [`GlobalAlloc::alloc_zeroed`] method
144753dece8SMiguel Ojeda /// of the allocator registered with the `#[global_allocator]` attribute
145753dece8SMiguel Ojeda /// if there is one, or the `std` crate’s default.
146753dece8SMiguel Ojeda ///
147753dece8SMiguel Ojeda /// This function is expected to be deprecated in favor of the `alloc_zeroed` method
148753dece8SMiguel Ojeda /// of the [`Global`] type when it and the [`Allocator`] trait become stable.
149753dece8SMiguel Ojeda ///
150753dece8SMiguel Ojeda /// # Safety
151753dece8SMiguel Ojeda ///
152753dece8SMiguel Ojeda /// See [`GlobalAlloc::alloc_zeroed`].
153753dece8SMiguel Ojeda ///
154753dece8SMiguel Ojeda /// # Examples
155753dece8SMiguel Ojeda ///
156753dece8SMiguel Ojeda /// ```
157753dece8SMiguel Ojeda /// use std::alloc::{alloc_zeroed, dealloc, Layout};
158753dece8SMiguel Ojeda ///
159753dece8SMiguel Ojeda /// unsafe {
160753dece8SMiguel Ojeda ///     let layout = Layout::new::<u16>();
161753dece8SMiguel Ojeda ///     let ptr = alloc_zeroed(layout);
162753dece8SMiguel Ojeda ///
163753dece8SMiguel Ojeda ///     assert_eq!(*(ptr as *mut u16), 0);
164753dece8SMiguel Ojeda ///
165753dece8SMiguel Ojeda ///     dealloc(ptr, layout);
166753dece8SMiguel Ojeda /// }
167753dece8SMiguel Ojeda /// ```
168753dece8SMiguel Ojeda #[stable(feature = "global_alloc", since = "1.28.0")]
169753dece8SMiguel Ojeda #[must_use = "losing the pointer will leak memory"]
170753dece8SMiguel Ojeda #[inline]
alloc_zeroed(layout: Layout) -> *mut u8171753dece8SMiguel Ojeda pub unsafe fn alloc_zeroed(layout: Layout) -> *mut u8 {
172753dece8SMiguel Ojeda     unsafe { __rust_alloc_zeroed(layout.size(), layout.align()) }
173753dece8SMiguel Ojeda }
174753dece8SMiguel Ojeda 
175753dece8SMiguel Ojeda #[cfg(not(test))]
176753dece8SMiguel Ojeda impl Global {
177753dece8SMiguel Ojeda     #[inline]
alloc_impl(&self, layout: Layout, zeroed: bool) -> Result<NonNull<[u8]>, AllocError>178753dece8SMiguel Ojeda     fn alloc_impl(&self, layout: Layout, zeroed: bool) -> Result<NonNull<[u8]>, AllocError> {
179753dece8SMiguel Ojeda         match layout.size() {
180753dece8SMiguel Ojeda             0 => Ok(NonNull::slice_from_raw_parts(layout.dangling(), 0)),
181753dece8SMiguel Ojeda             // SAFETY: `layout` is non-zero in size,
182753dece8SMiguel Ojeda             size => unsafe {
183753dece8SMiguel Ojeda                 let raw_ptr = if zeroed { alloc_zeroed(layout) } else { alloc(layout) };
184753dece8SMiguel Ojeda                 let ptr = NonNull::new(raw_ptr).ok_or(AllocError)?;
185753dece8SMiguel Ojeda                 Ok(NonNull::slice_from_raw_parts(ptr, size))
186753dece8SMiguel Ojeda             },
187753dece8SMiguel Ojeda         }
188753dece8SMiguel Ojeda     }
189753dece8SMiguel Ojeda 
190753dece8SMiguel Ojeda     // SAFETY: Same as `Allocator::grow`
191753dece8SMiguel Ojeda     #[inline]
grow_impl( &self, ptr: NonNull<u8>, old_layout: Layout, new_layout: Layout, zeroed: bool, ) -> Result<NonNull<[u8]>, AllocError>192753dece8SMiguel Ojeda     unsafe fn grow_impl(
193753dece8SMiguel Ojeda         &self,
194753dece8SMiguel Ojeda         ptr: NonNull<u8>,
195753dece8SMiguel Ojeda         old_layout: Layout,
196753dece8SMiguel Ojeda         new_layout: Layout,
197753dece8SMiguel Ojeda         zeroed: bool,
198753dece8SMiguel Ojeda     ) -> Result<NonNull<[u8]>, AllocError> {
199753dece8SMiguel Ojeda         debug_assert!(
200753dece8SMiguel Ojeda             new_layout.size() >= old_layout.size(),
201753dece8SMiguel Ojeda             "`new_layout.size()` must be greater than or equal to `old_layout.size()`"
202753dece8SMiguel Ojeda         );
203753dece8SMiguel Ojeda 
204753dece8SMiguel Ojeda         match old_layout.size() {
205753dece8SMiguel Ojeda             0 => self.alloc_impl(new_layout, zeroed),
206753dece8SMiguel Ojeda 
207753dece8SMiguel Ojeda             // SAFETY: `new_size` is non-zero as `old_size` is greater than or equal to `new_size`
208753dece8SMiguel Ojeda             // as required by safety conditions. Other conditions must be upheld by the caller
209753dece8SMiguel Ojeda             old_size if old_layout.align() == new_layout.align() => unsafe {
210753dece8SMiguel Ojeda                 let new_size = new_layout.size();
211753dece8SMiguel Ojeda 
212753dece8SMiguel Ojeda                 // `realloc` probably checks for `new_size >= old_layout.size()` or something similar.
213753dece8SMiguel Ojeda                 intrinsics::assume(new_size >= old_layout.size());
214753dece8SMiguel Ojeda 
215753dece8SMiguel Ojeda                 let raw_ptr = realloc(ptr.as_ptr(), old_layout, new_size);
216753dece8SMiguel Ojeda                 let ptr = NonNull::new(raw_ptr).ok_or(AllocError)?;
217753dece8SMiguel Ojeda                 if zeroed {
218753dece8SMiguel Ojeda                     raw_ptr.add(old_size).write_bytes(0, new_size - old_size);
219753dece8SMiguel Ojeda                 }
220753dece8SMiguel Ojeda                 Ok(NonNull::slice_from_raw_parts(ptr, new_size))
221753dece8SMiguel Ojeda             },
222753dece8SMiguel Ojeda 
223753dece8SMiguel Ojeda             // SAFETY: because `new_layout.size()` must be greater than or equal to `old_size`,
224753dece8SMiguel Ojeda             // both the old and new memory allocation are valid for reads and writes for `old_size`
225753dece8SMiguel Ojeda             // bytes. Also, because the old allocation wasn't yet deallocated, it cannot overlap
226753dece8SMiguel Ojeda             // `new_ptr`. Thus, the call to `copy_nonoverlapping` is safe. The safety contract
227753dece8SMiguel Ojeda             // for `dealloc` must be upheld by the caller.
228753dece8SMiguel Ojeda             old_size => unsafe {
229753dece8SMiguel Ojeda                 let new_ptr = self.alloc_impl(new_layout, zeroed)?;
230753dece8SMiguel Ojeda                 ptr::copy_nonoverlapping(ptr.as_ptr(), new_ptr.as_mut_ptr(), old_size);
231753dece8SMiguel Ojeda                 self.deallocate(ptr, old_layout);
232753dece8SMiguel Ojeda                 Ok(new_ptr)
233753dece8SMiguel Ojeda             },
234753dece8SMiguel Ojeda         }
235753dece8SMiguel Ojeda     }
236753dece8SMiguel Ojeda }
237753dece8SMiguel Ojeda 
238753dece8SMiguel Ojeda #[unstable(feature = "allocator_api", issue = "32838")]
239753dece8SMiguel Ojeda #[cfg(not(test))]
240753dece8SMiguel Ojeda unsafe impl Allocator for Global {
241753dece8SMiguel Ojeda     #[inline]
allocate(&self, layout: Layout) -> Result<NonNull<[u8]>, AllocError>242753dece8SMiguel Ojeda     fn allocate(&self, layout: Layout) -> Result<NonNull<[u8]>, AllocError> {
243753dece8SMiguel Ojeda         self.alloc_impl(layout, false)
244753dece8SMiguel Ojeda     }
245753dece8SMiguel Ojeda 
246753dece8SMiguel Ojeda     #[inline]
allocate_zeroed(&self, layout: Layout) -> Result<NonNull<[u8]>, AllocError>247753dece8SMiguel Ojeda     fn allocate_zeroed(&self, layout: Layout) -> Result<NonNull<[u8]>, AllocError> {
248753dece8SMiguel Ojeda         self.alloc_impl(layout, true)
249753dece8SMiguel Ojeda     }
250753dece8SMiguel Ojeda 
251753dece8SMiguel Ojeda     #[inline]
deallocate(&self, ptr: NonNull<u8>, layout: Layout)252753dece8SMiguel Ojeda     unsafe fn deallocate(&self, ptr: NonNull<u8>, layout: Layout) {
253753dece8SMiguel Ojeda         if layout.size() != 0 {
254753dece8SMiguel Ojeda             // SAFETY: `layout` is non-zero in size,
255753dece8SMiguel Ojeda             // other conditions must be upheld by the caller
256753dece8SMiguel Ojeda             unsafe { dealloc(ptr.as_ptr(), layout) }
257753dece8SMiguel Ojeda         }
258753dece8SMiguel Ojeda     }
259753dece8SMiguel Ojeda 
260753dece8SMiguel Ojeda     #[inline]
grow( &self, ptr: NonNull<u8>, old_layout: Layout, new_layout: Layout, ) -> Result<NonNull<[u8]>, AllocError>261753dece8SMiguel Ojeda     unsafe fn grow(
262753dece8SMiguel Ojeda         &self,
263753dece8SMiguel Ojeda         ptr: NonNull<u8>,
264753dece8SMiguel Ojeda         old_layout: Layout,
265753dece8SMiguel Ojeda         new_layout: Layout,
266753dece8SMiguel Ojeda     ) -> Result<NonNull<[u8]>, AllocError> {
267753dece8SMiguel Ojeda         // SAFETY: all conditions must be upheld by the caller
268753dece8SMiguel Ojeda         unsafe { self.grow_impl(ptr, old_layout, new_layout, false) }
269753dece8SMiguel Ojeda     }
270753dece8SMiguel Ojeda 
271753dece8SMiguel Ojeda     #[inline]
grow_zeroed( &self, ptr: NonNull<u8>, old_layout: Layout, new_layout: Layout, ) -> Result<NonNull<[u8]>, AllocError>272753dece8SMiguel Ojeda     unsafe fn grow_zeroed(
273753dece8SMiguel Ojeda         &self,
274753dece8SMiguel Ojeda         ptr: NonNull<u8>,
275753dece8SMiguel Ojeda         old_layout: Layout,
276753dece8SMiguel Ojeda         new_layout: Layout,
277753dece8SMiguel Ojeda     ) -> Result<NonNull<[u8]>, AllocError> {
278753dece8SMiguel Ojeda         // SAFETY: all conditions must be upheld by the caller
279753dece8SMiguel Ojeda         unsafe { self.grow_impl(ptr, old_layout, new_layout, true) }
280753dece8SMiguel Ojeda     }
281753dece8SMiguel Ojeda 
282753dece8SMiguel Ojeda     #[inline]
shrink( &self, ptr: NonNull<u8>, old_layout: Layout, new_layout: Layout, ) -> Result<NonNull<[u8]>, AllocError>283753dece8SMiguel Ojeda     unsafe fn shrink(
284753dece8SMiguel Ojeda         &self,
285753dece8SMiguel Ojeda         ptr: NonNull<u8>,
286753dece8SMiguel Ojeda         old_layout: Layout,
287753dece8SMiguel Ojeda         new_layout: Layout,
288753dece8SMiguel Ojeda     ) -> Result<NonNull<[u8]>, AllocError> {
289753dece8SMiguel Ojeda         debug_assert!(
290753dece8SMiguel Ojeda             new_layout.size() <= old_layout.size(),
291753dece8SMiguel Ojeda             "`new_layout.size()` must be smaller than or equal to `old_layout.size()`"
292753dece8SMiguel Ojeda         );
293753dece8SMiguel Ojeda 
294753dece8SMiguel Ojeda         match new_layout.size() {
295753dece8SMiguel Ojeda             // SAFETY: conditions must be upheld by the caller
296753dece8SMiguel Ojeda             0 => unsafe {
297753dece8SMiguel Ojeda                 self.deallocate(ptr, old_layout);
298753dece8SMiguel Ojeda                 Ok(NonNull::slice_from_raw_parts(new_layout.dangling(), 0))
299753dece8SMiguel Ojeda             },
300753dece8SMiguel Ojeda 
301753dece8SMiguel Ojeda             // SAFETY: `new_size` is non-zero. Other conditions must be upheld by the caller
302753dece8SMiguel Ojeda             new_size if old_layout.align() == new_layout.align() => unsafe {
303753dece8SMiguel Ojeda                 // `realloc` probably checks for `new_size <= old_layout.size()` or something similar.
304753dece8SMiguel Ojeda                 intrinsics::assume(new_size <= old_layout.size());
305753dece8SMiguel Ojeda 
306753dece8SMiguel Ojeda                 let raw_ptr = realloc(ptr.as_ptr(), old_layout, new_size);
307753dece8SMiguel Ojeda                 let ptr = NonNull::new(raw_ptr).ok_or(AllocError)?;
308753dece8SMiguel Ojeda                 Ok(NonNull::slice_from_raw_parts(ptr, new_size))
309753dece8SMiguel Ojeda             },
310753dece8SMiguel Ojeda 
311753dece8SMiguel Ojeda             // SAFETY: because `new_size` must be smaller than or equal to `old_layout.size()`,
312753dece8SMiguel Ojeda             // both the old and new memory allocation are valid for reads and writes for `new_size`
313753dece8SMiguel Ojeda             // bytes. Also, because the old allocation wasn't yet deallocated, it cannot overlap
314753dece8SMiguel Ojeda             // `new_ptr`. Thus, the call to `copy_nonoverlapping` is safe. The safety contract
315753dece8SMiguel Ojeda             // for `dealloc` must be upheld by the caller.
316753dece8SMiguel Ojeda             new_size => unsafe {
317753dece8SMiguel Ojeda                 let new_ptr = self.allocate(new_layout)?;
318753dece8SMiguel Ojeda                 ptr::copy_nonoverlapping(ptr.as_ptr(), new_ptr.as_mut_ptr(), new_size);
319753dece8SMiguel Ojeda                 self.deallocate(ptr, old_layout);
320753dece8SMiguel Ojeda                 Ok(new_ptr)
321753dece8SMiguel Ojeda             },
322753dece8SMiguel Ojeda         }
323753dece8SMiguel Ojeda     }
324753dece8SMiguel Ojeda }
325753dece8SMiguel Ojeda 
326753dece8SMiguel Ojeda /// The allocator for unique pointers.
327753dece8SMiguel Ojeda #[cfg(all(not(no_global_oom_handling), not(test)))]
328753dece8SMiguel Ojeda #[lang = "exchange_malloc"]
329753dece8SMiguel Ojeda #[inline]
exchange_malloc(size: usize, align: usize) -> *mut u8330753dece8SMiguel Ojeda unsafe fn exchange_malloc(size: usize, align: usize) -> *mut u8 {
331753dece8SMiguel Ojeda     let layout = unsafe { Layout::from_size_align_unchecked(size, align) };
332753dece8SMiguel Ojeda     match Global.allocate(layout) {
333753dece8SMiguel Ojeda         Ok(ptr) => ptr.as_mut_ptr(),
334753dece8SMiguel Ojeda         Err(_) => handle_alloc_error(layout),
335753dece8SMiguel Ojeda     }
336753dece8SMiguel Ojeda }
337753dece8SMiguel Ojeda 
338753dece8SMiguel Ojeda // # Allocation error handler
339753dece8SMiguel Ojeda 
340753dece8SMiguel Ojeda #[cfg(not(no_global_oom_handling))]
341753dece8SMiguel Ojeda extern "Rust" {
342753dece8SMiguel Ojeda     // This is the magic symbol to call the global alloc error handler. rustc generates
343753dece8SMiguel Ojeda     // it to call `__rg_oom` if there is a `#[alloc_error_handler]`, or to call the
344753dece8SMiguel Ojeda     // default implementations below (`__rdl_oom`) otherwise.
__rust_alloc_error_handler(size: usize, align: usize) -> !345753dece8SMiguel Ojeda     fn __rust_alloc_error_handler(size: usize, align: usize) -> !;
346753dece8SMiguel Ojeda }
347753dece8SMiguel Ojeda 
348753dece8SMiguel Ojeda /// Abort on memory allocation error or failure.
349753dece8SMiguel Ojeda ///
350753dece8SMiguel Ojeda /// Callers of memory allocation APIs wishing to abort computation
351753dece8SMiguel Ojeda /// in response to an allocation error are encouraged to call this function,
352753dece8SMiguel Ojeda /// rather than directly invoking `panic!` or similar.
353753dece8SMiguel Ojeda ///
354753dece8SMiguel Ojeda /// The default behavior of this function is to print a message to standard error
355753dece8SMiguel Ojeda /// and abort the process.
356753dece8SMiguel Ojeda /// It can be replaced with [`set_alloc_error_hook`] and [`take_alloc_error_hook`].
357753dece8SMiguel Ojeda ///
358753dece8SMiguel Ojeda /// [`set_alloc_error_hook`]: ../../std/alloc/fn.set_alloc_error_hook.html
359753dece8SMiguel Ojeda /// [`take_alloc_error_hook`]: ../../std/alloc/fn.take_alloc_error_hook.html
360753dece8SMiguel Ojeda #[stable(feature = "global_alloc", since = "1.28.0")]
361753dece8SMiguel Ojeda #[rustc_const_unstable(feature = "const_alloc_error", issue = "92523")]
362753dece8SMiguel Ojeda #[cfg(all(not(no_global_oom_handling), not(test)))]
363753dece8SMiguel Ojeda #[cold]
handle_alloc_error(layout: Layout) -> !364753dece8SMiguel Ojeda pub const fn handle_alloc_error(layout: Layout) -> ! {
365753dece8SMiguel Ojeda     const fn ct_error(_: Layout) -> ! {
366753dece8SMiguel Ojeda         panic!("allocation failed");
367753dece8SMiguel Ojeda     }
368753dece8SMiguel Ojeda 
369753dece8SMiguel Ojeda     fn rt_error(layout: Layout) -> ! {
370753dece8SMiguel Ojeda         unsafe {
371753dece8SMiguel Ojeda             __rust_alloc_error_handler(layout.size(), layout.align());
372753dece8SMiguel Ojeda         }
373753dece8SMiguel Ojeda     }
374753dece8SMiguel Ojeda 
375753dece8SMiguel Ojeda     unsafe { core::intrinsics::const_eval_select((layout,), ct_error, rt_error) }
376753dece8SMiguel Ojeda }
377753dece8SMiguel Ojeda 
378753dece8SMiguel Ojeda // For alloc test `std::alloc::handle_alloc_error` can be used directly.
379753dece8SMiguel Ojeda #[cfg(all(not(no_global_oom_handling), test))]
380753dece8SMiguel Ojeda pub use std::alloc::handle_alloc_error;
381753dece8SMiguel Ojeda 
382753dece8SMiguel Ojeda #[cfg(all(not(no_global_oom_handling), not(test)))]
383753dece8SMiguel Ojeda #[doc(hidden)]
384753dece8SMiguel Ojeda #[allow(unused_attributes)]
385753dece8SMiguel Ojeda #[unstable(feature = "alloc_internals", issue = "none")]
386753dece8SMiguel Ojeda pub mod __alloc_error_handler {
3873ed03f4dSMiguel Ojeda     // called via generated `__rust_alloc_error_handler` if there is no
3883ed03f4dSMiguel Ojeda     // `#[alloc_error_handler]`.
389753dece8SMiguel Ojeda     #[rustc_std_internal_symbol]
__rdl_oom(size: usize, _align: usize) -> !3903ed03f4dSMiguel Ojeda     pub unsafe fn __rdl_oom(size: usize, _align: usize) -> ! {
391753dece8SMiguel Ojeda         extern "Rust" {
3923ed03f4dSMiguel Ojeda             // This symbol is emitted by rustc next to __rust_alloc_error_handler.
3933ed03f4dSMiguel Ojeda             // Its value depends on the -Zoom={panic,abort} compiler option.
3943ed03f4dSMiguel Ojeda             static __rust_alloc_error_handler_should_panic: u8;
395753dece8SMiguel Ojeda         }
3963ed03f4dSMiguel Ojeda 
3973ed03f4dSMiguel Ojeda         if unsafe { __rust_alloc_error_handler_should_panic != 0 } {
3983ed03f4dSMiguel Ojeda             panic!("memory allocation of {size} bytes failed")
3993ed03f4dSMiguel Ojeda         } else {
4003ed03f4dSMiguel Ojeda             core::panicking::panic_nounwind_fmt(format_args!(
4013ed03f4dSMiguel Ojeda                 "memory allocation of {size} bytes failed"
4023ed03f4dSMiguel Ojeda             ))
4033ed03f4dSMiguel Ojeda         }
404753dece8SMiguel Ojeda     }
405753dece8SMiguel Ojeda }
406753dece8SMiguel Ojeda 
407753dece8SMiguel Ojeda /// Specialize clones into pre-allocated, uninitialized memory.
408753dece8SMiguel Ojeda /// Used by `Box::clone` and `Rc`/`Arc::make_mut`.
409753dece8SMiguel Ojeda pub(crate) trait WriteCloneIntoRaw: Sized {
write_clone_into_raw(&self, target: *mut Self)410753dece8SMiguel Ojeda     unsafe fn write_clone_into_raw(&self, target: *mut Self);
411753dece8SMiguel Ojeda }
412753dece8SMiguel Ojeda 
413753dece8SMiguel Ojeda impl<T: Clone> WriteCloneIntoRaw for T {
414753dece8SMiguel Ojeda     #[inline]
write_clone_into_raw(&self, target: *mut Self)415753dece8SMiguel Ojeda     default unsafe fn write_clone_into_raw(&self, target: *mut Self) {
416753dece8SMiguel Ojeda         // Having allocated *first* may allow the optimizer to create
417753dece8SMiguel Ojeda         // the cloned value in-place, skipping the local and move.
418753dece8SMiguel Ojeda         unsafe { target.write(self.clone()) };
419753dece8SMiguel Ojeda     }
420753dece8SMiguel Ojeda }
421753dece8SMiguel Ojeda 
422753dece8SMiguel Ojeda impl<T: Copy> WriteCloneIntoRaw for T {
423753dece8SMiguel Ojeda     #[inline]
write_clone_into_raw(&self, target: *mut Self)424753dece8SMiguel Ojeda     unsafe fn write_clone_into_raw(&self, target: *mut Self) {
425753dece8SMiguel Ojeda         // We can always copy in-place, without ever involving a local value.
426753dece8SMiguel Ojeda         unsafe { target.copy_from_nonoverlapping(self, 1) };
427753dece8SMiguel Ojeda     }
428753dece8SMiguel Ojeda }
429