]> git.lizzy.rs Git - rust.git/blob - library/alloc/src/alloc.rs
Suggest `mem::forget` if `mem::ManuallyDrop::new` isn't used
[rust.git] / library / alloc / src / alloc.rs
1 //! Memory allocation APIs
2
3 #![stable(feature = "alloc_module", since = "1.28.0")]
4
5 use core::intrinsics::{self, min_align_of_val, size_of_val};
6 use core::ptr::{NonNull, Unique};
7
8 #[stable(feature = "alloc_module", since = "1.28.0")]
9 #[doc(inline)]
10 pub use core::alloc::*;
11
12 #[cfg(test)]
13 mod tests;
14
15 extern "Rust" {
16     // These are the magic symbols to call the global allocator.  rustc generates
17     // them from the `#[global_allocator]` attribute if there is one, or uses the
18     // default implementations in libstd (`__rdl_alloc` etc in `src/libstd/alloc.rs`)
19     // otherwise.
20     #[rustc_allocator]
21     #[rustc_allocator_nounwind]
22     fn __rust_alloc(size: usize, align: usize) -> *mut u8;
23     #[rustc_allocator_nounwind]
24     fn __rust_dealloc(ptr: *mut u8, size: usize, align: usize);
25     #[rustc_allocator_nounwind]
26     fn __rust_realloc(ptr: *mut u8, old_size: usize, align: usize, new_size: usize) -> *mut u8;
27     #[rustc_allocator_nounwind]
28     fn __rust_alloc_zeroed(size: usize, align: usize) -> *mut u8;
29 }
30
31 /// The global memory allocator.
32 ///
33 /// This type implements the [`AllocRef`] trait by forwarding calls
34 /// to the allocator registered with the `#[global_allocator]` attribute
35 /// if there is one, or the `std` crate’s default.
36 ///
37 /// Note: while this type is unstable, the functionality it provides can be
38 /// accessed through the [free functions in `alloc`](index.html#functions).
39 #[unstable(feature = "allocator_api", issue = "32838")]
40 #[derive(Copy, Clone, Default, Debug)]
41 pub struct Global;
42
43 /// Allocate memory with the global allocator.
44 ///
45 /// This function forwards calls to the [`GlobalAlloc::alloc`] method
46 /// of the allocator registered with the `#[global_allocator]` attribute
47 /// if there is one, or the `std` crate’s default.
48 ///
49 /// This function is expected to be deprecated in favor of the `alloc` method
50 /// of the [`Global`] type when it and the [`AllocRef`] trait become stable.
51 ///
52 /// # Safety
53 ///
54 /// See [`GlobalAlloc::alloc`].
55 ///
56 /// # Examples
57 ///
58 /// ```
59 /// use std::alloc::{alloc, dealloc, Layout};
60 ///
61 /// unsafe {
62 ///     let layout = Layout::new::<u16>();
63 ///     let ptr = alloc(layout);
64 ///
65 ///     *(ptr as *mut u16) = 42;
66 ///     assert_eq!(*(ptr as *mut u16), 42);
67 ///
68 ///     dealloc(ptr, layout);
69 /// }
70 /// ```
71 #[stable(feature = "global_alloc", since = "1.28.0")]
72 #[inline]
73 pub unsafe fn alloc(layout: Layout) -> *mut u8 {
74     unsafe { __rust_alloc(layout.size(), layout.align()) }
75 }
76
77 /// Deallocate memory with the global allocator.
78 ///
79 /// This function forwards calls to the [`GlobalAlloc::dealloc`] method
80 /// of the allocator registered with the `#[global_allocator]` attribute
81 /// if there is one, or the `std` crate’s default.
82 ///
83 /// This function is expected to be deprecated in favor of the `dealloc` method
84 /// of the [`Global`] type when it and the [`AllocRef`] trait become stable.
85 ///
86 /// # Safety
87 ///
88 /// See [`GlobalAlloc::dealloc`].
89 #[stable(feature = "global_alloc", since = "1.28.0")]
90 #[inline]
91 pub unsafe fn dealloc(ptr: *mut u8, layout: Layout) {
92     unsafe { __rust_dealloc(ptr, layout.size(), layout.align()) }
93 }
94
95 /// Reallocate memory with the global allocator.
96 ///
97 /// This function forwards calls to the [`GlobalAlloc::realloc`] method
98 /// of the allocator registered with the `#[global_allocator]` attribute
99 /// if there is one, or the `std` crate’s default.
100 ///
101 /// This function is expected to be deprecated in favor of the `realloc` method
102 /// of the [`Global`] type when it and the [`AllocRef`] trait become stable.
103 ///
104 /// # Safety
105 ///
106 /// See [`GlobalAlloc::realloc`].
107 #[stable(feature = "global_alloc", since = "1.28.0")]
108 #[inline]
109 pub unsafe fn realloc(ptr: *mut u8, layout: Layout, new_size: usize) -> *mut u8 {
110     unsafe { __rust_realloc(ptr, layout.size(), layout.align(), new_size) }
111 }
112
113 /// Allocate zero-initialized memory with the global allocator.
114 ///
115 /// This function forwards calls to the [`GlobalAlloc::alloc_zeroed`] method
116 /// of the allocator registered with the `#[global_allocator]` attribute
117 /// if there is one, or the `std` crate’s default.
118 ///
119 /// This function is expected to be deprecated in favor of the `alloc_zeroed` method
120 /// of the [`Global`] type when it and the [`AllocRef`] trait become stable.
121 ///
122 /// # Safety
123 ///
124 /// See [`GlobalAlloc::alloc_zeroed`].
125 ///
126 /// # Examples
127 ///
128 /// ```
129 /// use std::alloc::{alloc_zeroed, dealloc, Layout};
130 ///
131 /// unsafe {
132 ///     let layout = Layout::new::<u16>();
133 ///     let ptr = alloc_zeroed(layout);
134 ///
135 ///     assert_eq!(*(ptr as *mut u16), 0);
136 ///
137 ///     dealloc(ptr, layout);
138 /// }
139 /// ```
140 #[stable(feature = "global_alloc", since = "1.28.0")]
141 #[inline]
142 pub unsafe fn alloc_zeroed(layout: Layout) -> *mut u8 {
143     unsafe { __rust_alloc_zeroed(layout.size(), layout.align()) }
144 }
145
146 impl Global {
147     #[inline]
148     fn alloc_impl(&mut self, layout: Layout, zeroed: bool) -> Result<NonNull<[u8]>, AllocErr> {
149         match layout.size() {
150             0 => Ok(NonNull::slice_from_raw_parts(layout.dangling(), 0)),
151             // SAFETY: `layout` is non-zero in size,
152             size => unsafe {
153                 let raw_ptr = if zeroed { alloc_zeroed(layout) } else { alloc(layout) };
154                 let ptr = NonNull::new(raw_ptr).ok_or(AllocErr)?;
155                 Ok(NonNull::slice_from_raw_parts(ptr, size))
156             },
157         }
158     }
159
160     // Safety: Same as `AllocRef::grow`
161     #[inline]
162     unsafe fn grow_impl(
163         &mut self,
164         ptr: NonNull<u8>,
165         layout: Layout,
166         new_size: usize,
167         zeroed: bool,
168     ) -> Result<NonNull<[u8]>, AllocErr> {
169         debug_assert!(
170             new_size >= layout.size(),
171             "`new_size` must be greater than or equal to `layout.size()`"
172         );
173
174         match layout.size() {
175             // SAFETY: the caller must ensure that the `new_size` does not overflow.
176             // `layout.align()` comes from a `Layout` and is thus guaranteed to be valid for a Layout.
177             0 => unsafe {
178                 let new_layout = Layout::from_size_align_unchecked(new_size, layout.align());
179                 self.alloc_impl(new_layout, zeroed)
180             },
181
182             // SAFETY: `new_size` is non-zero as `old_size` is greater than or equal to `new_size`
183             // as required by safety conditions. Other conditions must be upheld by the caller
184             old_size => unsafe {
185                 // `realloc` probably checks for `new_size >= size` or something similar.
186                 intrinsics::assume(new_size >= layout.size());
187
188                 let raw_ptr = realloc(ptr.as_ptr(), layout, new_size);
189                 let ptr = NonNull::new(raw_ptr).ok_or(AllocErr)?;
190                 if zeroed {
191                     raw_ptr.add(old_size).write_bytes(0, new_size - old_size);
192                 }
193                 Ok(NonNull::slice_from_raw_parts(ptr, new_size))
194             },
195         }
196     }
197 }
198
199 #[unstable(feature = "allocator_api", issue = "32838")]
200 unsafe impl AllocRef for Global {
201     #[inline]
202     fn alloc(&mut self, layout: Layout) -> Result<NonNull<[u8]>, AllocErr> {
203         self.alloc_impl(layout, false)
204     }
205
206     #[inline]
207     fn alloc_zeroed(&mut self, layout: Layout) -> Result<NonNull<[u8]>, AllocErr> {
208         self.alloc_impl(layout, true)
209     }
210
211     #[inline]
212     unsafe fn dealloc(&mut self, ptr: NonNull<u8>, layout: Layout) {
213         if layout.size() != 0 {
214             // SAFETY: `layout` is non-zero in size,
215             // other conditions must be upheld by the caller
216             unsafe { dealloc(ptr.as_ptr(), layout) }
217         }
218     }
219
220     #[inline]
221     unsafe fn grow(
222         &mut self,
223         ptr: NonNull<u8>,
224         layout: Layout,
225         new_size: usize,
226     ) -> Result<NonNull<[u8]>, AllocErr> {
227         // SAFETY: all conditions must be upheld by the caller
228         unsafe { self.grow_impl(ptr, layout, new_size, false) }
229     }
230
231     #[inline]
232     unsafe fn grow_zeroed(
233         &mut self,
234         ptr: NonNull<u8>,
235         layout: Layout,
236         new_size: usize,
237     ) -> Result<NonNull<[u8]>, AllocErr> {
238         // SAFETY: all conditions must be upheld by the caller
239         unsafe { self.grow_impl(ptr, layout, new_size, true) }
240     }
241
242     #[inline]
243     unsafe fn shrink(
244         &mut self,
245         ptr: NonNull<u8>,
246         layout: Layout,
247         new_size: usize,
248     ) -> Result<NonNull<[u8]>, AllocErr> {
249         debug_assert!(
250             new_size <= layout.size(),
251             "`new_size` must be smaller than or equal to `layout.size()`"
252         );
253
254         match new_size {
255             // SAFETY: conditions must be upheld by the caller
256             0 => unsafe {
257                 self.dealloc(ptr, layout);
258                 Ok(NonNull::slice_from_raw_parts(layout.dangling(), 0))
259             },
260
261             // SAFETY: `new_size` is non-zero. Other conditions must be upheld by the caller
262             new_size => unsafe {
263                 // `realloc` probably checks for `new_size <= size` or something similar.
264                 intrinsics::assume(new_size <= layout.size());
265
266                 let raw_ptr = realloc(ptr.as_ptr(), layout, new_size);
267                 let ptr = NonNull::new(raw_ptr).ok_or(AllocErr)?;
268                 Ok(NonNull::slice_from_raw_parts(ptr, new_size))
269             },
270         }
271     }
272 }
273
274 /// The allocator for unique pointers.
275 // This function must not unwind. If it does, MIR codegen will fail.
276 #[cfg(not(test))]
277 #[lang = "exchange_malloc"]
278 #[inline]
279 unsafe fn exchange_malloc(size: usize, align: usize) -> *mut u8 {
280     let layout = unsafe { Layout::from_size_align_unchecked(size, align) };
281     match Global.alloc(layout) {
282         Ok(ptr) => ptr.as_non_null_ptr().as_ptr(),
283         Err(_) => handle_alloc_error(layout),
284     }
285 }
286
287 #[cfg_attr(not(test), lang = "box_free")]
288 #[inline]
289 // This signature has to be the same as `Box`, otherwise an ICE will happen.
290 // When an additional parameter to `Box` is added (like `A: AllocRef`), this has to be added here as
291 // well.
292 // For example if `Box` is changed to  `struct Box<T: ?Sized, A: AllocRef>(Unique<T>, A)`,
293 // this function has to be changed to `fn box_free<T: ?Sized, A: AllocRef>(Unique<T>, A)` as well.
294 pub(crate) unsafe fn box_free<T: ?Sized>(ptr: Unique<T>) {
295     unsafe {
296         let size = size_of_val(ptr.as_ref());
297         let align = min_align_of_val(ptr.as_ref());
298         let layout = Layout::from_size_align_unchecked(size, align);
299         Global.dealloc(ptr.cast().into(), layout)
300     }
301 }
302
303 /// Abort on memory allocation error or failure.
304 ///
305 /// Callers of memory allocation APIs wishing to abort computation
306 /// in response to an allocation error are encouraged to call this function,
307 /// rather than directly invoking `panic!` or similar.
308 ///
309 /// The default behavior of this function is to print a message to standard error
310 /// and abort the process.
311 /// It can be replaced with [`set_alloc_error_hook`] and [`take_alloc_error_hook`].
312 ///
313 /// [`set_alloc_error_hook`]: ../../std/alloc/fn.set_alloc_error_hook.html
314 /// [`take_alloc_error_hook`]: ../../std/alloc/fn.take_alloc_error_hook.html
315 #[stable(feature = "global_alloc", since = "1.28.0")]
316 #[rustc_allocator_nounwind]
317 pub fn handle_alloc_error(layout: Layout) -> ! {
318     extern "Rust" {
319         #[lang = "oom"]
320         fn oom_impl(layout: Layout) -> !;
321     }
322     unsafe { oom_impl(layout) }
323 }