]> git.lizzy.rs Git - rust.git/blob - library/std/src/alloc.rs
Auto merge of #79115 - cuviper:rust-description, r=Mark-Simulacrum
[rust.git] / library / std / src / alloc.rs
1 //! Memory allocation APIs
2 //!
3 //! In a given program, the standard library has one “global” memory allocator
4 //! that is used for example by `Box<T>` and `Vec<T>`.
5 //!
6 //! Currently the default global allocator is unspecified. Libraries, however,
7 //! like `cdylib`s and `staticlib`s are guaranteed to use the [`System`] by
8 //! default.
9 //!
10 //! # The `#[global_allocator]` attribute
11 //!
12 //! This attribute allows configuring the choice of global allocator.
13 //! You can use this to implement a completely custom global allocator
14 //! to route all default allocation requests to a custom object.
15 //!
16 //! ```rust
17 //! use std::alloc::{GlobalAlloc, System, Layout};
18 //!
19 //! struct MyAllocator;
20 //!
21 //! unsafe impl GlobalAlloc for MyAllocator {
22 //!     unsafe fn alloc(&self, layout: Layout) -> *mut u8 {
23 //!         System.alloc(layout)
24 //!     }
25 //!
26 //!     unsafe fn dealloc(&self, ptr: *mut u8, layout: Layout) {
27 //!         System.dealloc(ptr, layout)
28 //!     }
29 //! }
30 //!
31 //! #[global_allocator]
32 //! static GLOBAL: MyAllocator = MyAllocator;
33 //!
34 //! fn main() {
35 //!     // This `Vec` will allocate memory through `GLOBAL` above
36 //!     let mut v = Vec::new();
37 //!     v.push(1);
38 //! }
39 //! ```
40 //!
41 //! The attribute is used on a `static` item whose type implements the
42 //! [`GlobalAlloc`] trait. This type can be provided by an external library:
43 //!
44 //! ```rust,ignore (demonstrates crates.io usage)
45 //! extern crate jemallocator;
46 //!
47 //! use jemallocator::Jemalloc;
48 //!
49 //! #[global_allocator]
50 //! static GLOBAL: Jemalloc = Jemalloc;
51 //!
52 //! fn main() {}
53 //! ```
54 //!
55 //! The `#[global_allocator]` can only be used once in a crate
56 //! or its recursive dependencies.
57
58 #![deny(unsafe_op_in_unsafe_fn)]
59 #![stable(feature = "alloc_module", since = "1.28.0")]
60
61 use core::intrinsics;
62 use core::ptr::NonNull;
63 use core::sync::atomic::{AtomicPtr, Ordering};
64 use core::{mem, ptr};
65
66 use crate::sys_common::util::dumb_print;
67
68 #[stable(feature = "alloc_module", since = "1.28.0")]
69 #[doc(inline)]
70 pub use alloc_crate::alloc::*;
71
72 /// The default memory allocator provided by the operating system.
73 ///
74 /// This is based on `malloc` on Unix platforms and `HeapAlloc` on Windows,
75 /// plus related functions.
76 ///
77 /// This type implements the `GlobalAlloc` trait and Rust programs by default
78 /// work as if they had this definition:
79 ///
80 /// ```rust
81 /// use std::alloc::System;
82 ///
83 /// #[global_allocator]
84 /// static A: System = System;
85 ///
86 /// fn main() {
87 ///     let a = Box::new(4); // Allocates from the system allocator.
88 ///     println!("{}", a);
89 /// }
90 /// ```
91 ///
92 /// You can also define your own wrapper around `System` if you'd like, such as
93 /// keeping track of the number of all bytes allocated:
94 ///
95 /// ```rust
96 /// use std::alloc::{System, GlobalAlloc, Layout};
97 /// use std::sync::atomic::{AtomicUsize, Ordering::SeqCst};
98 ///
99 /// struct Counter;
100 ///
101 /// static ALLOCATED: AtomicUsize = AtomicUsize::new(0);
102 ///
103 /// unsafe impl GlobalAlloc for Counter {
104 ///     unsafe fn alloc(&self, layout: Layout) -> *mut u8 {
105 ///         let ret = System.alloc(layout);
106 ///         if !ret.is_null() {
107 ///             ALLOCATED.fetch_add(layout.size(), SeqCst);
108 ///         }
109 ///         return ret
110 ///     }
111 ///
112 ///     unsafe fn dealloc(&self, ptr: *mut u8, layout: Layout) {
113 ///         System.dealloc(ptr, layout);
114 ///         ALLOCATED.fetch_sub(layout.size(), SeqCst);
115 ///     }
116 /// }
117 ///
118 /// #[global_allocator]
119 /// static A: Counter = Counter;
120 ///
121 /// fn main() {
122 ///     println!("allocated bytes before main: {}", ALLOCATED.load(SeqCst));
123 /// }
124 /// ```
125 ///
126 /// It can also be used directly to allocate memory independently of whatever
127 /// global allocator has been selected for a Rust program. For example if a Rust
128 /// program opts in to using jemalloc as the global allocator, `System` will
129 /// still allocate memory using `malloc` and `HeapAlloc`.
130 #[stable(feature = "alloc_system_type", since = "1.28.0")]
131 #[derive(Debug, Default, Copy, Clone)]
132 pub struct System;
133
134 impl System {
135     #[inline]
136     fn alloc_impl(&self, layout: Layout, zeroed: bool) -> Result<NonNull<[u8]>, AllocError> {
137         match layout.size() {
138             0 => Ok(NonNull::slice_from_raw_parts(layout.dangling(), 0)),
139             // SAFETY: `layout` is non-zero in size,
140             size => unsafe {
141                 let raw_ptr = if zeroed {
142                     GlobalAlloc::alloc_zeroed(self, layout)
143                 } else {
144                     GlobalAlloc::alloc(self, layout)
145                 };
146                 let ptr = NonNull::new(raw_ptr).ok_or(AllocError)?;
147                 Ok(NonNull::slice_from_raw_parts(ptr, size))
148             },
149         }
150     }
151
152     // SAFETY: Same as `AllocRef::grow`
153     #[inline]
154     unsafe fn grow_impl(
155         &self,
156         ptr: NonNull<u8>,
157         old_layout: Layout,
158         new_layout: Layout,
159         zeroed: bool,
160     ) -> Result<NonNull<[u8]>, AllocError> {
161         debug_assert!(
162             new_layout.size() >= old_layout.size(),
163             "`new_layout.size()` must be greater than or equal to `old_layout.size()`"
164         );
165
166         match old_layout.size() {
167             0 => self.alloc_impl(new_layout, zeroed),
168
169             // SAFETY: `new_size` is non-zero as `old_size` is greater than or equal to `new_size`
170             // as required by safety conditions. Other conditions must be upheld by the caller
171             old_size if old_layout.align() == new_layout.align() => unsafe {
172                 let new_size = new_layout.size();
173
174                 // `realloc` probably checks for `new_size >= old_layout.size()` or something similar.
175                 intrinsics::assume(new_size >= old_layout.size());
176
177                 let raw_ptr = GlobalAlloc::realloc(self, ptr.as_ptr(), old_layout, new_size);
178                 let ptr = NonNull::new(raw_ptr).ok_or(AllocError)?;
179                 if zeroed {
180                     raw_ptr.add(old_size).write_bytes(0, new_size - old_size);
181                 }
182                 Ok(NonNull::slice_from_raw_parts(ptr, new_size))
183             },
184
185             // SAFETY: because `new_layout.size()` must be greater than or equal to `old_size`,
186             // both the old and new memory allocation are valid for reads and writes for `old_size`
187             // bytes. Also, because the old allocation wasn't yet deallocated, it cannot overlap
188             // `new_ptr`. Thus, the call to `copy_nonoverlapping` is safe. The safety contract
189             // for `dealloc` must be upheld by the caller.
190             old_size => unsafe {
191                 let new_ptr = self.alloc_impl(new_layout, zeroed)?;
192                 ptr::copy_nonoverlapping(ptr.as_ptr(), new_ptr.as_mut_ptr(), old_size);
193                 AllocRef::dealloc(&self, ptr, old_layout);
194                 Ok(new_ptr)
195             },
196         }
197     }
198 }
199
200 // The AllocRef impl checks the layout size to be non-zero and forwards to the GlobalAlloc impl,
201 // which is in `std::sys::*::alloc`.
202 #[unstable(feature = "allocator_api", issue = "32838")]
203 unsafe impl AllocRef for System {
204     #[inline]
205     fn alloc(&self, layout: Layout) -> Result<NonNull<[u8]>, AllocError> {
206         self.alloc_impl(layout, false)
207     }
208
209     #[inline]
210     fn alloc_zeroed(&self, layout: Layout) -> Result<NonNull<[u8]>, AllocError> {
211         self.alloc_impl(layout, true)
212     }
213
214     #[inline]
215     unsafe fn dealloc(&self, ptr: NonNull<u8>, layout: Layout) {
216         if layout.size() != 0 {
217             // SAFETY: `layout` is non-zero in size,
218             // other conditions must be upheld by the caller
219             unsafe { GlobalAlloc::dealloc(self, ptr.as_ptr(), layout) }
220         }
221     }
222
223     #[inline]
224     unsafe fn grow(
225         &self,
226         ptr: NonNull<u8>,
227         old_layout: Layout,
228         new_layout: Layout,
229     ) -> Result<NonNull<[u8]>, AllocError> {
230         // SAFETY: all conditions must be upheld by the caller
231         unsafe { self.grow_impl(ptr, old_layout, new_layout, false) }
232     }
233
234     #[inline]
235     unsafe fn grow_zeroed(
236         &self,
237         ptr: NonNull<u8>,
238         old_layout: Layout,
239         new_layout: Layout,
240     ) -> Result<NonNull<[u8]>, AllocError> {
241         // SAFETY: all conditions must be upheld by the caller
242         unsafe { self.grow_impl(ptr, old_layout, new_layout, true) }
243     }
244
245     #[inline]
246     unsafe fn shrink(
247         &self,
248         ptr: NonNull<u8>,
249         old_layout: Layout,
250         new_layout: Layout,
251     ) -> Result<NonNull<[u8]>, AllocError> {
252         debug_assert!(
253             new_layout.size() <= old_layout.size(),
254             "`new_layout.size()` must be smaller than or equal to `old_layout.size()`"
255         );
256
257         match new_layout.size() {
258             // SAFETY: conditions must be upheld by the caller
259             0 => unsafe {
260                 AllocRef::dealloc(&self, ptr, old_layout);
261                 Ok(NonNull::slice_from_raw_parts(new_layout.dangling(), 0))
262             },
263
264             // SAFETY: `new_size` is non-zero. Other conditions must be upheld by the caller
265             new_size if old_layout.align() == new_layout.align() => unsafe {
266                 // `realloc` probably checks for `new_size <= old_layout.size()` or something similar.
267                 intrinsics::assume(new_size <= old_layout.size());
268
269                 let raw_ptr = GlobalAlloc::realloc(self, ptr.as_ptr(), old_layout, new_size);
270                 let ptr = NonNull::new(raw_ptr).ok_or(AllocError)?;
271                 Ok(NonNull::slice_from_raw_parts(ptr, new_size))
272             },
273
274             // SAFETY: because `new_size` must be smaller than or equal to `old_layout.size()`,
275             // both the old and new memory allocation are valid for reads and writes for `new_size`
276             // bytes. Also, because the old allocation wasn't yet deallocated, it cannot overlap
277             // `new_ptr`. Thus, the call to `copy_nonoverlapping` is safe. The safety contract
278             // for `dealloc` must be upheld by the caller.
279             new_size => unsafe {
280                 let new_ptr = AllocRef::alloc(&self, new_layout)?;
281                 ptr::copy_nonoverlapping(ptr.as_ptr(), new_ptr.as_mut_ptr(), new_size);
282                 AllocRef::dealloc(&self, ptr, old_layout);
283                 Ok(new_ptr)
284             },
285         }
286     }
287 }
288
289 static HOOK: AtomicPtr<()> = AtomicPtr::new(ptr::null_mut());
290
291 /// Registers a custom allocation error hook, replacing any that was previously registered.
292 ///
293 /// The allocation error hook is invoked when an infallible memory allocation fails, before
294 /// the runtime aborts. The default hook prints a message to standard error,
295 /// but this behavior can be customized with the [`set_alloc_error_hook`] and
296 /// [`take_alloc_error_hook`] functions.
297 ///
298 /// The hook is provided with a `Layout` struct which contains information
299 /// about the allocation that failed.
300 ///
301 /// The allocation error hook is a global resource.
302 #[unstable(feature = "alloc_error_hook", issue = "51245")]
303 pub fn set_alloc_error_hook(hook: fn(Layout)) {
304     HOOK.store(hook as *mut (), Ordering::SeqCst);
305 }
306
307 /// Unregisters the current allocation error hook, returning it.
308 ///
309 /// *See also the function [`set_alloc_error_hook`].*
310 ///
311 /// If no custom hook is registered, the default hook will be returned.
312 #[unstable(feature = "alloc_error_hook", issue = "51245")]
313 pub fn take_alloc_error_hook() -> fn(Layout) {
314     let hook = HOOK.swap(ptr::null_mut(), Ordering::SeqCst);
315     if hook.is_null() { default_alloc_error_hook } else { unsafe { mem::transmute(hook) } }
316 }
317
318 fn default_alloc_error_hook(layout: Layout) {
319     dumb_print(format_args!("memory allocation of {} bytes failed\n", layout.size()));
320 }
321
322 #[cfg(not(test))]
323 #[doc(hidden)]
324 #[alloc_error_handler]
325 #[unstable(feature = "alloc_internals", issue = "none")]
326 pub fn rust_oom(layout: Layout) -> ! {
327     let hook = HOOK.load(Ordering::SeqCst);
328     let hook: fn(Layout) =
329         if hook.is_null() { default_alloc_error_hook } else { unsafe { mem::transmute(hook) } };
330     hook(layout);
331     crate::process::abort()
332 }
333
334 #[cfg(not(test))]
335 #[doc(hidden)]
336 #[allow(unused_attributes)]
337 #[unstable(feature = "alloc_internals", issue = "none")]
338 pub mod __default_lib_allocator {
339     use super::{GlobalAlloc, Layout, System};
340     // These magic symbol names are used as a fallback for implementing the
341     // `__rust_alloc` etc symbols (see `src/liballoc/alloc.rs`) when there is
342     // no `#[global_allocator]` attribute.
343
344     // for symbol names src/librustc_ast/expand/allocator.rs
345     // for signatures src/librustc_allocator/lib.rs
346
347     // linkage directives are provided as part of the current compiler allocator
348     // ABI
349
350     #[rustc_std_internal_symbol]
351     pub unsafe extern "C" fn __rdl_alloc(size: usize, align: usize) -> *mut u8 {
352         // SAFETY: see the guarantees expected by `Layout::from_size_align` and
353         // `GlobalAlloc::alloc`.
354         unsafe {
355             let layout = Layout::from_size_align_unchecked(size, align);
356             System.alloc(layout)
357         }
358     }
359
360     #[rustc_std_internal_symbol]
361     pub unsafe extern "C" fn __rdl_dealloc(ptr: *mut u8, size: usize, align: usize) {
362         // SAFETY: see the guarantees expected by `Layout::from_size_align` and
363         // `GlobalAlloc::dealloc`.
364         unsafe { System.dealloc(ptr, Layout::from_size_align_unchecked(size, align)) }
365     }
366
367     #[rustc_std_internal_symbol]
368     pub unsafe extern "C" fn __rdl_realloc(
369         ptr: *mut u8,
370         old_size: usize,
371         align: usize,
372         new_size: usize,
373     ) -> *mut u8 {
374         // SAFETY: see the guarantees expected by `Layout::from_size_align` and
375         // `GlobalAlloc::realloc`.
376         unsafe {
377             let old_layout = Layout::from_size_align_unchecked(old_size, align);
378             System.realloc(ptr, old_layout, new_size)
379         }
380     }
381
382     #[rustc_std_internal_symbol]
383     pub unsafe extern "C" fn __rdl_alloc_zeroed(size: usize, align: usize) -> *mut u8 {
384         // SAFETY: see the guarantees expected by `Layout::from_size_align` and
385         // `GlobalAlloc::alloc_zeroed`.
386         unsafe {
387             let layout = Layout::from_size_align_unchecked(size, align);
388             System.alloc_zeroed(layout)
389         }
390     }
391 }