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