core/ub_checks.rs
1//! Provides the [`assert_unsafe_precondition`] macro as well as some utility functions that cover
2//! common preconditions.
3
4use crate::intrinsics::{self, const_eval_select};
5
6/// Checks that the preconditions of an unsafe function are followed.
7///
8/// The check is enabled at runtime if debug assertions are enabled when the
9/// caller is monomorphized. In const-eval/Miri checks implemented with this
10/// macro for language UB are always ignored.
11///
12/// This macro should be called as
13/// `assert_unsafe_precondition!(check_{library,language}_ub, "message", (ident: type = expr, ident: type = expr) => check_expr)`
14/// where each `expr` will be evaluated and passed in as function argument `ident: type`. Then all
15/// those arguments are passed to a function with the body `check_expr`.
16/// Pick `check_language_ub` when this is guarding a violation of language UB, i.e., immediate UB
17/// according to the Rust Abstract Machine. Pick `check_library_ub` when this is guarding a violation
18/// of a documented library precondition that does not *immediately* lead to language UB.
19///
20/// If `check_library_ub` is used but the check is actually guarding language UB, the check will
21/// slow down const-eval/Miri and we'll get the panic message instead of the interpreter's nice
22/// diagnostic, but our ability to detect UB is unchanged.
23/// But if `check_language_ub` is used when the check is actually for library UB, the check is
24/// omitted in const-eval/Miri and thus UB might occur undetected. Even if we eventually execute
25/// language UB which relies on the library UB, the backtrace Miri reports may be far removed from
26/// original cause.
27///
28/// These checks are behind a condition which is evaluated at codegen time, not expansion time like
29/// [`debug_assert`]. This means that a standard library built with optimizations and debug
30/// assertions disabled will have these checks optimized out of its monomorphizations, but if a
31/// caller of the standard library has debug assertions enabled and monomorphizes an expansion of
32/// this macro, that monomorphization will contain the check.
33///
34/// Since these checks cannot be optimized out in MIR, some care must be taken in both call and
35/// implementation to mitigate their compile-time overhead. Calls to this macro always expand to
36/// this structure:
37/// ```ignore (pseudocode)
38/// if ::core::intrinsics::check_language_ub() {
39/// precondition_check(args)
40/// }
41/// ```
42/// where `precondition_check` is monomorphic with the attributes `#[rustc_nounwind]`, `#[inline]` and
43/// `#[rustc_no_mir_inline]`. This combination of attributes ensures that the actual check logic is
44/// compiled only once and generates a minimal amount of IR because the check cannot be inlined in
45/// MIR, but *can* be inlined and fully optimized by a codegen backend.
46///
47/// Callers should avoid introducing any other `let` bindings or any code outside this macro in
48/// order to call it. Since the precompiled standard library is built with full debuginfo and these
49/// variables cannot be optimized out in MIR, an innocent-looking `let` can produce enough
50/// debuginfo to have a measurable compile-time impact on debug builds.
51#[macro_export]
52#[unstable(feature = "ub_checks", issue = "none")]
53#[allow_internal_unstable(coverage_attribute)]
54macro_rules! assert_unsafe_precondition {
55 ($kind:ident, $message:expr, ($($name:ident:$ty:ty = $arg:expr),*$(,)?) => $e:expr $(,)?) => {
56 {
57 // This check is inlineable, but not by the MIR inliner.
58 // The reason for this is that the MIR inliner is in an exceptionally bad position
59 // to think about whether or not to inline this. In MIR, this call is gated behind `debug_assertions`,
60 // which will codegen to `false` in release builds. Inlining the check would be wasted work in that case and
61 // would be bad for compile times.
62 //
63 // LLVM on the other hand sees the constant branch, so if it's `false`, it can immediately delete it without
64 // inlining the check. If it's `true`, it can inline it and get significantly better performance.
65 #[rustc_no_mir_inline]
66 #[inline]
67 #[rustc_nounwind]
68 #[track_caller]
69 #[ferrocene::annotation(
70 "This code cannot be covered because it causes an non-unwinding panic, which means it cannot be caught by any means in a test."
71 )]
72 const fn precondition_check($($name:$ty),*) {
73 if !$e {
74 let msg = concat!("unsafe precondition(s) violated: ", $message,
75 "\n\nThis indicates a bug in the program. \
76 This Undefined Behavior check is optional, and cannot be relied on for safety.");
77 ::core::panicking::panic_nounwind_fmt(::core::fmt::Arguments::from_str(msg), false);
78 }
79 }
80
81 if ::core::ub_checks::$kind() {
82 precondition_check($($arg,)*);
83 }
84 }
85 };
86}
87#[unstable(feature = "ub_checks", issue = "none")]
88pub use assert_unsafe_precondition;
89/// Checking library UB is always enabled when UB-checking is done
90/// (and we use a reexport so that there is no unnecessary wrapper function).
91#[unstable(feature = "ub_checks", issue = "none")]
92pub use intrinsics::ub_checks as check_library_ub;
93
94/// Determines whether we should check for language UB.
95///
96/// The intention is to not do that when running in the interpreter, as that one has its own
97/// language UB checks which generally produce better errors.
98#[inline]
99#[rustc_allow_const_fn_unstable(const_eval_select)]
100pub(crate) const fn check_language_ub() -> bool {
101 // Only used for UB checks so we may const_eval_select.
102 const_eval_select!(
103 @capture { } -> bool:
104 if const {
105 // Always disable UB checks.
106 false
107 } else {
108 // Disable UB checks in Miri.
109 !cfg!(miri)
110 }
111 ) && intrinsics::ub_checks()
112}
113
114/// Checks whether `ptr` is properly aligned with respect to the given alignment, and
115/// if `is_zst == false`, that `ptr` is not null.
116///
117/// In `const` this is approximate and can fail spuriously. It is primarily intended
118/// for `assert_unsafe_precondition!` with `check_language_ub`, in which case the
119/// check is anyway not executed in `const`.
120#[inline]
121#[rustc_allow_const_fn_unstable(const_eval_select)]
122pub(crate) const fn maybe_is_aligned_and_not_null(
123 ptr: *const (),
124 align: usize,
125 is_zst: bool,
126) -> bool {
127 // This is just for safety checks so we can const_eval_select.
128 maybe_is_aligned(ptr, align) && (is_zst || !ptr.is_null())
129}
130
131/// Checks whether `ptr` is properly aligned with respect to the given alignment.
132///
133/// In `const` this is approximate and can fail spuriously. It is primarily intended
134/// for `assert_unsafe_precondition!` with `check_language_ub`, in which case the
135/// check is anyway not executed in `const`.
136#[inline]
137#[rustc_allow_const_fn_unstable(const_eval_select)]
138pub(crate) const fn maybe_is_aligned(ptr: *const (), align: usize) -> bool {
139 // This is just for safety checks so we can const_eval_select.
140 const_eval_select!(
141 @capture { ptr: *const (), align: usize } -> bool:
142 if const {
143 true
144 } else {
145 ptr.is_aligned_to(align)
146 }
147 )
148}
149
150#[inline]
151pub(crate) const fn is_valid_allocation_size(size: usize, len: usize) -> bool {
152 let max_len = if size == 0 { usize::MAX } else { isize::MAX as usize / size };
153 len <= max_len
154}
155
156/// Checks whether the regions of memory starting at `src` and `dst` of size
157/// `count * size` do *not* overlap.
158///
159/// Note that in const-eval this function just returns `true` and therefore must
160/// only be used with `assert_unsafe_precondition!`, similar to `is_aligned_and_not_null`.
161#[inline]
162#[rustc_allow_const_fn_unstable(const_eval_select)]
163pub(crate) const fn maybe_is_nonoverlapping(
164 src: *const (),
165 dst: *const (),
166 size: usize,
167 count: usize,
168) -> bool {
169 // This is just for safety checks so we can const_eval_select.
170 const_eval_select!(
171 @capture { src: *const (), dst: *const (), size: usize, count: usize } -> bool:
172 if const {
173 true
174 } else {
175 let src_usize = src.addr();
176 let dst_usize = dst.addr();
177 let Some(size) = size.checked_mul(count) else {
178 crate::panicking::panic_nounwind(
179 "is_nonoverlapping: `size_of::<T>() * count` overflows a usize",
180 )
181 };
182 let diff = src_usize.abs_diff(dst_usize);
183 // If the absolute distance between the ptrs is at least as big as the size of the buffer,
184 // they do not overlap.
185 diff >= size
186 }
187 )
188}