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