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