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