]> git.lizzy.rs Git - rust.git/blob - src/liballoc/alloc.rs
Rollup merge of #61453 - lzutao:nouse-featuregate-integer_atomics, r=sfackler
[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::{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 extern "Rust" {
14     // These are the magic symbols to call the global allocator.  rustc generates
15     // them from the `#[global_allocator]` attribute if there is one, or uses the
16     // default implementations in libstd (`__rdl_alloc` etc in `src/libstd/alloc.rs`)
17     // otherwise.
18     #[allocator]
19     #[rustc_allocator_nounwind]
20     fn __rust_alloc(size: usize, align: usize) -> *mut u8;
21     #[rustc_allocator_nounwind]
22     fn __rust_dealloc(ptr: *mut u8, size: usize, align: usize);
23     #[rustc_allocator_nounwind]
24     fn __rust_realloc(ptr: *mut u8,
25                       old_size: usize,
26                       align: usize,
27                       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 [`Alloc`] 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 /// [`Alloc`]: trait.Alloc.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 [`Alloc`] trait become stable.
54 ///
55 /// # Safety
56 ///
57 /// See [`GlobalAlloc::alloc`].
58 ///
59 /// [`Global`]: struct.Global.html
60 /// [`Alloc`]: trait.Alloc.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 [`Alloc`] trait become stable.
92 ///
93 /// # Safety
94 ///
95 /// See [`GlobalAlloc::dealloc`].
96 ///
97 /// [`Global`]: struct.Global.html
98 /// [`Alloc`]: trait.Alloc.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 [`Alloc`] trait become stable.
114 ///
115 /// # Safety
116 ///
117 /// See [`GlobalAlloc::realloc`].
118 ///
119 /// [`Global`]: struct.Global.html
120 /// [`Alloc`]: trait.Alloc.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 [`Alloc`] trait become stable.
136 ///
137 /// # Safety
138 ///
139 /// See [`GlobalAlloc::alloc_zeroed`].
140 ///
141 /// [`Global`]: struct.Global.html
142 /// [`Alloc`]: trait.Alloc.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 Alloc for Global {
167     #[inline]
168     unsafe fn alloc(&mut self, layout: Layout) -> Result<NonNull<u8>, AllocErr> {
169         NonNull::new(alloc(layout)).ok_or(AllocErr)
170     }
171
172     #[inline]
173     unsafe fn dealloc(&mut self, ptr: NonNull<u8>, layout: Layout) {
174         dealloc(ptr.as_ptr(), layout)
175     }
176
177     #[inline]
178     unsafe fn realloc(&mut self,
179                       ptr: NonNull<u8>,
180                       layout: Layout,
181                       new_size: usize)
182                       -> Result<NonNull<u8>, AllocErr>
183     {
184         NonNull::new(realloc(ptr.as_ptr(), layout, new_size)).ok_or(AllocErr)
185     }
186
187     #[inline]
188     unsafe fn alloc_zeroed(&mut self, layout: Layout) -> Result<NonNull<u8>, AllocErr> {
189         NonNull::new(alloc_zeroed(layout)).ok_or(AllocErr)
190     }
191 }
192
193 /// The allocator for unique pointers.
194 // This function must not unwind. If it does, MIR codegen will fail.
195 #[cfg(not(test))]
196 #[lang = "exchange_malloc"]
197 #[inline]
198 unsafe fn exchange_malloc(size: usize, align: usize) -> *mut u8 {
199     if size == 0 {
200         align as *mut u8
201     } else {
202         let layout = Layout::from_size_align_unchecked(size, align);
203         let ptr = alloc(layout);
204         if !ptr.is_null() {
205             ptr
206         } else {
207             handle_alloc_error(layout)
208         }
209     }
210 }
211
212 #[cfg_attr(not(test), lang = "box_free")]
213 #[inline]
214 pub(crate) unsafe fn box_free<T: ?Sized>(ptr: Unique<T>) {
215     let ptr = ptr.as_ptr();
216     let size = size_of_val(&*ptr);
217     let align = min_align_of_val(&*ptr);
218     // We do not allocate for Box<T> when T is ZST, so deallocation is also not necessary.
219     if size != 0 {
220         let layout = Layout::from_size_align_unchecked(size, align);
221         dealloc(ptr as *mut u8, layout);
222     }
223 }
224
225 /// Abort on memory allocation error or failure.
226 ///
227 /// Callers of memory allocation APIs wishing to abort computation
228 /// in response to an allocation error are encouraged to call this function,
229 /// rather than directly invoking `panic!` or similar.
230 ///
231 /// The default behavior of this function is to print a message to standard error
232 /// and abort the process.
233 /// It can be replaced with [`set_alloc_error_hook`] and [`take_alloc_error_hook`].
234 ///
235 /// [`set_alloc_error_hook`]: ../../std/alloc/fn.set_alloc_error_hook.html
236 /// [`take_alloc_error_hook`]: ../../std/alloc/fn.take_alloc_error_hook.html
237 #[stable(feature = "global_alloc", since = "1.28.0")]
238 #[rustc_allocator_nounwind]
239 pub fn handle_alloc_error(layout: Layout) -> ! {
240     #[allow(improper_ctypes)]
241     extern "Rust" {
242         #[lang = "oom"]
243         fn oom_impl(layout: Layout) -> !;
244     }
245     unsafe { oom_impl(layout) }
246 }
247
248 #[cfg(test)]
249 mod tests {
250     extern crate test;
251     use test::Bencher;
252     use crate::boxed::Box;
253     use crate::alloc::{Global, Alloc, Layout, handle_alloc_error};
254
255     #[test]
256     fn allocate_zeroed() {
257         unsafe {
258             let layout = Layout::from_size_align(1024, 1).unwrap();
259             let ptr = Global.alloc_zeroed(layout.clone())
260                 .unwrap_or_else(|_| handle_alloc_error(layout));
261
262             let mut i = ptr.cast::<u8>().as_ptr();
263             let end = i.add(layout.size());
264             while i < end {
265                 assert_eq!(*i, 0);
266                 i = i.offset(1);
267             }
268             Global.dealloc(ptr, layout);
269         }
270     }
271
272     #[bench]
273     #[cfg(not(miri))] // Miri does not support benchmarks
274     fn alloc_owned_small(b: &mut Bencher) {
275         b.iter(|| {
276             let _: Box<_> = box 10;
277         })
278     }
279 }