1
//! Provides the [`assert_unsafe_precondition`] macro as well as some utility functions that cover
2
//! common preconditions.
3

            
4
use 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 if we eventually execute language UB which relies on the
25
/// library UB, the backtrace Miri reports may be far removed from original cause.
26
///
27
/// These checks are behind a condition which is evaluated at codegen time, not expansion time like
28
/// [`debug_assert`]. This means that a standard library built with optimizations and debug
29
/// assertions disabled will have these checks optimized out of its monomorphizations, but if a
30
/// caller of the standard library has debug assertions enabled and monomorphizes an expansion of
31
/// this macro, that monomorphization will contain the check.
32
///
33
/// Since these checks cannot be optimized out in MIR, some care must be taken in both call and
34
/// implementation to mitigate their compile-time overhead. Calls to this macro always expand to
35
/// this structure:
36
/// ```ignore (pseudocode)
37
/// if ::core::intrinsics::check_language_ub() {
38
///     precondition_check(args)
39
/// }
40
/// ```
41
/// where `precondition_check` is monomorphic with the attributes `#[rustc_nounwind]`, `#[inline]` and
42
/// `#[rustc_no_mir_inline]`. This combination of attributes ensures that the actual check logic is
43
/// compiled only once and generates a minimal amount of IR because the check cannot be inlined in
44
/// MIR, but *can* be inlined and fully optimized by a codegen backend.
45
///
46
/// Callers should avoid introducing any other `let` bindings or any code outside this macro in
47
/// order to call it. Since the precompiled standard library is built with full debuginfo and these
48
/// variables cannot be optimized out in MIR, an innocent-looking `let` can produce enough
49
/// debuginfo to have a measurable compile-time impact on debug builds.
50
#[macro_export]
51
#[unstable(feature = "ub_checks", issue = "none")]
52
#[allow_internal_unstable(coverage_attribute)]
53
macro_rules! assert_unsafe_precondition {
54
    ($kind:ident, $message:expr, ($($name:ident:$ty:ty = $arg:expr),*$(,)?) => $e:expr $(,)?) => {
55
        {
56
            // This check is inlineable, but not by the MIR inliner.
57
            // The reason for this is that the MIR inliner is in an exceptionally bad position
58
            // to think about whether or not to inline this. In MIR, this call is gated behind `debug_assertions`,
59
            // which will codegen to `false` in release builds. Inlining the check would be wasted work in that case and
60
            // would be bad for compile times.
61
            //
62
            // LLVM on the other hand sees the constant branch, so if it's `false`, it can immediately delete it without
63
            // inlining the check. If it's `true`, it can inline it and get significantly better performance.
64
            #[rustc_no_mir_inline]
65
            #[inline]
66
            #[rustc_nounwind]
67
            #[track_caller]
68
7556642
            const fn precondition_check($($name:$ty),*) {
69
7556642
                if !$e {
70
                    // Ferrocene annotation: This code cannot be covered because it causes an
71
                    // non-unwinding panic, which means it cannot be caught by any means in a test.
72
                    let msg = concat!("unsafe precondition(s) violated: ", $message,
73
                        "\n\nThis indicates a bug in the program. \
74
                        This Undefined Behavior check is optional, and cannot be relied on for safety.");
75
                    // blocked on fmt::Arguments
76
                    #[cfg(not(feature = "ferrocene_certified"))]
77
                    ::core::panicking::panic_nounwind_fmt(::core::fmt::Arguments::new_const(&[msg]), false);
78
                    #[cfg(feature = "ferrocene_certified")]
79
                    ::core::panicking::panic_nounwind(msg);
80
7556642
                }
81
7556642
            }
82

            
83
            if ::core::ub_checks::$kind() {
84
                precondition_check($($arg,)*);
85
            }
86
        }
87
    };
88
}
89
#[unstable(feature = "ub_checks", issue = "none")]
90
pub use assert_unsafe_precondition;
91
/// Checking library UB is always enabled when UB-checking is done
92
/// (and we use a reexport so that there is no unnecessary wrapper function).
93
#[unstable(feature = "ub_checks", issue = "none")]
94
pub use intrinsics::ub_checks as check_library_ub;
95

            
96
/// Determines whether we should check for language UB.
97
///
98
/// The intention is to not do that when running in the interpreter, as that one has its own
99
/// language UB checks which generally produce better errors.
100
#[inline]
101
#[rustc_allow_const_fn_unstable(const_eval_select)]
102
69929807
pub(crate) const fn check_language_ub() -> bool {
103
    // Only used for UB checks so we may const_eval_select.
104
69929807
    intrinsics::ub_checks()
105
69929807
        && const_eval_select!(
106
            @capture { } -> bool:
107
            if const {
108
                // Always disable UB checks.
109
                false
110
            } else {
111
                // Disable UB checks in Miri.
112
                !cfg!(miri)
113
            }
114
        )
115
69929807
}
116

            
117
/// Checks whether `ptr` is properly aligned with respect to the given alignment, and
118
/// if `is_zst == false`, that `ptr` is not null.
119
///
120
/// In `const` this is approximate and can fail spuriously. It is primarily intended
121
/// for `assert_unsafe_precondition!` with `check_language_ub`, in which case the
122
/// check is anyway not executed in `const`.
123
#[inline]
124
#[rustc_allow_const_fn_unstable(const_eval_select)]
125
#[cfg(any(
126
    not(feature = "ferrocene_certified"),
127
    all(feature = "ferrocene_certified", debug_assertions)
128
))]
129
12001123
pub(crate) const fn maybe_is_aligned_and_not_null(
130
12001123
    ptr: *const (),
131
12001123
    align: usize,
132
12001123
    is_zst: bool,
133
12001123
) -> bool {
134
    // This is just for safety checks so we can const_eval_select.
135
12001123
    maybe_is_aligned(ptr, align) && (is_zst || !ptr.is_null())
136
12001123
}
137

            
138
/// Checks whether `ptr` is properly aligned with respect to the given alignment.
139
///
140
/// In `const` this is approximate and can fail spuriously. It is primarily intended
141
/// for `assert_unsafe_precondition!` with `check_language_ub`, in which case the
142
/// check is anyway not executed in `const`.
143
#[inline]
144
#[rustc_allow_const_fn_unstable(const_eval_select)]
145
12001123
pub(crate) const fn maybe_is_aligned(ptr: *const (), align: usize) -> bool {
146
    // This is just for safety checks so we can const_eval_select.
147
12001123
    const_eval_select!(
148
        @capture { ptr: *const (), align: usize } -> bool:
149
        if const {
150
            true
151
        } else {
152
            ptr.is_aligned_to(align)
153
        }
154
    )
155
12001123
}
156

            
157
#[inline]
158
#[cfg(not(feature = "ferrocene_certified"))]
159
pub(crate) const fn is_valid_allocation_size(size: usize, len: usize) -> bool {
160
    let max_len = if size == 0 { usize::MAX } else { isize::MAX as usize / size };
161
    len <= max_len
162
}
163

            
164
/// Checks whether the regions of memory starting at `src` and `dst` of size
165
/// `count * size` do *not* overlap.
166
///
167
/// Note that in const-eval this function just returns `true` and therefore must
168
/// only be used with `assert_unsafe_precondition!`, similar to `is_aligned_and_not_null`.
169
#[inline]
170
#[rustc_allow_const_fn_unstable(const_eval_select)]
171
#[cfg(not(feature = "ferrocene_certified"))]
172
pub(crate) const fn maybe_is_nonoverlapping(
173
    src: *const (),
174
    dst: *const (),
175
    size: usize,
176
    count: usize,
177
) -> bool {
178
    // This is just for safety checks so we can const_eval_select.
179
    const_eval_select!(
180
        @capture { src: *const (), dst: *const (), size: usize, count: usize } -> bool:
181
        if const {
182
            true
183
        } else {
184
            let src_usize = src.addr();
185
            let dst_usize = dst.addr();
186
            let Some(size) = size.checked_mul(count) else {
187
                crate::panicking::panic_nounwind(
188
                    "is_nonoverlapping: `size_of::<T>() * count` overflows a usize",
189
                )
190
            };
191
            let diff = src_usize.abs_diff(dst_usize);
192
            // If the absolute distance between the ptrs is at least as big as the size of the buffer,
193
            // they do not overlap.
194
            diff >= size
195
        }
196
    )
197
}