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