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