Skip to content

Commit 0b644e4

Browse files
committed
Auto merge of #79045 - oli-obk:dont_rely_on_alloc_happening_for_soundness, r=TimDiekmann
Document that heap allocations are not guaranteed to happen, even if explicitly performed in the code cc `@RalfJung`
2 parents 89524d0 + efcd8a9 commit 0b644e4

File tree

1 file changed

+21
-0
lines changed

1 file changed

+21
-0
lines changed

library/core/src/alloc/global.rs

+21
Original file line numberDiff line numberDiff line change
@@ -53,6 +53,27 @@ use crate::ptr;
5353
/// * `Layout` queries and calculations in general must be correct. Callers of
5454
/// this trait are allowed to rely on the contracts defined on each method,
5555
/// 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 unused allocations that it can either
59+
/// eliminate entirely or move to the stack and thus never invoke the allocator. The
60+
/// optimizer may further assume that allocation is infallible, so code that used to fail due
61+
/// to allocator failures may now suddenly work because the optimizer worked around the
62+
/// need for an allocation. More concretely, the following code example is unsound, irrespective
63+
/// of whether your custom allocator allows counting how many allocations have happened.
64+
///
65+
/// ```rust,ignore (unsound and has placeholders)
66+
/// drop(Box::new(42));
67+
/// let number_of_heap_allocs = /* call private allocator API */;
68+
/// unsafe { std::intrinsics::assume(number_of_heap_allocs > 0); }
69+
/// ```
70+
///
71+
/// Note that the optimizations mentioned above are not the only
72+
/// optimization that can be applied. You may generally not rely on heap allocations
73+
/// happening if they can be removed without changing program behavior.
74+
/// Whether allocations happen or not is not part of the program behavior, even if it
75+
/// could be detected via an allocator that tracks allocations by printing or otherwise
76+
/// having side effects.
5677
#[stable(feature = "global_alloc", since = "1.28.0")]
5778
pub unsafe trait GlobalAlloc {
5879
/// Allocate memory as described by the given `layout`.

0 commit comments

Comments
 (0)