]> git.lizzy.rs Git - rust.git/blob - src/liballoc/alloc.rs
Rollup merge of #58044 - Lokathor:lokathor, r=alexcrichton
[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 #[unstable(feature = "allocator_api", issue = "32838")]
38 #[derive(Copy, Clone, Default, Debug)]
39 pub struct Global;
40
41 /// Allocate memory with the global allocator.
42 ///
43 /// This function forwards calls to the [`GlobalAlloc::alloc`] method
44 /// of the allocator registered with the `#[global_allocator]` attribute
45 /// if there is one, or the `std` crate’s default.
46 ///
47 /// This function is expected to be deprecated in favor of the `alloc` method
48 /// of the [`Global`] type when it and the [`Alloc`] trait become stable.
49 ///
50 /// # Safety
51 ///
52 /// See [`GlobalAlloc::alloc`].
53 ///
54 /// # Examples
55 ///
56 /// ```
57 /// use std::alloc::{alloc, dealloc, Layout};
58 ///
59 /// unsafe {
60 ///     let layout = Layout::new::<u16>();
61 ///     let ptr = alloc(layout);
62 ///
63 ///     *(ptr as *mut u16) = 42;
64 ///     assert_eq!(*(ptr as *mut u16), 42);
65 ///
66 ///     dealloc(ptr, layout);
67 /// }
68 /// ```
69 #[stable(feature = "global_alloc", since = "1.28.0")]
70 #[inline]
71 pub unsafe fn alloc(layout: Layout) -> *mut u8 {
72     __rust_alloc(layout.size(), layout.align())
73 }
74
75 /// Deallocate memory with the global allocator.
76 ///
77 /// This function forwards calls to the [`GlobalAlloc::dealloc`] method
78 /// of the allocator registered with the `#[global_allocator]` attribute
79 /// if there is one, or the `std` crate’s default.
80 ///
81 /// This function is expected to be deprecated in favor of the `dealloc` method
82 /// of the [`Global`] type when it and the [`Alloc`] trait become stable.
83 ///
84 /// # Safety
85 ///
86 /// See [`GlobalAlloc::dealloc`].
87 #[stable(feature = "global_alloc", since = "1.28.0")]
88 #[inline]
89 pub unsafe fn dealloc(ptr: *mut u8, layout: Layout) {
90     __rust_dealloc(ptr, layout.size(), layout.align())
91 }
92
93 /// Reallocate memory with the global allocator.
94 ///
95 /// This function forwards calls to the [`GlobalAlloc::realloc`] method
96 /// of the allocator registered with the `#[global_allocator]` attribute
97 /// if there is one, or the `std` crate’s default.
98 ///
99 /// This function is expected to be deprecated in favor of the `realloc` method
100 /// of the [`Global`] type when it and the [`Alloc`] trait become stable.
101 ///
102 /// # Safety
103 ///
104 /// See [`GlobalAlloc::realloc`].
105 #[stable(feature = "global_alloc", since = "1.28.0")]
106 #[inline]
107 pub unsafe fn realloc(ptr: *mut u8, layout: Layout, new_size: usize) -> *mut u8 {
108     __rust_realloc(ptr, layout.size(), layout.align(), new_size)
109 }
110
111 /// Allocate zero-initialized memory with the global allocator.
112 ///
113 /// This function forwards calls to the [`GlobalAlloc::alloc_zeroed`] method
114 /// of the allocator registered with the `#[global_allocator]` attribute
115 /// if there is one, or the `std` crate’s default.
116 ///
117 /// This function is expected to be deprecated in favor of the `alloc_zeroed` method
118 /// of the [`Global`] type when it and the [`Alloc`] trait become stable.
119 ///
120 /// # Safety
121 ///
122 /// See [`GlobalAlloc::alloc_zeroed`].
123 ///
124 /// # Examples
125 ///
126 /// ```
127 /// use std::alloc::{alloc_zeroed, dealloc, Layout};
128 ///
129 /// unsafe {
130 ///     let layout = Layout::new::<u16>();
131 ///     let ptr = alloc_zeroed(layout);
132 ///
133 ///     assert_eq!(*(ptr as *mut u16), 0);
134 ///
135 ///     dealloc(ptr, layout);
136 /// }
137 /// ```
138 #[stable(feature = "global_alloc", since = "1.28.0")]
139 #[inline]
140 pub unsafe fn alloc_zeroed(layout: Layout) -> *mut u8 {
141     __rust_alloc_zeroed(layout.size(), layout.align())
142 }
143
144 #[unstable(feature = "allocator_api", issue = "32838")]
145 unsafe impl Alloc for Global {
146     #[inline]
147     unsafe fn alloc(&mut self, layout: Layout) -> Result<NonNull<u8>, AllocErr> {
148         NonNull::new(alloc(layout)).ok_or(AllocErr)
149     }
150
151     #[inline]
152     unsafe fn dealloc(&mut self, ptr: NonNull<u8>, layout: Layout) {
153         dealloc(ptr.as_ptr(), layout)
154     }
155
156     #[inline]
157     unsafe fn realloc(&mut self,
158                       ptr: NonNull<u8>,
159                       layout: Layout,
160                       new_size: usize)
161                       -> Result<NonNull<u8>, AllocErr>
162     {
163         NonNull::new(realloc(ptr.as_ptr(), layout, new_size)).ok_or(AllocErr)
164     }
165
166     #[inline]
167     unsafe fn alloc_zeroed(&mut self, layout: Layout) -> Result<NonNull<u8>, AllocErr> {
168         NonNull::new(alloc_zeroed(layout)).ok_or(AllocErr)
169     }
170 }
171
172 /// The allocator for unique pointers.
173 // This function must not unwind. If it does, MIR codegen will fail.
174 #[cfg(not(test))]
175 #[lang = "exchange_malloc"]
176 #[inline]
177 unsafe fn exchange_malloc(size: usize, align: usize) -> *mut u8 {
178     if size == 0 {
179         align as *mut u8
180     } else {
181         let layout = Layout::from_size_align_unchecked(size, align);
182         let ptr = alloc(layout);
183         if !ptr.is_null() {
184             ptr
185         } else {
186             handle_alloc_error(layout)
187         }
188     }
189 }
190
191 #[cfg_attr(not(test), lang = "box_free")]
192 #[inline]
193 pub(crate) unsafe fn box_free<T: ?Sized>(ptr: Unique<T>) {
194     let ptr = ptr.as_ptr();
195     let size = size_of_val(&*ptr);
196     let align = min_align_of_val(&*ptr);
197     // We do not allocate for Box<T> when T is ZST, so deallocation is also not necessary.
198     if size != 0 {
199         let layout = Layout::from_size_align_unchecked(size, align);
200         dealloc(ptr as *mut u8, layout);
201     }
202 }
203
204 /// Abort on memory allocation error or failure.
205 ///
206 /// Callers of memory allocation APIs wishing to abort computation
207 /// in response to an allocation error are encouraged to call this function,
208 /// rather than directly invoking `panic!` or similar.
209 ///
210 /// The default behavior of this function is to print a message to standard error
211 /// and abort the process.
212 /// It can be replaced with [`set_alloc_error_hook`] and [`take_alloc_error_hook`].
213 ///
214 /// [`set_alloc_error_hook`]: ../../std/alloc/fn.set_alloc_error_hook.html
215 /// [`take_alloc_error_hook`]: ../../std/alloc/fn.take_alloc_error_hook.html
216 #[stable(feature = "global_alloc", since = "1.28.0")]
217 #[rustc_allocator_nounwind]
218 pub fn handle_alloc_error(layout: Layout) -> ! {
219     #[allow(improper_ctypes)]
220     extern "Rust" {
221         #[lang = "oom"]
222         fn oom_impl(layout: Layout) -> !;
223     }
224     unsafe { oom_impl(layout) }
225 }
226
227 #[cfg(test)]
228 mod tests {
229     extern crate test;
230     use test::Bencher;
231     use crate::boxed::Box;
232     use crate::alloc::{Global, Alloc, Layout, handle_alloc_error};
233
234     #[test]
235     fn allocate_zeroed() {
236         unsafe {
237             let layout = Layout::from_size_align(1024, 1).unwrap();
238             let ptr = Global.alloc_zeroed(layout.clone())
239                 .unwrap_or_else(|_| handle_alloc_error(layout));
240
241             let mut i = ptr.cast::<u8>().as_ptr();
242             let end = i.add(layout.size());
243             while i < end {
244                 assert_eq!(*i, 0);
245                 i = i.offset(1);
246             }
247             Global.dealloc(ptr, layout);
248         }
249     }
250
251     #[bench]
252     fn alloc_owned_small(b: &mut Bencher) {
253         b.iter(|| {
254             let _: Box<_> = box 10;
255         })
256     }
257 }