]> git.lizzy.rs Git - rust.git/blob - src/librustc_mir/transform/check_unsafety.rs
Auto merge of #50767 - oli-obk:rls_clippy, r=kennytm
[rust.git] / src / librustc_mir / transform / check_unsafety.rs
1 // Copyright 2017 The Rust Project Developers. See the COPYRIGHT
2 // file at the top-level directory of this distribution and at
3 // http://rust-lang.org/COPYRIGHT.
4 //
5 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
6 // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
7 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
8 // option. This file may not be copied, modified, or distributed
9 // except according to those terms.
10
11 use rustc_data_structures::fx::FxHashSet;
12 use rustc_data_structures::indexed_vec::IndexVec;
13 use rustc_data_structures::sync::Lrc;
14
15 use rustc::ty::maps::Providers;
16 use rustc::ty::{self, TyCtxt};
17 use rustc::hir;
18 use rustc::hir::def_id::DefId;
19 use rustc::lint::builtin::{SAFE_EXTERN_STATICS, SAFE_PACKED_BORROWS, UNUSED_UNSAFE};
20 use rustc::mir::*;
21 use rustc::mir::visit::{PlaceContext, Visitor};
22
23 use syntax::ast;
24 use syntax::symbol::Symbol;
25
26 use util;
27
28 pub struct UnsafetyChecker<'a, 'tcx: 'a> {
29     mir: &'a Mir<'tcx>,
30     visibility_scope_info: &'a IndexVec<VisibilityScope, VisibilityScopeInfo>,
31     violations: Vec<UnsafetyViolation>,
32     source_info: SourceInfo,
33     tcx: TyCtxt<'a, 'tcx, 'tcx>,
34     param_env: ty::ParamEnv<'tcx>,
35     used_unsafe: FxHashSet<ast::NodeId>,
36     inherited_blocks: Vec<(ast::NodeId, bool)>,
37 }
38
39 impl<'a, 'gcx, 'tcx> UnsafetyChecker<'a, 'tcx> {
40     fn new(mir: &'a Mir<'tcx>,
41            visibility_scope_info: &'a IndexVec<VisibilityScope, VisibilityScopeInfo>,
42            tcx: TyCtxt<'a, 'tcx, 'tcx>,
43            param_env: ty::ParamEnv<'tcx>) -> Self {
44         Self {
45             mir,
46             visibility_scope_info,
47             violations: vec![],
48             source_info: SourceInfo {
49                 span: mir.span,
50                 scope: ARGUMENT_VISIBILITY_SCOPE
51             },
52             tcx,
53             param_env,
54             used_unsafe: FxHashSet(),
55             inherited_blocks: vec![],
56         }
57     }
58 }
59
60 impl<'a, 'tcx> Visitor<'tcx> for UnsafetyChecker<'a, 'tcx> {
61     fn visit_terminator(&mut self,
62                         block: BasicBlock,
63                         terminator: &Terminator<'tcx>,
64                         location: Location)
65     {
66         self.source_info = terminator.source_info;
67         match terminator.kind {
68             TerminatorKind::Goto { .. } |
69             TerminatorKind::SwitchInt { .. } |
70             TerminatorKind::Drop { .. } |
71             TerminatorKind::Yield { .. } |
72             TerminatorKind::Assert { .. } |
73             TerminatorKind::DropAndReplace { .. } |
74             TerminatorKind::GeneratorDrop |
75             TerminatorKind::Resume |
76             TerminatorKind::Abort |
77             TerminatorKind::Return |
78             TerminatorKind::Unreachable |
79             TerminatorKind::FalseEdges { .. } |
80             TerminatorKind::FalseUnwind { .. } => {
81                 // safe (at least as emitted during MIR construction)
82             }
83
84             TerminatorKind::Call { ref func, .. } => {
85                 let func_ty = func.ty(self.mir, self.tcx);
86                 let sig = func_ty.fn_sig(self.tcx);
87                 if let hir::Unsafety::Unsafe = sig.unsafety() {
88                     self.require_unsafe("call to unsafe function")
89                 }
90             }
91         }
92         self.super_terminator(block, terminator, location);
93     }
94
95     fn visit_statement(&mut self,
96                        block: BasicBlock,
97                        statement: &Statement<'tcx>,
98                        location: Location)
99     {
100         self.source_info = statement.source_info;
101         match statement.kind {
102             StatementKind::Assign(..) |
103             StatementKind::SetDiscriminant { .. } |
104             StatementKind::StorageLive(..) |
105             StatementKind::StorageDead(..) |
106             StatementKind::EndRegion(..) |
107             StatementKind::Validate(..) |
108             StatementKind::UserAssertTy(..) |
109             StatementKind::Nop => {
110                 // safe (at least as emitted during MIR construction)
111             }
112
113             StatementKind::InlineAsm { .. } => {
114                 self.require_unsafe("use of inline assembly")
115             },
116         }
117         self.super_statement(block, statement, location);
118     }
119
120     fn visit_rvalue(&mut self,
121                     rvalue: &Rvalue<'tcx>,
122                     location: Location)
123     {
124         if let &Rvalue::Aggregate(box ref aggregate, _) = rvalue {
125             match aggregate {
126                 &AggregateKind::Array(..) |
127                 &AggregateKind::Tuple |
128                 &AggregateKind::Adt(..) => {}
129                 &AggregateKind::Closure(def_id, _) |
130                 &AggregateKind::Generator(def_id, _, _) => {
131                     let UnsafetyCheckResult {
132                         violations, unsafe_blocks
133                     } = self.tcx.unsafety_check_result(def_id);
134                     self.register_violations(&violations, &unsafe_blocks);
135                 }
136             }
137         }
138         self.super_rvalue(rvalue, location);
139     }
140
141     fn visit_place(&mut self,
142                     place: &Place<'tcx>,
143                     context: PlaceContext<'tcx>,
144                     location: Location) {
145         if let PlaceContext::Borrow { .. } = context {
146             if util::is_disaligned(self.tcx, self.mir, self.param_env, place) {
147                 let source_info = self.source_info;
148                 let lint_root =
149                     self.visibility_scope_info[source_info.scope].lint_root;
150                 self.register_violations(&[UnsafetyViolation {
151                     source_info,
152                     description: Symbol::intern("borrow of packed field").as_interned_str(),
153                     kind: UnsafetyViolationKind::BorrowPacked(lint_root)
154                 }], &[]);
155             }
156         }
157
158         match place {
159             &Place::Projection(box Projection {
160                 ref base, ref elem
161             }) => {
162                 let old_source_info = self.source_info;
163                 if let &Place::Local(local) = base {
164                     if self.mir.local_decls[local].internal {
165                         // Internal locals are used in the `move_val_init` desugaring.
166                         // We want to check unsafety against the source info of the
167                         // desugaring, rather than the source info of the RHS.
168                         self.source_info = self.mir.local_decls[local].source_info;
169                     }
170                 }
171                 let base_ty = base.ty(self.mir, self.tcx).to_ty(self.tcx);
172                 match base_ty.sty {
173                     ty::TyRawPtr(..) => {
174                         self.require_unsafe("dereference of raw pointer")
175                     }
176                     ty::TyAdt(adt, _) => {
177                         if adt.is_union() {
178                             if context == PlaceContext::Store ||
179                                 context == PlaceContext::AsmOutput ||
180                                 context == PlaceContext::Drop
181                             {
182                                 let elem_ty = match elem {
183                                     &ProjectionElem::Field(_, ty) => ty,
184                                     _ => span_bug!(
185                                         self.source_info.span,
186                                         "non-field projection {:?} from union?",
187                                         place)
188                                 };
189                                 if elem_ty.moves_by_default(self.tcx, self.param_env,
190                                                             self.source_info.span) {
191                                     self.require_unsafe(
192                                         "assignment to non-`Copy` union field")
193                                 } else {
194                                     // write to non-move union, safe
195                                 }
196                             } else {
197                                 self.require_unsafe("access to union field")
198                             }
199                         }
200                     }
201                     _ => {}
202                 }
203                 self.source_info = old_source_info;
204             }
205             &Place::Local(..) => {
206                 // locals are safe
207             }
208             &Place::Static(box Static { def_id, ty: _ }) => {
209                 if self.tcx.is_static(def_id) == Some(hir::Mutability::MutMutable) {
210                     self.require_unsafe("use of mutable static");
211                 } else if self.tcx.is_foreign_item(def_id) {
212                     let source_info = self.source_info;
213                     let lint_root =
214                         self.visibility_scope_info[source_info.scope].lint_root;
215                     self.register_violations(&[UnsafetyViolation {
216                         source_info,
217                         description: Symbol::intern("use of extern static").as_interned_str(),
218                         kind: UnsafetyViolationKind::ExternStatic(lint_root)
219                     }], &[]);
220                 }
221             }
222         };
223         self.super_place(place, context, location);
224     }
225 }
226
227 impl<'a, 'tcx> UnsafetyChecker<'a, 'tcx> {
228     fn require_unsafe(&mut self,
229                       description: &'static str)
230     {
231         let source_info = self.source_info;
232         self.register_violations(&[UnsafetyViolation {
233             source_info,
234             description: Symbol::intern(description).as_interned_str(),
235             kind: UnsafetyViolationKind::General,
236         }], &[]);
237     }
238
239     fn register_violations(&mut self,
240                            violations: &[UnsafetyViolation],
241                            unsafe_blocks: &[(ast::NodeId, bool)]) {
242         let within_unsafe = match self.visibility_scope_info[self.source_info.scope].safety {
243             Safety::Safe => {
244                 for violation in violations {
245                     if !self.violations.contains(violation) {
246                         self.violations.push(violation.clone())
247                     }
248                 }
249
250                 false
251             }
252             Safety::BuiltinUnsafe | Safety::FnUnsafe => true,
253             Safety::ExplicitUnsafe(node_id) => {
254                 if !violations.is_empty() {
255                     self.used_unsafe.insert(node_id);
256                 }
257                 true
258             }
259         };
260         self.inherited_blocks.extend(unsafe_blocks.iter().map(|&(node_id, is_used)| {
261             (node_id, is_used && !within_unsafe)
262         }));
263     }
264 }
265
266 pub(crate) fn provide(providers: &mut Providers) {
267     *providers = Providers {
268         unsafety_check_result,
269         unsafe_derive_on_repr_packed,
270         ..*providers
271     };
272 }
273
274 struct UnusedUnsafeVisitor<'a> {
275     used_unsafe: &'a FxHashSet<ast::NodeId>,
276     unsafe_blocks: &'a mut Vec<(ast::NodeId, bool)>,
277 }
278
279 impl<'a, 'tcx> hir::intravisit::Visitor<'tcx> for UnusedUnsafeVisitor<'a> {
280     fn nested_visit_map<'this>(&'this mut self) ->
281         hir::intravisit::NestedVisitorMap<'this, 'tcx>
282     {
283         hir::intravisit::NestedVisitorMap::None
284     }
285
286     fn visit_block(&mut self, block: &'tcx hir::Block) {
287         hir::intravisit::walk_block(self, block);
288
289         if let hir::UnsafeBlock(hir::UserProvided) = block.rules {
290             self.unsafe_blocks.push((block.id, self.used_unsafe.contains(&block.id)));
291         }
292     }
293 }
294
295 fn check_unused_unsafe<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>,
296                                  def_id: DefId,
297                                  used_unsafe: &FxHashSet<ast::NodeId>,
298                                  unsafe_blocks: &'a mut Vec<(ast::NodeId, bool)>)
299 {
300     let body_id =
301         tcx.hir.as_local_node_id(def_id).and_then(|node_id| {
302             tcx.hir.maybe_body_owned_by(node_id)
303         });
304
305     let body_id = match body_id {
306         Some(body) => body,
307         None => {
308             debug!("check_unused_unsafe({:?}) - no body found", def_id);
309             return
310         }
311     };
312     let body = tcx.hir.body(body_id);
313     debug!("check_unused_unsafe({:?}, body={:?}, used_unsafe={:?})",
314            def_id, body, used_unsafe);
315
316     let mut visitor =  UnusedUnsafeVisitor { used_unsafe, unsafe_blocks };
317     hir::intravisit::Visitor::visit_body(&mut visitor, body);
318 }
319
320 fn unsafety_check_result<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>, def_id: DefId)
321                                    -> UnsafetyCheckResult
322 {
323     debug!("unsafety_violations({:?})", def_id);
324
325     // NB: this borrow is valid because all the consumers of
326     // `mir_built` force this.
327     let mir = &tcx.mir_built(def_id).borrow();
328
329     let visibility_scope_info = match mir.visibility_scope_info {
330         ClearCrossCrate::Set(ref data) => data,
331         ClearCrossCrate::Clear => {
332             debug!("unsafety_violations: {:?} - remote, skipping", def_id);
333             return UnsafetyCheckResult {
334                 violations: Lrc::new([]),
335                 unsafe_blocks: Lrc::new([])
336             }
337         }
338     };
339
340     let param_env = tcx.param_env(def_id);
341     let mut checker = UnsafetyChecker::new(
342         mir, visibility_scope_info, tcx, param_env);
343     checker.visit_mir(mir);
344
345     check_unused_unsafe(tcx, def_id, &checker.used_unsafe, &mut checker.inherited_blocks);
346     UnsafetyCheckResult {
347         violations: checker.violations.into(),
348         unsafe_blocks: checker.inherited_blocks.into()
349     }
350 }
351
352 fn unsafe_derive_on_repr_packed<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>, def_id: DefId) {
353     let lint_node_id = match tcx.hir.as_local_node_id(def_id) {
354         Some(node_id) => node_id,
355         None => bug!("checking unsafety for non-local def id {:?}", def_id)
356     };
357
358     // FIXME: when we make this a hard error, this should have its
359     // own error code.
360     let message = if !tcx.generics_of(def_id).types.is_empty() {
361         format!("#[derive] can't be used on a #[repr(packed)] struct with \
362                  type parameters (error E0133)")
363     } else {
364         format!("#[derive] can't be used on a non-Copy #[repr(packed)] struct \
365                  (error E0133)")
366     };
367     tcx.lint_node(SAFE_PACKED_BORROWS,
368                   lint_node_id,
369                   tcx.def_span(def_id),
370                   &message);
371 }
372
373 /// Return the NodeId for an enclosing scope that is also `unsafe`
374 fn is_enclosed(tcx: TyCtxt,
375                used_unsafe: &FxHashSet<ast::NodeId>,
376                id: ast::NodeId) -> Option<(String, ast::NodeId)> {
377     let parent_id = tcx.hir.get_parent_node(id);
378     if parent_id != id {
379         if used_unsafe.contains(&parent_id) {
380             Some(("block".to_string(), parent_id))
381         } else if let Some(hir::map::NodeItem(&hir::Item {
382             node: hir::ItemFn(_, fn_unsafety, _, _, _, _),
383             ..
384         })) = tcx.hir.find(parent_id) {
385             match fn_unsafety {
386                 hir::Unsafety::Unsafe => Some(("fn".to_string(), parent_id)),
387                 hir::Unsafety::Normal => None,
388             }
389         } else {
390             is_enclosed(tcx, used_unsafe, parent_id)
391         }
392     } else {
393         None
394     }
395 }
396
397 fn report_unused_unsafe(tcx: TyCtxt, used_unsafe: &FxHashSet<ast::NodeId>, id: ast::NodeId) {
398     let span = tcx.sess.codemap().def_span(tcx.hir.span(id));
399     let msg = "unnecessary `unsafe` block";
400     let mut db = tcx.struct_span_lint_node(UNUSED_UNSAFE, id, span, msg);
401     db.span_label(span, msg);
402     if let Some((kind, id)) = is_enclosed(tcx, used_unsafe, id) {
403         db.span_label(tcx.sess.codemap().def_span(tcx.hir.span(id)),
404                       format!("because it's nested under this `unsafe` {}", kind));
405     }
406     db.emit();
407 }
408
409 fn builtin_derive_def_id<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>, def_id: DefId) -> Option<DefId> {
410     debug!("builtin_derive_def_id({:?})", def_id);
411     if let Some(impl_def_id) = tcx.impl_of_method(def_id) {
412         if tcx.has_attr(impl_def_id, "automatically_derived") {
413             debug!("builtin_derive_def_id({:?}) - is {:?}", def_id, impl_def_id);
414             Some(impl_def_id)
415         } else {
416             debug!("builtin_derive_def_id({:?}) - not automatically derived", def_id);
417             None
418         }
419     } else {
420         debug!("builtin_derive_def_id({:?}) - not a method", def_id);
421         None
422     }
423 }
424
425 pub fn check_unsafety<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>, def_id: DefId) {
426     debug!("check_unsafety({:?})", def_id);
427
428     // closures are handled by their parent fn.
429     if tcx.is_closure(def_id) {
430         return;
431     }
432
433     let UnsafetyCheckResult {
434         violations,
435         unsafe_blocks
436     } = tcx.unsafety_check_result(def_id);
437
438     for &UnsafetyViolation {
439         source_info, description, kind
440     } in violations.iter() {
441         // Report an error.
442         match kind {
443             UnsafetyViolationKind::General => {
444                 struct_span_err!(
445                     tcx.sess, source_info.span, E0133,
446                     "{} requires unsafe function or block", description)
447                     .span_label(source_info.span, &description.as_str()[..])
448                     .emit();
449             }
450             UnsafetyViolationKind::ExternStatic(lint_node_id) => {
451                 tcx.lint_node(SAFE_EXTERN_STATICS,
452                               lint_node_id,
453                               source_info.span,
454                               &format!("{} requires unsafe function or \
455                                         block (error E0133)", &description.as_str()[..]));
456             }
457             UnsafetyViolationKind::BorrowPacked(lint_node_id) => {
458                 if let Some(impl_def_id) = builtin_derive_def_id(tcx, def_id) {
459                     tcx.unsafe_derive_on_repr_packed(impl_def_id);
460                 } else {
461                     tcx.lint_node(SAFE_PACKED_BORROWS,
462                                   lint_node_id,
463                                   source_info.span,
464                                   &format!("{} requires unsafe function or \
465                                             block (error E0133)", &description.as_str()[..]));
466                 }
467             }
468         }
469     }
470
471     let mut unsafe_blocks: Vec<_> = unsafe_blocks.into_iter().collect();
472     unsafe_blocks.sort();
473     let used_unsafe: FxHashSet<_> = unsafe_blocks.iter()
474         .flat_map(|&&(id, used)| if used { Some(id) } else { None })
475         .collect();
476     for &(block_id, is_used) in unsafe_blocks {
477         if !is_used {
478             report_unused_unsafe(tcx, &used_unsafe, block_id);
479         }
480     }
481 }