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