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;
9 pub struct CheckPackedRef;
11 impl<'tcx> MirLint<'tcx> for CheckPackedRef {
12 fn run_lint(&self, tcx: TyCtxt<'tcx>, body: &Body<'tcx>) {
13 let param_env = tcx.param_env(body.source.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);
20 struct PackedRefChecker<'a, 'tcx> {
23 param_env: ty::ParamEnv<'tcx>,
24 source_info: SourceInfo,
27 impl<'tcx> Visitor<'tcx> for PackedRefChecker<'_, '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);
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);
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 def_id = self.body.source.instance.def_id();
44 if let Some(impl_def_id) = self.tcx.impl_of_method(def_id)
45 && self.tcx.is_builtin_derive(impl_def_id)
47 // If we ever reach here it means that the generated derive
48 // code is somehow doing an unaligned reference, which it
52 let source_info = self.source_info;
53 let lint_root = self.body.source_scopes[source_info.scope]
58 self.tcx.struct_span_lint_hir(
62 "reference to packed field is unaligned",
66 "fields of packed structs are not properly aligned, and creating \
67 a misaligned reference is undefined behavior (even if that \
68 reference is never dereferenced)",
71 "copy the field contents to a local variable, or replace the \
72 reference with a raw pointer and use `read_unaligned`/`write_unaligned` \
73 (loads and stores via `*p` must be properly aligned even when using raw pointers)"