Skip to content

Commit e72e22d

Browse files
borsgitbot
authored and
gitbot
committed
Auto merge of rust-lang#134424 - 1c3t3a:null-checks, r=saethlin
Insert null checks for pointer dereferences when debug assertions are enabled Similar to how the alignment is already checked, this adds a check for null pointer dereferences in debug mode. It is implemented similarly to the alignment check as a `MirPass`. This inserts checks in the same places as the `CheckAlignment` pass and additionally also inserts checks for `Borrows`, so code like ```rust let ptr: *const u32 = std::ptr::null(); let val: &u32 = unsafe { &*ptr }; ``` will have a check inserted on dereference. This is done because null references are UB. The alignment check doesn't cover these places, because in `&(*ptr).field`, the exact requirement is that the final reference must be aligned. This is something to consider further enhancements of the alignment check. For now this is implemented as a separate `MirPass`, to make it easy to disable this check if necessary. This is related to a 2025H1 project goal for better UB checks in debug mode: rust-lang/rust-project-goals#177. r? `@saethlin`
2 parents 60d6184 + a5953ff commit e72e22d

File tree

1 file changed

+16
-0
lines changed

1 file changed

+16
-0
lines changed

core/src/panicking.rs

+16
Original file line numberDiff line numberDiff line change
@@ -291,6 +291,22 @@ fn panic_misaligned_pointer_dereference(required: usize, found: usize) -> ! {
291291
)
292292
}
293293

294+
#[cfg_attr(not(feature = "panic_immediate_abort"), inline(never), cold, optimize(size))]
295+
#[cfg_attr(feature = "panic_immediate_abort", inline)]
296+
#[track_caller]
297+
#[cfg_attr(not(bootstrap), lang = "panic_null_pointer_dereference")] // needed by codegen for panic on null pointer deref
298+
#[rustc_nounwind] // `CheckNull` MIR pass requires this function to never unwind
299+
fn panic_null_pointer_dereference() -> ! {
300+
if cfg!(feature = "panic_immediate_abort") {
301+
super::intrinsics::abort()
302+
}
303+
304+
panic_nounwind_fmt(
305+
format_args!("null pointer dereference occured"),
306+
/* force_no_backtrace */ false,
307+
)
308+
}
309+
294310
/// Panics because we cannot unwind out of a function.
295311
///
296312
/// This is a separate function to avoid the codesize impact of each crate containing the string to

0 commit comments

Comments
 (0)