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