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