Skip to content
This repository was archived by the owner on May 28, 2025. It is now read-only.

Commit 67f4824

Browse files
committed
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 is related to a 2025H1 project goal for better UB checks in debug mode: rust-lang/rust-project-goals#177.
1 parent 851322b commit 67f4824

File tree

31 files changed

+280
-6
lines changed

31 files changed

+280
-6
lines changed

compiler/rustc_codegen_cranelift/src/base.rs

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -417,6 +417,16 @@ fn codegen_fn_body(fx: &mut FunctionCx<'_, '_, '_>, start_block: Block) {
417417
Some(source_info.span),
418418
);
419419
}
420+
AssertKind::NullPointerDereference => {
421+
let location = fx.get_caller_location(source_info).load_scalar(fx);
422+
423+
codegen_panic_inner(
424+
fx,
425+
rustc_hir::LangItem::PanicNullPointerDereference,
426+
&[location],
427+
Some(source_info.span),
428+
)
429+
}
420430
_ => {
421431
let location = fx.get_caller_location(source_info).load_scalar(fx);
422432

compiler/rustc_codegen_ssa/src/mir/block.rs

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -713,6 +713,11 @@ impl<'a, 'tcx, Bx: BuilderMethods<'a, 'tcx>> FunctionCx<'a, 'tcx, Bx> {
713713
// and `#[track_caller]` adds an implicit third argument.
714714
(LangItem::PanicMisalignedPointerDereference, vec![required, found, location])
715715
}
716+
AssertKind::NullPointerDereference => {
717+
// It's `fn panic_null_pointer_dereference()`,
718+
// `#[track_caller]` adds an implicit argument.
719+
(LangItem::PanicNullPointerDereference, vec![location])
720+
}
716721
_ => {
717722
// It's `pub fn panic_...()` and `#[track_caller]` adds an implicit argument.
718723
(msg.panic_function(), vec![location])

compiler/rustc_const_eval/src/const_eval/machine.rs

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -508,6 +508,7 @@ impl<'tcx> interpret::Machine<'tcx> for CompileTimeMachine<'tcx> {
508508
found: eval_to_int(found)?,
509509
}
510510
}
511+
NullPointerDereference => NullPointerDereference,
511512
};
512513
Err(ConstEvalErrKind::AssertFailure(err)).into()
513514
}

