Skip to main content

rustc_mir_transform/
check_null.rs

1use rustc_hir::attrs::lang_items::LangItem;
2use rustc_index::IndexVec;
3use rustc_middle::mir::visit::{MutatingUseContext, NonMutatingUseContext, PlaceContext};
4use rustc_middle::mir::*;
5use rustc_middle::ty::{Ty, TyCtxt};
6use rustc_session::Session;
7
8use crate::PassPolicy;
9use crate::check_pointers::{BorrowedFieldProjectionMode, PointerCheck, check_pointers};
10
11pub(super) struct CheckNull;
12
13impl<'tcx> crate::MirPass<'tcx> for CheckNull {
14    fn policy(&self, sess: &Session) -> PassPolicy {
15        // When UB checks are enabled this is part of their semantics, not an optimization.
16        PassPolicy::optional_non_optimization(sess.ub_checks())
17    }
18
19    fn run_pass(&self, tcx: TyCtxt<'tcx>, body: &mut Body<'tcx>) {
20        check_pointers(
21            tcx,
22            body,
23            &[],
24            insert_null_check,
25            BorrowedFieldProjectionMode::NoFollowProjections,
26        );
27    }
28}
29
30fn insert_null_check<'tcx>(
31    tcx: TyCtxt<'tcx>,
32    pointer: Place<'tcx>,
33    pointee_ty: Ty<'tcx>,
34    context: PlaceContext,
35    local_decls: &mut IndexVec<Local, LocalDecl<'tcx>>,
36    stmts: &mut Vec<Statement<'tcx>>,
37    source_info: SourceInfo,
38) -> PointerCheck<'tcx> {
39    // Cast the pointer to a *const ().
40    let const_raw_ptr = Ty::new_imm_ptr(tcx, tcx.types.unit);
41    let rvalue = Rvalue::Cast(CastKind::PtrToPtr, Operand::Copy(pointer), const_raw_ptr);
42    let thin_ptr = local_decls.push(LocalDecl::with_source_info(const_raw_ptr, source_info)).into();
43    stmts.push(Statement::new(source_info, StatementKind::Assign(Box::new((thin_ptr, rvalue)))));
44
45    // Transmute the pointer to a usize (equivalent to `ptr.addr()`).
46    let rvalue = Rvalue::Cast(CastKind::Transmute, Operand::Copy(thin_ptr), tcx.types.usize);
47    let addr = local_decls.push(LocalDecl::with_source_info(tcx.types.usize, source_info)).into();
48    stmts.push(Statement::new(source_info, StatementKind::Assign(Box::new((addr, rvalue)))));
49
50    let zero = Operand::Constant(Box::new(ConstOperand {
51        span: source_info.span,
52        user_ty: None,
53        const_: Const::Val(ConstValue::from_target_usize(0, &tcx), tcx.types.usize),
54    }));
55
56    let (pointee_should_be_checked, assert_kind) = match context {
57        // Borrows pointing to "null" are UB even if the pointee is a ZST.
58        PlaceContext::NonMutatingUse(NonMutatingUseContext::SharedBorrow)
59        | PlaceContext::MutatingUse(MutatingUseContext::Borrow) => {
60            // Pointer should be checked unconditionally.
61            (
62                Operand::Constant(Box::new(ConstOperand {
63                    span: source_info.span,
64                    user_ty: None,
65                    const_: Const::from_bool(tcx, true),
66                })),
67                AssertKind::NullReferenceConstructed,
68            )
69        }
70        // Other usages of null pointers only are UB if the pointee is not a ZST.
71        _ => {
72            let size_of = tcx.require_lang_item(LangItem::SizeOf, source_info.span);
73            let size_of =
74                Operand::unevaluated_constant(tcx, size_of, &[pointee_ty.into()], source_info.span);
75
76            let pointee_should_be_checked =
77                local_decls.push(LocalDecl::with_source_info(tcx.types.bool, source_info)).into();
78            let rvalue = Rvalue::BinaryOp(BinOp::Ne, Box::new((size_of, zero.clone())));
79            stmts.push(Statement::new(
80                source_info,
81                StatementKind::Assign(Box::new((pointee_should_be_checked, rvalue))),
82            ));
83            (Operand::Copy(pointee_should_be_checked), AssertKind::NullPointerDereference)
84        }
85    };
86
87    // Check whether the pointer is null.
88    let is_null = local_decls.push(LocalDecl::with_source_info(tcx.types.bool, source_info)).into();
89    stmts.push(Statement::new(
90        source_info,
91        StatementKind::Assign(Box::new((
92            is_null,
93            Rvalue::BinaryOp(BinOp::Eq, Box::new((Operand::Copy(addr), zero))),
94        ))),
95    ));
96
97    // We want to throw an exception if the pointer is null and the pointee is not unconditionally
98    // allowed (which for all non-borrow place uses, is when the pointee is ZST).
99    let should_throw_exception =
100        local_decls.push(LocalDecl::with_source_info(tcx.types.bool, source_info)).into();
101    stmts.push(Statement::new(
102        source_info,
103        StatementKind::Assign(Box::new((
104            should_throw_exception,
105            Rvalue::BinaryOp(
106                BinOp::BitAnd,
107                Box::new((Operand::Copy(is_null), pointee_should_be_checked)),
108            ),
109        ))),
110    ));
111
112    // The final condition whether this pointer usage is ok or not.
113    let is_ok = local_decls.push(LocalDecl::with_source_info(tcx.types.bool, source_info)).into();
114    stmts.push(Statement::new(
115        source_info,
116        StatementKind::Assign(Box::new((
117            is_ok,
118            Rvalue::UnaryOp(UnOp::Not, Operand::Copy(should_throw_exception)),
119        ))),
120    ));
121
122    // Emit a PointerCheck that asserts on the condition and otherwise triggers
123    // the chosen AssertKind.
124    PointerCheck { cond: Operand::Copy(is_ok), assert_kind: Box::new(assert_kind) }
125}