]> git.lizzy.rs Git - rust.git/blob - src/librustc_mir/transform/check_unsafety.rs
Rollup merge of #56024 - oli-obk:const_fn_collect_inner, r=michaelwoerister
[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::query::Providers;
16 use rustc::ty::{self, TyCtxt};
17 use rustc::hir;
18 use rustc::hir::Node;
19 use rustc::hir::def_id::DefId;
20 use rustc::lint::builtin::{SAFE_EXTERN_STATICS, SAFE_PACKED_BORROWS, UNUSED_UNSAFE};
21 use rustc::mir::*;
22 use rustc::mir::visit::{PlaceContext, Visitor, MutatingUseContext};
23
24 use syntax::ast;
25 use syntax::symbol::Symbol;
26
27 use util;
28
29 pub struct UnsafetyChecker<'a, 'tcx: 'a> {
30     mir: &'a Mir<'tcx>,
31     min_const_fn: bool,
32     source_scope_local_data: &'a IndexVec<SourceScope, SourceScopeLocalData>,
33     violations: Vec<UnsafetyViolation>,
34     source_info: SourceInfo,
35     tcx: TyCtxt<'a, 'tcx, 'tcx>,
36     param_env: ty::ParamEnv<'tcx>,
37     used_unsafe: FxHashSet<ast::NodeId>,
38     inherited_blocks: Vec<(ast::NodeId, bool)>,
39 }
40
41 impl<'a, 'gcx, 'tcx> UnsafetyChecker<'a, 'tcx> {
42     fn new(
43         min_const_fn: bool,
44         mir: &'a Mir<'tcx>,
45         source_scope_local_data: &'a IndexVec<SourceScope, SourceScopeLocalData>,
46         tcx: TyCtxt<'a, 'tcx, 'tcx>,
47         param_env: ty::ParamEnv<'tcx>,
48     ) -> Self {
49         Self {
50             mir,
51             min_const_fn,
52             source_scope_local_data,
53             violations: vec![],
54             source_info: SourceInfo {
55                 span: mir.span,
56                 scope: OUTERMOST_SOURCE_SCOPE
57             },
58             tcx,
59             param_env,
60             used_unsafe: Default::default(),
61             inherited_blocks: vec![],
62         }
63     }
64 }
65
66 impl<'a, 'tcx> Visitor<'tcx> for UnsafetyChecker<'a, 'tcx> {
67     fn visit_terminator(&mut self,
68                         block: BasicBlock,
69                         terminator: &Terminator<'tcx>,
70                         location: Location)
71     {
72         self.source_info = terminator.source_info;
73         match terminator.kind {
74             TerminatorKind::Goto { .. } |
75             TerminatorKind::SwitchInt { .. } |
76             TerminatorKind::Drop { .. } |
77             TerminatorKind::Yield { .. } |
78             TerminatorKind::Assert { .. } |
79             TerminatorKind::DropAndReplace { .. } |
80             TerminatorKind::GeneratorDrop |
81             TerminatorKind::Resume |
82             TerminatorKind::Abort |
83             TerminatorKind::Return |
84             TerminatorKind::Unreachable |
85             TerminatorKind::FalseEdges { .. } |
86             TerminatorKind::FalseUnwind { .. } => {
87                 // safe (at least as emitted during MIR construction)
88             }
89
90             TerminatorKind::Call { ref func, .. } => {
91                 let func_ty = func.ty(self.mir, self.tcx);
92                 let sig = func_ty.fn_sig(self.tcx);
93                 if let hir::Unsafety::Unsafe = sig.unsafety() {
94                     self.require_unsafe("call to unsafe function",
95                         "consult the function's documentation for information on how to avoid \
96                          undefined behavior")
97                 }
98             }
99         }
100         self.super_terminator(block, terminator, location);
101     }
102
103     fn visit_statement(&mut self,
104                        block: BasicBlock,
105                        statement: &Statement<'tcx>,
106                        location: Location)
107     {
108         self.source_info = statement.source_info;
109         match statement.kind {
110             StatementKind::Assign(..) |
111             StatementKind::FakeRead(..) |
112             StatementKind::SetDiscriminant { .. } |
113             StatementKind::StorageLive(..) |
114             StatementKind::StorageDead(..) |
115             StatementKind::Retag { .. } |
116             StatementKind::EscapeToRaw { .. } |
117             StatementKind::AscribeUserType(..) |
118             StatementKind::Nop => {
119                 // safe (at least as emitted during MIR construction)
120             }
121
122             StatementKind::InlineAsm { .. } => {
123                 self.require_unsafe("use of inline assembly",
124                     "inline assembly is entirely unchecked and can cause undefined behavior")
125             },
126         }
127         self.super_statement(block, statement, location);
128     }
129
130     fn visit_rvalue(&mut self,
131                     rvalue: &Rvalue<'tcx>,
132                     location: Location)
133     {
134         if let &Rvalue::Aggregate(box ref aggregate, _) = rvalue {
135             match aggregate {
136                 &AggregateKind::Array(..) |
137                 &AggregateKind::Tuple |
138                 &AggregateKind::Adt(..) => {}
139                 &AggregateKind::Closure(def_id, _) |
140                 &AggregateKind::Generator(def_id, _, _) => {
141                     let UnsafetyCheckResult {
142                         violations, unsafe_blocks
143                     } = self.tcx.unsafety_check_result(def_id);
144                     self.register_violations(&violations, &unsafe_blocks);
145                 }
146             }
147         }
148         self.super_rvalue(rvalue, location);
149     }
150
151     fn visit_place(&mut self,
152                     place: &Place<'tcx>,
153                     context: PlaceContext<'tcx>,
154                     location: Location) {
155         if context.is_borrow() {
156             if util::is_disaligned(self.tcx, self.mir, self.param_env, place) {
157                 let source_info = self.source_info;
158                 let lint_root =
159                     self.source_scope_local_data[source_info.scope].lint_root;
160                 self.register_violations(&[UnsafetyViolation {
161                     source_info,
162                     description: Symbol::intern("borrow of packed field").as_interned_str(),
163                     details:
164                         Symbol::intern("fields of packed structs might be misaligned: \
165                                         dereferencing a misaligned pointer or even just creating a \
166                                         misaligned reference is undefined behavior")
167                             .as_interned_str(),
168                     kind: UnsafetyViolationKind::BorrowPacked(lint_root)
169                 }], &[]);
170             }
171         }
172
173         match place {
174             &Place::Projection(box Projection {
175                 ref base, ref elem
176             }) => {
177                 let old_source_info = self.source_info;
178                 if let &Place::Local(local) = base {
179                     if self.mir.local_decls[local].internal {
180                         // Internal locals are used in the `move_val_init` desugaring.
181                         // We want to check unsafety against the source info of the
182                         // desugaring, rather than the source info of the RHS.
183                         self.source_info = self.mir.local_decls[local].source_info;
184                     }
185                 }
186                 let base_ty = base.ty(self.mir, self.tcx).to_ty(self.tcx);
187                 match base_ty.sty {
188                     ty::RawPtr(..) => {
189                         self.require_unsafe("dereference of raw pointer",
190                             "raw pointers may be NULL, dangling or unaligned; they can violate \
191                              aliasing rules and cause data races: all of these are undefined \
192                              behavior")
193                     }
194                     ty::Adt(adt, _) => {
195                         if adt.is_union() {
196                             if context == PlaceContext::MutatingUse(MutatingUseContext::Store) ||
197                                 context == PlaceContext::MutatingUse(MutatingUseContext::Drop) ||
198                                 context == PlaceContext::MutatingUse(
199                                     MutatingUseContext::AsmOutput
200                                 )
201                             {
202                                 let elem_ty = match elem {
203                                     &ProjectionElem::Field(_, ty) => ty,
204                                     _ => span_bug!(
205                                         self.source_info.span,
206                                         "non-field projection {:?} from union?",
207                                         place)
208                                 };
209                                 if elem_ty.moves_by_default(self.tcx, self.param_env,
210                                                             self.source_info.span) {
211                                     self.require_unsafe(
212                                         "assignment to non-`Copy` union field",
213                                         "the previous content of the field will be dropped, which \
214                                          causes undefined behavior if the field was not properly \
215                                          initialized")
216                                 } else {
217                                     // write to non-move union, safe
218                                 }
219                             } else {
220                                 self.require_unsafe("access to union field",
221                                     "the field may not be properly initialized: using \
222                                      uninitialized data will cause undefined behavior")
223                             }
224                         }
225                     }
226                     _ => {}
227                 }
228                 self.source_info = old_source_info;
229             }
230             &Place::Local(..) => {
231                 // locals are safe
232             }
233             &Place::Promoted(_) => {
234                 bug!("unsafety checking should happen before promotion")
235             }
236             &Place::Static(box Static { def_id, ty: _ }) => {
237                 if self.tcx.is_static(def_id) == Some(hir::Mutability::MutMutable) {
238                     self.require_unsafe("use of mutable static",
239                         "mutable statics can be mutated by multiple threads: aliasing violations \
240                          or data races will cause undefined behavior");
241                 } else if self.tcx.is_foreign_item(def_id) {
242                     let source_info = self.source_info;
243                     let lint_root =
244                         self.source_scope_local_data[source_info.scope].lint_root;
245                     self.register_violations(&[UnsafetyViolation {
246                         source_info,
247                         description: Symbol::intern("use of extern static").as_interned_str(),
248                         details:
249                             Symbol::intern("extern statics are not controlled by the Rust type \
250                                             system: invalid data, aliasing violations or data \
251                                             races will cause undefined behavior")
252                                 .as_interned_str(),
253                         kind: UnsafetyViolationKind::ExternStatic(lint_root)
254                     }], &[]);
255                 }
256             }
257         };
258         self.super_place(place, context, location);
259     }
260 }
261
262 impl<'a, 'tcx> UnsafetyChecker<'a, 'tcx> {
263     fn require_unsafe(&mut self,
264                       description: &'static str,
265                       details: &'static str)
266     {
267         let source_info = self.source_info;
268         self.register_violations(&[UnsafetyViolation {
269             source_info,
270             description: Symbol::intern(description).as_interned_str(),
271             details: Symbol::intern(details).as_interned_str(),
272             kind: UnsafetyViolationKind::General,
273         }], &[]);
274     }
275
276     fn register_violations(&mut self,
277                            violations: &[UnsafetyViolation],
278                            unsafe_blocks: &[(ast::NodeId, bool)]) {
279         if self.min_const_fn {
280             for violation in violations {
281                 let mut violation = violation.clone();
282                 violation.kind = UnsafetyViolationKind::MinConstFn;
283                 if !self.violations.contains(&violation) {
284                     self.violations.push(violation)
285                 }
286             }
287         }
288         let within_unsafe = match self.source_scope_local_data[self.source_info.scope].safety {
289             Safety::Safe => {
290                 for violation in violations {
291                     if !self.violations.contains(violation) {
292                         self.violations.push(violation.clone())
293                     }
294                 }
295                 false
296             }
297             Safety::BuiltinUnsafe | Safety::FnUnsafe => true,
298             Safety::ExplicitUnsafe(node_id) => {
299                 if !violations.is_empty() {
300                     self.used_unsafe.insert(node_id);
301                 }
302                 true
303             }
304         };
305         self.inherited_blocks.extend(unsafe_blocks.iter().map(|&(node_id, is_used)| {
306             (node_id, is_used && !within_unsafe)
307         }));
308     }
309 }
310
311 pub(crate) fn provide(providers: &mut Providers) {
312     *providers = Providers {
313         unsafety_check_result,
314         unsafe_derive_on_repr_packed,
315         ..*providers
316     };
317 }
318
319 struct UnusedUnsafeVisitor<'a> {
320     used_unsafe: &'a FxHashSet<ast::NodeId>,
321     unsafe_blocks: &'a mut Vec<(ast::NodeId, bool)>,
322 }
323
324 impl<'a, 'tcx> hir::intravisit::Visitor<'tcx> for UnusedUnsafeVisitor<'a> {
325     fn nested_visit_map<'this>(&'this mut self) ->
326         hir::intravisit::NestedVisitorMap<'this, 'tcx>
327     {
328         hir::intravisit::NestedVisitorMap::None
329     }
330
331     fn visit_block(&mut self, block: &'tcx hir::Block) {
332         hir::intravisit::walk_block(self, block);
333
334         if let hir::UnsafeBlock(hir::UserProvided) = block.rules {
335             self.unsafe_blocks.push((block.id, self.used_unsafe.contains(&block.id)));
336         }
337     }
338 }
339
340 fn check_unused_unsafe<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>,
341                                  def_id: DefId,
342                                  used_unsafe: &FxHashSet<ast::NodeId>,
343                                  unsafe_blocks: &'a mut Vec<(ast::NodeId, bool)>)
344 {
345     let body_id =
346         tcx.hir.as_local_node_id(def_id).and_then(|node_id| {
347             tcx.hir.maybe_body_owned_by(node_id)
348         });
349
350     let body_id = match body_id {
351         Some(body) => body,
352         None => {
353             debug!("check_unused_unsafe({:?}) - no body found", def_id);
354             return
355         }
356     };
357     let body = tcx.hir.body(body_id);
358     debug!("check_unused_unsafe({:?}, body={:?}, used_unsafe={:?})",
359            def_id, body, used_unsafe);
360
361     let mut visitor =  UnusedUnsafeVisitor { used_unsafe, unsafe_blocks };
362     hir::intravisit::Visitor::visit_body(&mut visitor, body);
363 }
364
365 fn unsafety_check_result<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>, def_id: DefId)
366                                    -> UnsafetyCheckResult
367 {
368     debug!("unsafety_violations({:?})", def_id);
369
370     // NB: this borrow is valid because all the consumers of
371     // `mir_built` force this.
372     let mir = &tcx.mir_built(def_id).borrow();
373
374     let source_scope_local_data = match mir.source_scope_local_data {
375         ClearCrossCrate::Set(ref data) => data,
376         ClearCrossCrate::Clear => {
377             debug!("unsafety_violations: {:?} - remote, skipping", def_id);
378             return UnsafetyCheckResult {
379                 violations: Lrc::new([]),
380                 unsafe_blocks: Lrc::new([])
381             }
382         }
383     };
384
385     let param_env = tcx.param_env(def_id);
386     let mut checker = UnsafetyChecker::new(
387         tcx.is_const_fn(def_id) && tcx.is_min_const_fn(def_id),
388         mir, source_scope_local_data, tcx, param_env);
389     checker.visit_mir(mir);
390
391     check_unused_unsafe(tcx, def_id, &checker.used_unsafe, &mut checker.inherited_blocks);
392     UnsafetyCheckResult {
393         violations: checker.violations.into(),
394         unsafe_blocks: checker.inherited_blocks.into()
395     }
396 }
397
398 fn unsafe_derive_on_repr_packed<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>, def_id: DefId) {
399     let lint_node_id = match tcx.hir.as_local_node_id(def_id) {
400         Some(node_id) => node_id,
401         None => bug!("checking unsafety for non-local def id {:?}", def_id)
402     };
403
404     // FIXME: when we make this a hard error, this should have its
405     // own error code.
406     let message = if tcx.generics_of(def_id).own_counts().types != 0 {
407         "#[derive] can't be used on a #[repr(packed)] struct with \
408          type parameters (error E0133)".to_string()
409     } else {
410         "#[derive] can't be used on a #[repr(packed)] struct that \
411          does not derive Copy (error E0133)".to_string()
412     };
413     tcx.lint_node(SAFE_PACKED_BORROWS,
414                   lint_node_id,
415                   tcx.def_span(def_id),
416                   &message);
417 }
418
419 /// Return the NodeId for an enclosing scope that is also `unsafe`
420 fn is_enclosed(tcx: TyCtxt,
421                used_unsafe: &FxHashSet<ast::NodeId>,
422                id: ast::NodeId) -> Option<(String, ast::NodeId)> {
423     let parent_id = tcx.hir.get_parent_node(id);
424     if parent_id != id {
425         if used_unsafe.contains(&parent_id) {
426             Some(("block".to_string(), parent_id))
427         } else if let Some(Node::Item(&hir::Item {
428             node: hir::ItemKind::Fn(_, header, _, _),
429             ..
430         })) = tcx.hir.find(parent_id) {
431             match header.unsafety {
432                 hir::Unsafety::Unsafe => Some(("fn".to_string(), parent_id)),
433                 hir::Unsafety::Normal => None,
434             }
435         } else {
436             is_enclosed(tcx, used_unsafe, parent_id)
437         }
438     } else {
439         None
440     }
441 }
442
443 fn report_unused_unsafe(tcx: TyCtxt, used_unsafe: &FxHashSet<ast::NodeId>, id: ast::NodeId) {
444     let span = tcx.sess.source_map().def_span(tcx.hir.span(id));
445     let msg = "unnecessary `unsafe` block";
446     let mut db = tcx.struct_span_lint_node(UNUSED_UNSAFE, id, span, msg);
447     db.span_label(span, msg);
448     if let Some((kind, id)) = is_enclosed(tcx, used_unsafe, id) {
449         db.span_label(tcx.sess.source_map().def_span(tcx.hir.span(id)),
450                       format!("because it's nested under this `unsafe` {}", kind));
451     }
452     db.emit();
453 }
454
455 fn builtin_derive_def_id<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>, def_id: DefId) -> Option<DefId> {
456     debug!("builtin_derive_def_id({:?})", def_id);
457     if let Some(impl_def_id) = tcx.impl_of_method(def_id) {
458         if tcx.has_attr(impl_def_id, "automatically_derived") {
459             debug!("builtin_derive_def_id({:?}) - is {:?}", def_id, impl_def_id);
460             Some(impl_def_id)
461         } else {
462             debug!("builtin_derive_def_id({:?}) - not automatically derived", def_id);
463             None
464         }
465     } else {
466         debug!("builtin_derive_def_id({:?}) - not a method", def_id);
467         None
468     }
469 }
470
471 pub fn check_unsafety<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>, def_id: DefId) {
472     debug!("check_unsafety({:?})", def_id);
473
474     // closures are handled by their parent fn.
475     if tcx.is_closure(def_id) {
476         return;
477     }
478
479     let UnsafetyCheckResult {
480         violations,
481         unsafe_blocks
482     } = tcx.unsafety_check_result(def_id);
483
484     for &UnsafetyViolation {
485         source_info, description, details, kind
486     } in violations.iter() {
487         // Report an error.
488         match kind {
489             UnsafetyViolationKind::General => {
490                 struct_span_err!(
491                     tcx.sess, source_info.span, E0133,
492                     "{} is unsafe and requires unsafe function or block", description)
493                     .span_label(source_info.span, &description.as_str()[..])
494                     .note(&details.as_str()[..])
495                     .emit();
496             }
497             UnsafetyViolationKind::MinConstFn => {
498                 tcx.sess.struct_span_err(
499                     source_info.span,
500                     &format!("{} is unsafe and unsafe operations \
501                             are not allowed in const fn", description))
502                     .span_label(source_info.span, &description.as_str()[..])
503                     .note(&details.as_str()[..])
504                     .emit();
505             }
506             UnsafetyViolationKind::ExternStatic(lint_node_id) => {
507                 tcx.lint_node_note(SAFE_EXTERN_STATICS,
508                               lint_node_id,
509                               source_info.span,
510                               &format!("{} is unsafe and requires unsafe function or block \
511                                         (error E0133)", &description.as_str()[..]),
512                               &details.as_str()[..]);
513             }
514             UnsafetyViolationKind::BorrowPacked(lint_node_id) => {
515                 if let Some(impl_def_id) = builtin_derive_def_id(tcx, def_id) {
516                     tcx.unsafe_derive_on_repr_packed(impl_def_id);
517                 } else {
518                     tcx.lint_node_note(SAFE_PACKED_BORROWS,
519                                   lint_node_id,
520                                   source_info.span,
521                                   &format!("{} is unsafe and requires unsafe function or block \
522                                             (error E0133)", &description.as_str()[..]),
523                                   &details.as_str()[..]);
524                 }
525             }
526         }
527     }
528
529     let mut unsafe_blocks: Vec<_> = unsafe_blocks.into_iter().collect();
530     unsafe_blocks.sort();
531     let used_unsafe: FxHashSet<_> = unsafe_blocks.iter()
532         .flat_map(|&&(id, used)| if used { Some(id) } else { None })
533         .collect();
534     for &(block_id, is_used) in unsafe_blocks {
535         if !is_used {
536             report_unused_unsafe(tcx, &used_unsafe, block_id);
537         }
538     }
539 }