]> git.lizzy.rs Git - rust.git/blob - library/alloc/src/alloc.rs
BTreeMap: better way to postpone root access in DrainFilter
[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 ///
40 /// [`AllocRef`]: trait.AllocRef.html
41 #[unstable(feature = "allocator_api", issue = "32838")]
42 #[derive(Copy, Clone, Default, Debug)]
43 pub struct Global;
44
45 /// Allocate memory with the global allocator.
46 ///
47 /// This function forwards calls to the [`GlobalAlloc::alloc`] method
48 /// of the allocator registered with the `#[global_allocator]` attribute
49 /// if there is one, or the `std` crate’s default.
50 ///
51 /// This function is expected to be deprecated in favor of the `alloc` method
52 /// of the [`Global`] type when it and the [`AllocRef`] trait become stable.
53 ///
54 /// # Safety
55 ///
56 /// See [`GlobalAlloc::alloc`].
57 ///
58 /// [`Global`]: struct.Global.html
59 /// [`AllocRef`]: trait.AllocRef.html
60 /// [`GlobalAlloc::alloc`]: trait.GlobalAlloc.html#tymethod.alloc
61 ///
62 /// # Examples
63 ///
64 /// ```
65 /// use std::alloc::{alloc, dealloc, Layout};
66 ///
67 /// unsafe {
68 ///     let layout = Layout::new::<u16>();
69 ///     let ptr = alloc(layout);
70 ///
71 ///     *(ptr as *mut u16) = 42;
72 ///     assert_eq!(*(ptr as *mut u16), 42);
73 ///
74 ///     dealloc(ptr, layout);
75 /// }
76 /// ```
77 #[stable(feature = "global_alloc", since = "1.28.0")]
78 #[inline]
79 pub unsafe fn alloc(layout: Layout) -> *mut u8 {
80     unsafe { __rust_alloc(layout.size(), layout.align()) }
81 }
82
83 /// Deallocate memory with the global allocator.
84 ///
85 /// This function forwards calls to the [`GlobalAlloc::dealloc`] method
86 /// of the allocator registered with the `#[global_allocator]` attribute
87 /// if there is one, or the `std` crate’s default.
88 ///
89 /// This function is expected to be deprecated in favor of the `dealloc` method
90 /// of the [`Global`] type when it and the [`AllocRef`] trait become stable.
91 ///
92 /// # Safety
93 ///
94 /// See [`GlobalAlloc::dealloc`].
95 ///
96 /// [`Global`]: struct.Global.html
97 /// [`AllocRef`]: trait.AllocRef.html
98 /// [`GlobalAlloc::dealloc`]: trait.GlobalAlloc.html#tymethod.dealloc
99 #[stable(feature = "global_alloc", since = "1.28.0")]
100 #[inline]
101 pub unsafe fn dealloc(ptr: *mut u8, layout: Layout) {
102     unsafe { __rust_dealloc(ptr, layout.size(), layout.align()) }
103 }
104
105 /// Reallocate memory with the global allocator.
106 ///
107 /// This function forwards calls to the [`GlobalAlloc::realloc`] method
108 /// of the allocator registered with the `#[global_allocator]` attribute
109 /// if there is one, or the `std` crate’s default.
110 ///
111 /// This function is expected to be deprecated in favor of the `realloc` method
112 /// of the [`Global`] type when it and the [`AllocRef`] trait become stable.
113 ///
114 /// # Safety
115 ///
116 /// See [`GlobalAlloc::realloc`].
117 ///
118 /// [`Global`]: struct.Global.html
119 /// [`AllocRef`]: trait.AllocRef.html
120 /// [`GlobalAlloc::realloc`]: trait.GlobalAlloc.html#method.realloc
121 #[stable(feature = "global_alloc", since = "1.28.0")]
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 [`AllocRef`] trait become stable.
135 ///
136 /// # Safety
137 ///
138 /// See [`GlobalAlloc::alloc_zeroed`].
139 ///
140 /// [`Global`]: struct.Global.html
141 /// [`AllocRef`]: trait.AllocRef.html
142 /// [`GlobalAlloc::alloc_zeroed`]: trait.GlobalAlloc.html#method.alloc_zeroed
143 ///
144 /// # Examples
145 ///
146 /// ```
147 /// use std::alloc::{alloc_zeroed, dealloc, Layout};
148 ///
149 /// unsafe {
150 ///     let layout = Layout::new::<u16>();
151 ///     let ptr = alloc_zeroed(layout);
152 ///
153 ///     assert_eq!(*(ptr as *mut u16), 0);
154 ///
155 ///     dealloc(ptr, layout);
156 /// }
157 /// ```
158 #[stable(feature = "global_alloc", since = "1.28.0")]
159 #[inline]
160 pub unsafe fn alloc_zeroed(layout: Layout) -> *mut u8 {
161     unsafe { __rust_alloc_zeroed(layout.size(), layout.align()) }
162 }
163
164 #[unstable(feature = "allocator_api", issue = "32838")]
165 unsafe impl AllocRef for Global {
166     #[inline]
167     fn alloc(&mut self, layout: Layout) -> Result<NonNull<[u8]>, AllocErr> {
168         let size = layout.size();
169         let ptr = if size == 0 {
170             layout.dangling()
171         } else {
172             // SAFETY: `layout` is non-zero in size,
173             unsafe { NonNull::new(alloc(layout)).ok_or(AllocErr)? }
174         };
175         Ok(NonNull::slice_from_raw_parts(ptr, size))
176     }
177
178     #[inline]
179     fn alloc_zeroed(&mut self, layout: Layout) -> Result<NonNull<[u8]>, AllocErr> {
180         let size = layout.size();
181         let ptr = if size == 0 {
182             layout.dangling()
183         } else {
184             // SAFETY: `layout` is non-zero in size,
185             unsafe { NonNull::new(alloc_zeroed(layout)).ok_or(AllocErr)? }
186         };
187         Ok(NonNull::slice_from_raw_parts(ptr, size))
188     }
189
190     #[inline]
191     unsafe fn dealloc(&mut self, ptr: NonNull<u8>, layout: Layout) {
192         if layout.size() != 0 {
193             // SAFETY: `layout` is non-zero in size,
194             // other conditions must be upheld by the caller
195             unsafe { dealloc(ptr.as_ptr(), layout) }
196         }
197     }
198
199     #[inline]
200     unsafe fn grow(
201         &mut self,
202         ptr: NonNull<u8>,
203         layout: Layout,
204         new_size: usize,
205     ) -> Result<NonNull<[u8]>, AllocErr> {
206         debug_assert!(
207             new_size >= layout.size(),
208             "`new_size` must be greater than or equal to `layout.size()`"
209         );
210
211         // SAFETY: `new_size` must be non-zero, which is checked in the match expression.
212         // Other conditions must be upheld by the caller
213         unsafe {
214             match layout.size() {
215                 old_size if old_size == new_size => {
216                     Ok(NonNull::slice_from_raw_parts(ptr, new_size))
217                 }
218                 0 => self.alloc(Layout::from_size_align_unchecked(new_size, layout.align())),
219                 old_size => {
220                     // `realloc` probably checks for `new_size > size` or something similar.
221                     intrinsics::assume(new_size > old_size);
222                     let raw_ptr = realloc(ptr.as_ptr(), layout, new_size);
223                     let ptr = NonNull::new(raw_ptr).ok_or(AllocErr)?;
224                     Ok(NonNull::slice_from_raw_parts(ptr, new_size))
225                 }
226             }
227         }
228     }
229
230     #[inline]
231     unsafe fn grow_zeroed(
232         &mut self,
233         ptr: NonNull<u8>,
234         layout: Layout,
235         new_size: usize,
236     ) -> Result<NonNull<[u8]>, AllocErr> {
237         debug_assert!(
238             new_size >= layout.size(),
239             "`new_size` must be greater than or equal to `layout.size()`"
240         );
241
242         // SAFETY: `new_size` must be non-zero, which is checked in the match expression.
243         // Other conditions must be upheld by the caller
244         unsafe {
245             match layout.size() {
246                 old_size if old_size == new_size => {
247                     Ok(NonNull::slice_from_raw_parts(ptr, new_size))
248                 }
249                 0 => self.alloc_zeroed(Layout::from_size_align_unchecked(new_size, layout.align())),
250                 old_size => {
251                     // `realloc` probably checks for `new_size > size` or something similar.
252                     intrinsics::assume(new_size > old_size);
253                     let raw_ptr = realloc(ptr.as_ptr(), layout, new_size);
254                     raw_ptr.add(old_size).write_bytes(0, new_size - old_size);
255                     let ptr = NonNull::new(raw_ptr).ok_or(AllocErr)?;
256                     Ok(NonNull::slice_from_raw_parts(ptr, new_size))
257                 }
258             }
259         }
260     }
261
262     #[inline]
263     unsafe fn shrink(
264         &mut self,
265         ptr: NonNull<u8>,
266         layout: Layout,
267         new_size: usize,
268     ) -> Result<NonNull<[u8]>, AllocErr> {
269         let old_size = layout.size();
270         debug_assert!(
271             new_size <= old_size,
272             "`new_size` must be smaller than or equal to `layout.size()`"
273         );
274
275         let ptr = if new_size == old_size {
276             ptr
277         } else if new_size == 0 {
278             // SAFETY: `layout` is non-zero in size as `old_size` != `new_size`
279             // Other conditions must be upheld by the caller
280             unsafe {
281                 self.dealloc(ptr, layout);
282             }
283             layout.dangling()
284         } else {
285             // SAFETY: new_size is not zero,
286             // Other conditions must be upheld by the caller
287             let raw_ptr = unsafe {
288                 // `realloc` probably checks for `new_size < old_size` or something similar.
289                 intrinsics::assume(new_size < old_size);
290                 realloc(ptr.as_ptr(), layout, new_size)
291             };
292             NonNull::new(raw_ptr).ok_or(AllocErr)?
293         };
294
295         Ok(NonNull::slice_from_raw_parts(ptr, new_size))
296     }
297 }
298
299 /// The allocator for unique pointers.
300 // This function must not unwind. If it does, MIR codegen will fail.
301 #[cfg(not(test))]
302 #[lang = "exchange_malloc"]
303 #[inline]
304 unsafe fn exchange_malloc(size: usize, align: usize) -> *mut u8 {
305     let layout = unsafe { Layout::from_size_align_unchecked(size, align) };
306     match Global.alloc(layout) {
307         Ok(ptr) => ptr.as_non_null_ptr().as_ptr(),
308         Err(_) => handle_alloc_error(layout),
309     }
310 }
311
312 #[cfg_attr(not(test), lang = "box_free")]
313 #[inline]
314 // This signature has to be the same as `Box`, otherwise an ICE will happen.
315 // When an additional parameter to `Box` is added (like `A: AllocRef`), this has to be added here as
316 // well.
317 // For example if `Box` is changed to  `struct Box<T: ?Sized, A: AllocRef>(Unique<T>, A)`,
318 // this function has to be changed to `fn box_free<T: ?Sized, A: AllocRef>(Unique<T>, A)` as well.
319 pub(crate) unsafe fn box_free<T: ?Sized>(ptr: Unique<T>) {
320     unsafe {
321         let size = size_of_val(ptr.as_ref());
322         let align = min_align_of_val(ptr.as_ref());
323         let layout = Layout::from_size_align_unchecked(size, align);
324         Global.dealloc(ptr.cast().into(), layout)
325     }
326 }
327
328 /// Abort on memory allocation error or failure.
329 ///
330 /// Callers of memory allocation APIs wishing to abort computation
331 /// in response to an allocation error are encouraged to call this function,
332 /// rather than directly invoking `panic!` or similar.
333 ///
334 /// The default behavior of this function is to print a message to standard error
335 /// and abort the process.
336 /// It can be replaced with [`set_alloc_error_hook`] and [`take_alloc_error_hook`].
337 ///
338 /// [`set_alloc_error_hook`]: ../../std/alloc/fn.set_alloc_error_hook.html
339 /// [`take_alloc_error_hook`]: ../../std/alloc/fn.take_alloc_error_hook.html
340 #[stable(feature = "global_alloc", since = "1.28.0")]
341 #[rustc_allocator_nounwind]
342 pub fn handle_alloc_error(layout: Layout) -> ! {
343     extern "Rust" {
344         #[lang = "oom"]
345         fn oom_impl(layout: Layout) -> !;
346     }
347     unsafe { oom_impl(layout) }
348 }