compiler/rustc_hir/src/lang_items.rs

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -316,6 +316,7 @@ language_item_table! {
316316
PanicAsyncFnResumedPanic, sym::panic_const_async_fn_resumed_panic, panic_const_async_fn_resumed_panic, Target::Fn, GenericRequirement::None;
317317
PanicAsyncGenFnResumedPanic, sym::panic_const_async_gen_fn_resumed_panic, panic_const_async_gen_fn_resumed_panic, Target::Fn, GenericRequirement::None;
318318
PanicGenFnNonePanic, sym::panic_const_gen_fn_none_panic, panic_const_gen_fn_none_panic, Target::Fn, GenericRequirement::None;
319+
PanicNullPointerDereference, sym::panic_null_pointer_dereference, panic_null_pointer_dereference, Target::Fn, GenericRequirement::None;
319320
/// libstd panic entry point. Necessary for const eval to be able to catch it
320321
BeginPanic, sym::begin_panic, begin_panic_fn, Target::Fn, GenericRequirement::None;
321322

compiler/rustc_middle/messages.ftl

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -17,6 +17,9 @@ middle_assert_gen_resume_after_panic = `gen` fn or block cannot be further itera
1717
middle_assert_misaligned_ptr_deref =
1818
misaligned pointer dereference: address must be a multiple of {$required} but is {$found}
1919
20+
middle_assert_null_ptr_deref =
21+
null pointer dereference occurred
22+
2023
middle_assert_op_overflow =
2124
attempt to compute `{$left} {$op} {$right}`, which would overflow
2225

compiler/rustc_middle/src/mir/syntax.rs

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1076,6 +1076,7 @@ pub enum AssertKind<O> {
10761076
ResumedAfterReturn(CoroutineKind),
10771077
ResumedAfterPanic(CoroutineKind),
10781078
MisalignedPointerDereference { required: O, found: O },
1079+
NullPointerDereference,
10791080
}
10801081

10811082
#[derive(Clone, Debug, PartialEq, TyEncodable, TyDecodable, Hash, HashStable)]

compiler/rustc_middle/src/mir/terminator.rs

Lines changed: 4 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -206,6 +206,7 @@ impl<O> AssertKind<O> {
206206
ResumedAfterPanic(CoroutineKind::Desugared(CoroutineDesugaring::Gen, _)) => {
207207
LangItem::PanicGenFnNonePanic
208208
}
209+
NullPointerDereference => LangItem::PanicNullPointerDereference,
209210

210211
BoundsCheck { .. } | MisalignedPointerDereference { .. } => {
211212
bug!("Unexpected AssertKind")
@@ -271,6 +272,7 @@ impl<O> AssertKind<O> {
271272
"\"misaligned pointer dereference: address must be a multiple of {{}} but is {{}}\", {required:?}, {found:?}"
272273
)
273274
}
275+
NullPointerDereference => write!(f, "\"null pointer dereference occured\""),
274276
ResumedAfterReturn(CoroutineKind::Coroutine(_)) => {
275277
write!(f, "\"coroutine resumed after completion\"")
276278
}
@@ -341,7 +343,7 @@ impl<O> AssertKind<O> {
341343
ResumedAfterPanic(CoroutineKind::Coroutine(_)) => {
342344
middle_assert_coroutine_resume_after_panic
343345
}
344-
346+
NullPointerDereference => middle_assert_null_ptr_deref,
345347
MisalignedPointerDereference { .. } => middle_assert_misaligned_ptr_deref,
346348
}
347349
}
@@ -374,7 +376,7 @@ impl<O> AssertKind<O> {
374376
add!("left", format!("{left:#?}"));
375377
add!("right", format!("{right:#?}"));
376378
}
377-
ResumedAfterReturn(_) | ResumedAfterPanic(_) => {}
379+
ResumedAfterReturn(_) | ResumedAfterPanic(_) | NullPointerDereference => {}
378380
MisalignedPointerDereference { required, found } => {
379381
add!("required", format!("{required:#?}"));
380382
add!("found", format!("{found:#?}"));

compiler/rustc_middle/src/mir/visit.rs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -636,7 +636,7 @@ macro_rules! make_mir_visitor {
636636
OverflowNeg(op) | DivisionByZero(op) | RemainderByZero(op) => {
637637
self.visit_operand(op, location);
638638
}
639-
ResumedAfterReturn(_) | ResumedAfterPanic(_) => {
639+
ResumedAfterReturn(_) | ResumedAfterPanic(_) | NullPointerDereference => {
640640
// Nothing to visit
641641
}
642642
MisalignedPointerDereference { required, found } => {
Lines changed: 110 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,110 @@
1+
use rustc_index::IndexVec;
2+
use rustc_middle::mir::interpret::Scalar;
3+
use rustc_middle::mir::*;
4+
use rustc_middle::ty::{Ty, TyCtxt};
5+
use rustc_session::Session;
6+
7+
use crate::check_pointers::{BorrowCheckMode, PointerCheck, check_pointers};
8+
9+
pub(super) struct CheckNull;
10+
11+
impl<'tcx> crate::MirPass<'tcx> for CheckNull {
12+
fn is_enabled(&self, sess: &Session) -> bool {
13+
sess.ub_checks()
14+
}
15+
16+
fn run_pass(&self, tcx: TyCtxt<'tcx>, body: &mut Body<'tcx>) {
17+
check_pointers(tcx, body, &[], insert_null_check, BorrowCheckMode::IncludeBorrows);
18+
}
19+
20+
fn is_required(&self) -> bool {
21+
true
22+
}
23+
}
24+
25+
fn insert_null_check<'tcx>(
26+
tcx: TyCtxt<'tcx>,
27+
pointer: Place<'tcx>,
28+
pointee_ty: Ty<'tcx>,
29+
local_decls: &mut IndexVec<Local, LocalDecl<'tcx>>,
30+
stmts: &mut Vec<Statement<'tcx>>,
31+
source_info: SourceInfo,
32+
) -> PointerCheck<'tcx> {
33+
// Cast the pointer to a *const ().
34+
let const_raw_ptr = Ty::new_imm_ptr(tcx, tcx.types.unit);
35+
let rvalue = Rvalue::Cast(CastKind::PtrToPtr, Operand::Copy(pointer), const_raw_ptr);
36+
let thin_ptr = local_decls.push(LocalDecl::with_source_info(const_raw_ptr, source_info)).into();
37+
stmts
38+
.push(Statement { source_info, kind: StatementKind::Assign(Box::new((thin_ptr, rvalue))) });
39+
40+
// Transmute the pointer to a usize (equivalent to `ptr.addr()`).
41+
let rvalue = Rvalue::Cast(CastKind::Transmute, Operand::Copy(thin_ptr), tcx.types.usize);
42+
let addr = local_decls.push(LocalDecl::with_source_info(tcx.types.usize, source_info)).into();
43+
stmts.push(Statement { source_info, kind: StatementKind::Assign(Box::new((addr, rvalue))) });
44+
45+
// Get size of the pointee (zero-sized reads and writes are allowed).
46+
let rvalue = Rvalue::NullaryOp(NullOp::SizeOf, pointee_ty);
47+
let sizeof_pointee =
48+
local_decls.push(LocalDecl::with_source_info(tcx.types.usize, source_info)).into();
49+
stmts.push(Statement {
50+
source_info,
51+
kind: StatementKind::Assign(Box::new((sizeof_pointee, rvalue))),
52+
});
53+
54+
// Check that the pointee is not a ZST.
55+
let zero = Operand::Constant(Box::new(ConstOperand {
56+
span: source_info.span,
57+
user_ty: None,
58+
const_: Const::Val(ConstValue::Scalar(Scalar::from_target_usize(0, &tcx)), tcx.types.usize),
59+
}));
60+
let is_pointee_no_zst =
61+
local_decls.push(LocalDecl::with_source_info(tcx.types.bool, source_info)).into();
62+
stmts.push(Statement {
63+
source_info,
64+
kind: StatementKind::Assign(Box::new((
65+
is_pointee_no_zst,
66+
Rvalue::BinaryOp(BinOp::Ne, Box::new((Operand::Copy(sizeof_pointee), zero.clone()))),
67+
))),
68+
});
69+
70+
// Check whether the pointer is null.
71+
let is_null = local_decls.push(LocalDecl::with_source_info(tcx.types.bool, source_info)).into();
72+
stmts.push(Statement {
73+
source_info,
74+
kind: StatementKind::Assign(Box::new((
75+
is_null,
76+
Rvalue::BinaryOp(BinOp::Eq, Box::new((Operand::Copy(addr), zero))),
77+
))),
78+
});
79+
80+
// We want to throw an exception if the pointer is null and doesn't point to a ZST.
81+
let should_throw_exception =
82+
local_decls.push(LocalDecl::with_source_info(tcx.types.bool, source_info)).into();
83+
stmts.push(Statement {
84+
source_info,
85+
kind: StatementKind::Assign(Box::new((
86+
should_throw_exception,
87+
Rvalue::BinaryOp(
88+
BinOp::BitAnd,
89+
Box::new((Operand::Copy(is_null), Operand::Copy(is_pointee_no_zst))),
90+
),
91+
))),
92+
});
93+
94+
// The final condition whether this pointer usage is ok or not.
95+
let is_ok = local_decls.push(LocalDecl::with_source_info(tcx.types.bool, source_info)).into();
96+
stmts.push(Statement {
97+
source_info,
98+
kind: StatementKind::Assign(Box::new((
99+
is_ok,
100+
Rvalue::UnaryOp(UnOp::Not, Operand::Copy(should_throw_exception)),
101+
))),
102+
});
103+
104+
// Emit a PointerCheck that asserts on the condition and otherwise triggers
105+
// a AssertKind::NullPointerDereference.
106+
PointerCheck {
107+
cond: Operand::Copy(is_ok),
108+
assert_kind: Box::new(AssertKind::NullPointerDereference),
109+
}
110+
}

compiler/rustc_mir_transform/src/check_pointers.rs

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -17,6 +17,7 @@ pub(crate) struct PointerCheck<'tcx> {
1717
/// [NonMutatingUseContext::SharedBorrow].
1818
#[derive(Copy, Clone)]
1919
pub(crate) enum BorrowCheckMode {
20+
IncludeBorrows,
2021
ExcludeBorrows,
2122
}
2223

@@ -168,7 +169,7 @@ impl<'a, 'tcx> PointerFinder<'a, 'tcx> {
168169
) => true,
169170
PlaceContext::MutatingUse(MutatingUseContext::Borrow)
170171
| PlaceContext::NonMutatingUse(NonMutatingUseContext::SharedBorrow) => {
171-
!matches!(self.borrow_check_mode, BorrowCheckMode::ExcludeBorrows)
172+
matches!(self.borrow_check_mode, BorrowCheckMode::IncludeBorrows)
172173
}
173174
_ => false,
174175
}

0 commit comments

Comments
 (0)