]> git.lizzy.rs Git - rust.git/blob - library/alloc/src/alloc.rs
Remove unused code from remaining compiler crates
[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::{self, 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 to call `__rg_alloc` etc if there is a `#[global_allocator]` attribute
18     // (the code expanding that attribute macro generates those functions), or to call
19     // the 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 #[unstable(feature = "allocator_api", issue = "32838")]
41 #[derive(Copy, Clone, Default, Debug)]
42 pub struct Global;
43
44 /// Allocate memory with the global allocator.
45 ///
46 /// This function forwards calls to the [`GlobalAlloc::alloc`] method
47 /// of the allocator registered with the `#[global_allocator]` attribute
48 /// if there is one, or the `std` crate’s default.
49 ///
50 /// This function is expected to be deprecated in favor of the `alloc` method
51 /// of the [`Global`] type when it and the [`AllocRef`] trait become stable.
52 ///
53 /// # Safety
54 ///
55 /// See [`GlobalAlloc::alloc`].
56 ///
57 /// # Examples
58 ///
59 /// ```
60 /// use std::alloc::{alloc, dealloc, Layout};
61 ///
62 /// unsafe {
63 ///     let layout = Layout::new::<u16>();
64 ///     let ptr = alloc(layout);
65 ///
66 ///     *(ptr as *mut u16) = 42;
67 ///     assert_eq!(*(ptr as *mut u16), 42);
68 ///
69 ///     dealloc(ptr, layout);
70 /// }
71 /// ```
72 #[stable(feature = "global_alloc", since = "1.28.0")]
73 #[inline]
74 pub unsafe fn alloc(layout: Layout) -> *mut u8 {
75     unsafe { __rust_alloc(layout.size(), layout.align()) }
76 }
77
78 /// Deallocate memory with the global allocator.
79 ///
80 /// This function forwards calls to the [`GlobalAlloc::dealloc`] method
81 /// of the allocator registered with the `#[global_allocator]` attribute
82 /// if there is one, or the `std` crate’s default.
83 ///
84 /// This function is expected to be deprecated in favor of the `dealloc` method
85 /// of the [`Global`] type when it and the [`AllocRef`] trait become stable.
86 ///
87 /// # Safety
88 ///
89 /// See [`GlobalAlloc::dealloc`].
90 #[stable(feature = "global_alloc", since = "1.28.0")]
91 #[inline]
92 pub unsafe fn dealloc(ptr: *mut u8, layout: Layout) {
93     unsafe { __rust_dealloc(ptr, layout.size(), layout.align()) }
94 }
95
96 /// Reallocate memory with the global allocator.
97 ///
98 /// This function forwards calls to the [`GlobalAlloc::realloc`] method
99 /// of the allocator registered with the `#[global_allocator]` attribute
100 /// if there is one, or the `std` crate’s default.
101 ///
102 /// This function is expected to be deprecated in favor of the `realloc` method
103 /// of the [`Global`] type when it and the [`AllocRef`] trait become stable.
104 ///
105 /// # Safety
106 ///
107 /// See [`GlobalAlloc::realloc`].
108 #[stable(feature = "global_alloc", since = "1.28.0")]
109 #[inline]
110 pub unsafe fn realloc(ptr: *mut u8, layout: Layout, new_size: usize) -> *mut u8 {
111     unsafe { __rust_realloc(ptr, layout.size(), layout.align(), new_size) }
112 }
113
114 /// Allocate zero-initialized memory with the global allocator.
115 ///
116 /// This function forwards calls to the [`GlobalAlloc::alloc_zeroed`] method
117 /// of the allocator registered with the `#[global_allocator]` attribute
118 /// if there is one, or the `std` crate’s default.
119 ///
120 /// This function is expected to be deprecated in favor of the `alloc_zeroed` method
121 /// of the [`Global`] type when it and the [`AllocRef`] trait become stable.
122 ///
123 /// # Safety
124 ///
125 /// See [`GlobalAlloc::alloc_zeroed`].
126 ///
127 /// # Examples
128 ///
129 /// ```
130 /// use std::alloc::{alloc_zeroed, dealloc, Layout};
131 ///
132 /// unsafe {
133 ///     let layout = Layout::new::<u16>();
134 ///     let ptr = alloc_zeroed(layout);
135 ///
136 ///     assert_eq!(*(ptr as *mut u16), 0);
137 ///
138 ///     dealloc(ptr, layout);
139 /// }
140 /// ```
141 #[stable(feature = "global_alloc", since = "1.28.0")]
142 #[inline]
143 pub unsafe fn alloc_zeroed(layout: Layout) -> *mut u8 {
144     unsafe { __rust_alloc_zeroed(layout.size(), layout.align()) }
145 }
146
147 impl Global {
148     #[inline]
149     fn alloc_impl(&self, layout: Layout, zeroed: bool) -> Result<NonNull<[u8]>, AllocError> {
150         match layout.size() {
151             0 => Ok(NonNull::slice_from_raw_parts(layout.dangling(), 0)),
152             // SAFETY: `layout` is non-zero in size,
153             size => unsafe {
154                 let raw_ptr = if zeroed { alloc_zeroed(layout) } else { alloc(layout) };
155                 let ptr = NonNull::new(raw_ptr).ok_or(AllocError)?;
156                 Ok(NonNull::slice_from_raw_parts(ptr, size))
157             },
158         }
159     }
160
161     // SAFETY: Same as `AllocRef::grow`
162     #[inline]
163     unsafe fn grow_impl(
164         &self,
165         ptr: NonNull<u8>,
166         old_layout: Layout,
167         new_layout: Layout,
168         zeroed: bool,
169     ) -> Result<NonNull<[u8]>, AllocError> {
170         debug_assert!(
171             new_layout.size() >= old_layout.size(),
172             "`new_layout.size()` must be greater than or equal to `old_layout.size()`"
173         );
174
175         match old_layout.size() {
176             0 => self.alloc_impl(new_layout, zeroed),
177
178             // SAFETY: `new_size` is non-zero as `old_size` is greater than or equal to `new_size`
179             // as required by safety conditions. Other conditions must be upheld by the caller
180             old_size if old_layout.align() == new_layout.align() => unsafe {
181                 let new_size = new_layout.size();
182
183                 // `realloc` probably checks for `new_size >= old_layout.size()` or something similar.
184                 intrinsics::assume(new_size >= old_layout.size());
185
186                 let raw_ptr = realloc(ptr.as_ptr(), old_layout, new_size);
187                 let ptr = NonNull::new(raw_ptr).ok_or(AllocError)?;
188                 if zeroed {
189                     raw_ptr.add(old_size).write_bytes(0, new_size - old_size);
190                 }
191                 Ok(NonNull::slice_from_raw_parts(ptr, new_size))
192             },
193
194             // SAFETY: because `new_layout.size()` must be greater than or equal to `old_size`,
195             // both the old and new memory allocation are valid for reads and writes for `old_size`
196             // bytes. Also, because the old allocation wasn't yet deallocated, it cannot overlap
197             // `new_ptr`. Thus, the call to `copy_nonoverlapping` is safe. The safety contract
198             // for `dealloc` must be upheld by the caller.
199             old_size => unsafe {
200                 let new_ptr = self.alloc_impl(new_layout, zeroed)?;
201                 ptr::copy_nonoverlapping(ptr.as_ptr(), new_ptr.as_mut_ptr(), old_size);
202                 self.dealloc(ptr, old_layout);
203                 Ok(new_ptr)
204             },
205         }
206     }
207 }
208
209 #[unstable(feature = "allocator_api", issue = "32838")]
210 unsafe impl AllocRef for Global {
211     #[inline]
212     fn alloc(&self, layout: Layout) -> Result<NonNull<[u8]>, AllocError> {
213         self.alloc_impl(layout, false)
214     }
215
216     #[inline]
217     fn alloc_zeroed(&self, layout: Layout) -> Result<NonNull<[u8]>, AllocError> {
218         self.alloc_impl(layout, true)
219     }
220
221     #[inline]
222     unsafe fn dealloc(&self, ptr: NonNull<u8>, layout: Layout) {
223         if layout.size() != 0 {
224             // SAFETY: `layout` is non-zero in size,
225             // other conditions must be upheld by the caller
226             unsafe { dealloc(ptr.as_ptr(), layout) }
227         }
228     }
229
230     #[inline]
231     unsafe fn grow(
232         &self,
233         ptr: NonNull<u8>,
234         old_layout: Layout,
235         new_layout: Layout,
236     ) -> Result<NonNull<[u8]>, AllocError> {
237         // SAFETY: all conditions must be upheld by the caller
238         unsafe { self.grow_impl(ptr, old_layout, new_layout, false) }
239     }
240
241     #[inline]
242     unsafe fn grow_zeroed(
243         &self,
244         ptr: NonNull<u8>,
245         old_layout: Layout,
246         new_layout: Layout,
247     ) -> Result<NonNull<[u8]>, AllocError> {
248         // SAFETY: all conditions must be upheld by the caller
249         unsafe { self.grow_impl(ptr, old_layout, new_layout, true) }
250     }
251
252     #[inline]
253     unsafe fn shrink(
254         &self,
255         ptr: NonNull<u8>,
256         old_layout: Layout,
257         new_layout: Layout,
258     ) -> Result<NonNull<[u8]>, AllocError> {
259         debug_assert!(
260             new_layout.size() <= old_layout.size(),
261             "`new_layout.size()` must be smaller than or equal to `old_layout.size()`"
262         );
263
264         match new_layout.size() {
265             // SAFETY: conditions must be upheld by the caller
266             0 => unsafe {
267                 self.dealloc(ptr, old_layout);
268                 Ok(NonNull::slice_from_raw_parts(new_layout.dangling(), 0))
269             },
270
271             // SAFETY: `new_size` is non-zero. Other conditions must be upheld by the caller
272             new_size if old_layout.align() == new_layout.align() => unsafe {
273                 // `realloc` probably checks for `new_size <= old_layout.size()` or something similar.
274                 intrinsics::assume(new_size <= old_layout.size());
275
276                 let raw_ptr = realloc(ptr.as_ptr(), old_layout, new_size);
277                 let ptr = NonNull::new(raw_ptr).ok_or(AllocError)?;
278                 Ok(NonNull::slice_from_raw_parts(ptr, new_size))
279             },
280
281             // SAFETY: because `new_size` must be smaller than or equal to `old_layout.size()`,
282             // both the old and new memory allocation are valid for reads and writes for `new_size`
283             // bytes. Also, because the old allocation wasn't yet deallocated, it cannot overlap
284             // `new_ptr`. Thus, the call to `copy_nonoverlapping` is safe. The safety contract
285             // for `dealloc` must be upheld by the caller.
286             new_size => unsafe {
287                 let new_ptr = self.alloc(new_layout)?;
288                 ptr::copy_nonoverlapping(ptr.as_ptr(), new_ptr.as_mut_ptr(), new_size);
289                 self.dealloc(ptr, old_layout);
290                 Ok(new_ptr)
291             },
292         }
293     }
294 }
295
296 /// The allocator for unique pointers.
297 // This function must not unwind. If it does, MIR codegen will fail.
298 #[cfg(not(test))]
299 #[lang = "exchange_malloc"]
300 #[inline]
301 unsafe fn exchange_malloc(size: usize, align: usize) -> *mut u8 {
302     let layout = unsafe { Layout::from_size_align_unchecked(size, align) };
303     match Global.alloc(layout) {
304         Ok(ptr) => ptr.as_mut_ptr(),
305         Err(_) => handle_alloc_error(layout),
306     }
307 }
308
309 #[cfg_attr(not(test), lang = "box_free")]
310 #[inline]
311 // This signature has to be the same as `Box`, otherwise an ICE will happen.
312 // When an additional parameter to `Box` is added (like `A: AllocRef`), this has to be added here as
313 // well.
314 // For example if `Box` is changed to  `struct Box<T: ?Sized, A: AllocRef>(Unique<T>, A)`,
315 // this function has to be changed to `fn box_free<T: ?Sized, A: AllocRef>(Unique<T>, A)` as well.
316 pub(crate) unsafe fn box_free<T: ?Sized>(ptr: Unique<T>) {
317     unsafe {
318         let size = size_of_val(ptr.as_ref());
319         let align = min_align_of_val(ptr.as_ref());
320         let layout = Layout::from_size_align_unchecked(size, align);
321         Global.dealloc(ptr.cast().into(), layout)
322     }
323 }
324
325 // # Allocation error handler
326
327 extern "Rust" {
328     // This is the magic symbol to call the global alloc error handler.  rustc generates
329     // it to call `__rg_oom` if there is a `#[alloc_error_handler]`, or to call the
330     // default implementations below (`__rdl_oom`) otherwise.
331     #[rustc_allocator_nounwind]
332     fn __rust_alloc_error_handler(size: usize, align: usize) -> !;
333 }
334
335 /// Abort on memory allocation error or failure.
336 ///
337 /// Callers of memory allocation APIs wishing to abort computation
338 /// in response to an allocation error are encouraged to call this function,
339 /// rather than directly invoking `panic!` or similar.
340 ///
341 /// The default behavior of this function is to print a message to standard error
342 /// and abort the process.
343 /// It can be replaced with [`set_alloc_error_hook`] and [`take_alloc_error_hook`].
344 ///
345 /// [`set_alloc_error_hook`]: ../../std/alloc/fn.set_alloc_error_hook.html
346 /// [`take_alloc_error_hook`]: ../../std/alloc/fn.take_alloc_error_hook.html
347 #[stable(feature = "global_alloc", since = "1.28.0")]
348 #[cfg(not(any(test, bootstrap)))]
349 #[rustc_allocator_nounwind]
350 pub fn handle_alloc_error(layout: Layout) -> ! {
351     unsafe {
352         __rust_alloc_error_handler(layout.size(), layout.align());
353     }
354 }
355
356 // For alloc test `std::alloc::handle_alloc_error` can be used directly.
357 #[cfg(test)]
358 pub use std::alloc::handle_alloc_error;
359
360 // In stage0 (bootstrap) `__rust_alloc_error_handler`,
361 // might not be generated yet, because an old compiler is used,
362 // so use the old direct call.
363 #[cfg(all(bootstrap, not(test)))]
364 #[stable(feature = "global_alloc", since = "1.28.0")]
365 #[doc(hidden)]
366 #[rustc_allocator_nounwind]
367 pub fn handle_alloc_error(layout: Layout) -> ! {
368     extern "Rust" {
369         #[lang = "oom"]
370         fn oom_impl(layout: Layout) -> !;
371     }
372     unsafe { oom_impl(layout) }
373 }
374
375 #[cfg(not(any(test, bootstrap)))]
376 #[doc(hidden)]
377 #[allow(unused_attributes)]
378 #[unstable(feature = "alloc_internals", issue = "none")]
379 pub mod __alloc_error_handler {
380     use crate::alloc::Layout;
381
382     // called via generated `__rust_alloc_error_handler`
383
384     // if there is no `#[alloc_error_handler]`
385     #[rustc_std_internal_symbol]
386     pub unsafe extern "C" fn __rdl_oom(size: usize, _align: usize) -> ! {
387         panic!("memory allocation of {} bytes failed", size)
388     }
389
390     // if there is a `#[alloc_error_handler]`
391     #[rustc_std_internal_symbol]
392     pub unsafe extern "C" fn __rg_oom(size: usize, align: usize) -> ! {
393         let layout = unsafe { Layout::from_size_align_unchecked(size, align) };
394         extern "Rust" {
395             #[lang = "oom"]
396             fn oom_impl(layout: Layout) -> !;
397         }
398         unsafe { oom_impl(layout) }
399     }
400 }