|
| 1 | +use rustc_middle::mir::visit::{PlaceContext, Visitor}; |
| 2 | +use rustc_middle::mir::*; |
| 3 | +use rustc_middle::ty::{self, TyCtxt}; |
| 4 | +use rustc_session::lint::builtin::UNALIGNED_REFERENCES; |
| 5 | + |
| 6 | +use crate::transform::{MirPass, MirSource}; |
| 7 | +use crate::util; |
| 8 | + |
| 9 | +pub struct CheckPackedRef; |
| 10 | + |
| 11 | +impl<'tcx> MirPass<'tcx> for CheckPackedRef { |
| 12 | + fn run_pass(&self, tcx: TyCtxt<'tcx>, src: MirSource<'tcx>, body: &mut Body<'tcx>) { |
| 13 | + let param_env = tcx.param_env(src.instance.def_id()); |
| 14 | + let source_info = SourceInfo::outermost(body.span); |
| 15 | + let mut checker = PackedRefChecker { body, tcx, param_env, source_info }; |
| 16 | + checker.visit_body(&body); |
| 17 | + } |
| 18 | +} |
| 19 | + |
| 20 | +struct PackedRefChecker<'a, 'tcx> { |
| 21 | + body: &'a Body<'tcx>, |
| 22 | + tcx: TyCtxt<'tcx>, |
| 23 | + param_env: ty::ParamEnv<'tcx>, |
| 24 | + source_info: SourceInfo, |
| 25 | +} |
| 26 | + |
| 27 | +impl<'a, 'tcx> Visitor<'tcx> for PackedRefChecker<'a, 'tcx> { |
| 28 | + fn visit_terminator(&mut self, terminator: &Terminator<'tcx>, location: Location) { |
| 29 | + // Make sure we know where in the MIR we are. |
| 30 | + self.source_info = terminator.source_info; |
| 31 | + self.super_terminator(terminator, location); |
| 32 | + } |
| 33 | + |
| 34 | + fn visit_statement(&mut self, statement: &Statement<'tcx>, location: Location) { |
| 35 | + // Make sure we know where in the MIR we are. |
| 36 | + self.source_info = statement.source_info; |
| 37 | + self.super_statement(statement, location); |
| 38 | + } |
| 39 | + |
| 40 | + fn visit_place(&mut self, place: &Place<'tcx>, context: PlaceContext, _location: Location) { |
| 41 | + if context.is_borrow() { |
| 42 | + if util::is_disaligned(self.tcx, self.body, self.param_env, *place) { |
| 43 | + let source_info = self.source_info; |
| 44 | + let lint_root = self.body.source_scopes[source_info.scope] |
| 45 | + .local_data |
| 46 | + .as_ref() |
| 47 | + .assert_crate_local() |
| 48 | + .lint_root; |
| 49 | + self.tcx.struct_span_lint_hir( |
| 50 | + UNALIGNED_REFERENCES, |
| 51 | + lint_root, |
| 52 | + source_info.span, |
| 53 | + |lint| { |
| 54 | + lint.build(&format!("reference to packed field is unaligned",)) |
| 55 | + .note( |
| 56 | + "fields of packed structs are not properly aligned, and creating \ |
| 57 | + a misaligned reference is undefined behavior (even if that \ |
| 58 | + reference is never dereferenced)", |
| 59 | + ) |
| 60 | + .emit() |
| 61 | + }, |
| 62 | + ); |
| 63 | + } |
| 64 | + } |
| 65 | + } |
| 66 | +} |
0 commit comments