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