]> git.lizzy.rs Git - rust.git/blob - library/core/src/alloc/global.rs
Document that heap allocations are not guaranteed to happen, even if explicitly perfo...
[rust.git] / library / core / src / alloc / global.rs
1 use crate::alloc::Layout;
2 use crate::cmp;
3 use crate::ptr;
4
5 /// A memory allocator that can be registered as the standard library’s default
6 /// through the `#[global_allocator]` attribute.
7 ///
8 /// Some of the methods require that a memory block be *currently
9 /// allocated* via an allocator. This means that:
10 ///
11 /// * the starting address for that memory block was previously
12 ///   returned by a previous call to an allocation method
13 ///   such as `alloc`, and
14 ///
15 /// * the memory block has not been subsequently deallocated, where
16 ///   blocks are deallocated either by being passed to a deallocation
17 ///   method such as `dealloc` or by being
18 ///   passed to a reallocation method that returns a non-null pointer.
19 ///
20 ///
21 /// # Example
22 ///
23 /// ```no_run
24 /// use std::alloc::{GlobalAlloc, Layout, alloc};
25 /// use std::ptr::null_mut;
26 ///
27 /// struct MyAllocator;
28 ///
29 /// unsafe impl GlobalAlloc for MyAllocator {
30 ///     unsafe fn alloc(&self, _layout: Layout) -> *mut u8 { null_mut() }
31 ///     unsafe fn dealloc(&self, _ptr: *mut u8, _layout: Layout) {}
32 /// }
33 ///
34 /// #[global_allocator]
35 /// static A: MyAllocator = MyAllocator;
36 ///
37 /// fn main() {
38 ///     unsafe {
39 ///         assert!(alloc(Layout::new::<u32>()).is_null())
40 ///     }
41 /// }
42 /// ```
43 ///
44 /// # Safety
45 ///
46 /// The `GlobalAlloc` trait is an `unsafe` trait for a number of reasons, and
47 /// implementors must ensure that they adhere to these contracts:
48 ///
49 /// * It's undefined behavior if global allocators unwind. This restriction may
50 ///   be lifted in the future, but currently a panic from any of these
51 ///   functions may lead to memory unsafety.
52 ///
53 /// * `Layout` queries and calculations in general must be correct. Callers of
54 ///   this trait are allowed to rely on the contracts defined on each method,
55 ///   and implementors must ensure such contracts remain true.
56 ///
57 /// * You may not rely on allocations actually happening, even if there are explicit
58 ///   heap allocations in the source. The optimizer may detect allocation/deallocation
59 ///   pairs that it can instead move to stack allocations/deallocations and thus never
60 ///   invoke the allocator here.
61 ///   More concretely, the following code example is unsound, irrespective of whether your
62 ///   custom allocator allows counting how many allocations have happened.
63 ///
64 ///   ```rust,ignore
65 ///   drop(Box::new(42));
66 ///   let number_of_heap_allocs = /* call private allocator API */;
67 ///   unsafe { std::intrinsics::assume(number_of_heap_allocs > 0); }
68 ///   ```
69 #[stable(feature = "global_alloc", since = "1.28.0")]
70 pub unsafe trait GlobalAlloc {
71     /// Allocate memory as described by the given `layout`.
72     ///
73     /// Returns a pointer to newly-allocated memory,
74     /// or null to indicate allocation failure.
75     ///
76     /// # Safety
77     ///
78     /// This function is unsafe because undefined behavior can result
79     /// if the caller does not ensure that `layout` has non-zero size.
80     ///
81     /// (Extension subtraits might provide more specific bounds on
82     /// behavior, e.g., guarantee a sentinel address or a null pointer
83     /// in response to a zero-size allocation request.)
84     ///
85     /// The allocated block of memory may or may not be initialized.
86     ///
87     /// # Errors
88     ///
89     /// Returning a null pointer indicates that either memory is exhausted
90     /// or `layout` does not meet this allocator's size or alignment constraints.
91     ///
92     /// Implementations are encouraged to return null on memory
93     /// exhaustion rather than aborting, but this is not
94     /// a strict requirement. (Specifically: it is *legal* to
95     /// implement this trait atop an underlying native allocation
96     /// library that aborts on memory exhaustion.)
97     ///
98     /// Clients wishing to abort computation in response to an
99     /// allocation error are encouraged to call the [`handle_alloc_error`] function,
100     /// rather than directly invoking `panic!` or similar.
101     ///
102     /// [`handle_alloc_error`]: ../../alloc/alloc/fn.handle_alloc_error.html
103     #[stable(feature = "global_alloc", since = "1.28.0")]
104     unsafe fn alloc(&self, layout: Layout) -> *mut u8;
105
106     /// Deallocate the block of memory at the given `ptr` pointer with the given `layout`.
107     ///
108     /// # Safety
109     ///
110     /// This function is unsafe because undefined behavior can result
111     /// if the caller does not ensure all of the following:
112     ///
113     /// * `ptr` must denote a block of memory currently allocated via
114     ///   this allocator,
115     ///
116     /// * `layout` must be the same layout that was used
117     ///   to allocate that block of memory,
118     #[stable(feature = "global_alloc", since = "1.28.0")]
119     unsafe fn dealloc(&self, ptr: *mut u8, layout: Layout);
120
121     /// Behaves like `alloc`, but also ensures that the contents
122     /// are set to zero before being returned.
123     ///
124     /// # Safety
125     ///
126     /// This function is unsafe for the same reasons that `alloc` is.
127     /// However the allocated block of memory is guaranteed to be initialized.
128     ///
129     /// # Errors
130     ///
131     /// Returning a null pointer indicates that either memory is exhausted
132     /// or `layout` does not meet allocator's size or alignment constraints,
133     /// just as in `alloc`.
134     ///
135     /// Clients wishing to abort computation in response to an
136     /// allocation error are encouraged to call the [`handle_alloc_error`] function,
137     /// rather than directly invoking `panic!` or similar.
138     ///
139     /// [`handle_alloc_error`]: ../../alloc/alloc/fn.handle_alloc_error.html
140     #[stable(feature = "global_alloc", since = "1.28.0")]
141     unsafe fn alloc_zeroed(&self, layout: Layout) -> *mut u8 {
142         let size = layout.size();
143         // SAFETY: the safety contract for `alloc` must be upheld by the caller.
144         let ptr = unsafe { self.alloc(layout) };
145         if !ptr.is_null() {
146             // SAFETY: as allocation succeeded, the region from `ptr`
147             // of size `size` is guaranteed to be valid for writes.
148             unsafe { ptr::write_bytes(ptr, 0, size) };
149         }
150         ptr
151     }
152
153     /// Shrink or grow a block of memory to the given `new_size`.
154     /// The block is described by the given `ptr` pointer and `layout`.
155     ///
156     /// If this returns a non-null pointer, then ownership of the memory block
157     /// referenced by `ptr` has been transferred to this allocator.
158     /// The memory may or may not have been deallocated,
159     /// and should be considered unusable (unless of course it was
160     /// transferred back to the caller again via the return value of
161     /// this method). The new memory block is allocated with `layout`, but
162     /// with the `size` updated to `new_size`.
163     ///
164     /// If this method returns null, then ownership of the memory
165     /// block has not been transferred to this allocator, and the
166     /// contents of the memory block are unaltered.
167     ///
168     /// # Safety
169     ///
170     /// This function is unsafe because undefined behavior can result
171     /// if the caller does not ensure all of the following:
172     ///
173     /// * `ptr` must be currently allocated via this allocator,
174     ///
175     /// * `layout` must be the same layout that was used
176     ///   to allocate that block of memory,
177     ///
178     /// * `new_size` must be greater than zero.
179     ///
180     /// * `new_size`, when rounded up to the nearest multiple of `layout.align()`,
181     ///   must not overflow (i.e., the rounded value must be less than `usize::MAX`).
182     ///
183     /// (Extension subtraits might provide more specific bounds on
184     /// behavior, e.g., guarantee a sentinel address or a null pointer
185     /// in response to a zero-size allocation request.)
186     ///
187     /// # Errors
188     ///
189     /// Returns null if the new layout does not meet the size
190     /// and alignment constraints of the allocator, or if reallocation
191     /// otherwise fails.
192     ///
193     /// Implementations are encouraged to return null on memory
194     /// exhaustion rather than panicking or aborting, but this is not
195     /// a strict requirement. (Specifically: it is *legal* to
196     /// implement this trait atop an underlying native allocation
197     /// library that aborts on memory exhaustion.)
198     ///
199     /// Clients wishing to abort computation in response to a
200     /// reallocation error are encouraged to call the [`handle_alloc_error`] function,
201     /// rather than directly invoking `panic!` or similar.
202     ///
203     /// [`handle_alloc_error`]: ../../alloc/alloc/fn.handle_alloc_error.html
204     #[stable(feature = "global_alloc", since = "1.28.0")]
205     unsafe fn realloc(&self, ptr: *mut u8, layout: Layout, new_size: usize) -> *mut u8 {
206         // SAFETY: the caller must ensure that the `new_size` does not overflow.
207         // `layout.align()` comes from a `Layout` and is thus guaranteed to be valid.
208         let new_layout = unsafe { Layout::from_size_align_unchecked(new_size, layout.align()) };
209         // SAFETY: the caller must ensure that `new_layout` is greater than zero.
210         let new_ptr = unsafe { self.alloc(new_layout) };
211         if !new_ptr.is_null() {
212             // SAFETY: the previously allocated block cannot overlap the newly allocated block.
213             // The safety contract for `dealloc` must be upheld by the caller.
214             unsafe {
215                 ptr::copy_nonoverlapping(ptr, new_ptr, cmp::min(layout.size(), new_size));
216                 self.dealloc(ptr, layout);
217             }
218         }
219         new_ptr
220     }
221 }