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.
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.
11 use rustc_data_structures::fx::FxHashSet;
12 use rustc_data_structures::indexed_vec::IndexVec;
13 use rustc_data_structures::sync::Lrc;
15 use rustc::ty::query::Providers;
16 use rustc::ty::{self, TyCtxt};
19 use rustc::hir::def_id::DefId;
20 use rustc::lint::builtin::{SAFE_EXTERN_STATICS, SAFE_PACKED_BORROWS, UNUSED_UNSAFE};
22 use rustc::mir::visit::{PlaceContext, Visitor, MutatingUseContext};
25 use syntax::symbol::Symbol;
26 use syntax::feature_gate::{emit_feature_err, GateIssue};
32 pub struct UnsafetyChecker<'a, 'tcx: 'a> {
35 source_scope_local_data: &'a IndexVec<SourceScope, SourceScopeLocalData>,
36 violations: Vec<UnsafetyViolation>,
37 source_info: SourceInfo,
38 tcx: TyCtxt<'a, 'tcx, 'tcx>,
39 param_env: ty::ParamEnv<'tcx>,
40 /// mark an `unsafe` block as used, so we don't lint it
41 used_unsafe: FxHashSet<ast::NodeId>,
42 inherited_blocks: Vec<(ast::NodeId, bool)>,
45 impl<'a, 'gcx, 'tcx> UnsafetyChecker<'a, 'tcx> {
49 source_scope_local_data: &'a IndexVec<SourceScope, SourceScopeLocalData>,
50 tcx: TyCtxt<'a, 'tcx, 'tcx>,
51 param_env: ty::ParamEnv<'tcx>,
56 source_scope_local_data,
58 source_info: SourceInfo {
60 scope: OUTERMOST_SOURCE_SCOPE
64 used_unsafe: Default::default(),
65 inherited_blocks: vec![],
70 impl<'a, 'tcx> Visitor<'tcx> for UnsafetyChecker<'a, 'tcx> {
71 fn visit_terminator(&mut self,
73 terminator: &Terminator<'tcx>,
76 self.source_info = terminator.source_info;
77 match terminator.kind {
78 TerminatorKind::Goto { .. } |
79 TerminatorKind::SwitchInt { .. } |
80 TerminatorKind::Drop { .. } |
81 TerminatorKind::Yield { .. } |
82 TerminatorKind::Assert { .. } |
83 TerminatorKind::DropAndReplace { .. } |
84 TerminatorKind::GeneratorDrop |
85 TerminatorKind::Resume |
86 TerminatorKind::Abort |
87 TerminatorKind::Return |
88 TerminatorKind::Unreachable |
89 TerminatorKind::FalseEdges { .. } |
90 TerminatorKind::FalseUnwind { .. } => {
91 // safe (at least as emitted during MIR construction)
94 TerminatorKind::Call { ref func, .. } => {
95 let func_ty = func.ty(self.mir, self.tcx);
96 let sig = func_ty.fn_sig(self.tcx);
97 if let hir::Unsafety::Unsafe = sig.unsafety() {
98 self.require_unsafe("call to unsafe function",
99 "consult the function's documentation for information on how to avoid \
100 undefined behavior", UnsafetyViolationKind::GatedConstFnCall)
104 self.super_terminator(block, terminator, location);
107 fn visit_statement(&mut self,
109 statement: &Statement<'tcx>,
112 self.source_info = statement.source_info;
113 match statement.kind {
114 StatementKind::Assign(..) |
115 StatementKind::FakeRead(..) |
116 StatementKind::SetDiscriminant { .. } |
117 StatementKind::StorageLive(..) |
118 StatementKind::StorageDead(..) |
119 StatementKind::Retag { .. } |
120 StatementKind::EscapeToRaw { .. } |
121 StatementKind::AscribeUserType(..) |
122 StatementKind::Nop => {
123 // safe (at least as emitted during MIR construction)
126 StatementKind::InlineAsm { .. } => {
127 self.require_unsafe("use of inline assembly",
128 "inline assembly is entirely unchecked and can cause undefined behavior",
129 UnsafetyViolationKind::General)
132 self.super_statement(block, statement, location);
135 fn visit_rvalue(&mut self,
136 rvalue: &Rvalue<'tcx>,
139 if let &Rvalue::Aggregate(box ref aggregate, _) = rvalue {
141 &AggregateKind::Array(..) |
142 &AggregateKind::Tuple => {}
143 &AggregateKind::Adt(ref def, ..) => {
144 match self.tcx.layout_scalar_valid_range(def.did) {
145 (Bound::Unbounded, Bound::Unbounded) => {},
146 _ => self.require_unsafe(
147 "initializing type with `rustc_layout_scalar_valid_range` attr",
148 "initializing a layout restricted type's field with a value outside \
149 the valid range is undefined behavior",
150 UnsafetyViolationKind::GeneralAndConstFn,
154 &AggregateKind::Closure(def_id, _) |
155 &AggregateKind::Generator(def_id, _, _) => {
156 let UnsafetyCheckResult {
157 violations, unsafe_blocks
158 } = self.tcx.unsafety_check_result(def_id);
159 self.register_violations(&violations, &unsafe_blocks);
163 self.super_rvalue(rvalue, location);
166 fn visit_place(&mut self,
168 context: PlaceContext<'tcx>,
169 location: Location) {
171 &Place::Projection(box Projection {
174 if context.is_borrow() {
175 if util::is_disaligned(self.tcx, self.mir, self.param_env, place) {
176 let source_info = self.source_info;
178 self.source_scope_local_data[source_info.scope].lint_root;
179 self.register_violations(&[UnsafetyViolation {
181 description: Symbol::intern("borrow of packed field").as_interned_str(),
183 Symbol::intern("fields of packed structs might be misaligned: \
184 dereferencing a misaligned pointer or even just \
185 creating a misaligned reference is undefined \
188 kind: UnsafetyViolationKind::BorrowPacked(lint_root)
192 let is_borrow_of_interior_mut = context.is_borrow() && !base
193 .ty(self.mir, self.tcx)
195 .is_freeze(self.tcx, self.param_env, self.source_info.span);
199 // * `&x.field` if `field`'s type has interior mutability
200 // because either of these would allow modifying the layout constrained field and
201 // insert values that violate the layout constraints.
202 if context.is_mutating_use() || is_borrow_of_interior_mut {
203 self.check_mut_borrowing_layout_constrained_field(
204 place, context.is_mutating_use(),
207 let old_source_info = self.source_info;
208 if let &Place::Local(local) = base {
209 if self.mir.local_decls[local].internal {
210 // Internal locals are used in the `move_val_init` desugaring.
211 // We want to check unsafety against the source info of the
212 // desugaring, rather than the source info of the RHS.
213 self.source_info = self.mir.local_decls[local].source_info;
216 let base_ty = base.ty(self.mir, self.tcx).to_ty(self.tcx);
219 self.require_unsafe("dereference of raw pointer",
220 "raw pointers may be NULL, dangling or unaligned; they can violate \
221 aliasing rules and cause data races: all of these are undefined \
222 behavior", UnsafetyViolationKind::General)
226 if context == PlaceContext::MutatingUse(MutatingUseContext::Store) ||
227 context == PlaceContext::MutatingUse(MutatingUseContext::Drop) ||
228 context == PlaceContext::MutatingUse(
229 MutatingUseContext::AsmOutput
232 let elem_ty = match elem {
233 &ProjectionElem::Field(_, ty) => ty,
235 self.source_info.span,
236 "non-field projection {:?} from union?",
239 if elem_ty.moves_by_default(self.tcx, self.param_env,
240 self.source_info.span) {
242 "assignment to non-`Copy` union field",
243 "the previous content of the field will be dropped, which \
244 causes undefined behavior if the field was not properly \
245 initialized", UnsafetyViolationKind::General)
247 // write to non-move union, safe
250 self.require_unsafe("access to union field",
251 "the field may not be properly initialized: using \
252 uninitialized data will cause undefined behavior",
253 UnsafetyViolationKind::General)
259 self.source_info = old_source_info;
261 &Place::Local(..) => {
264 &Place::Promoted(_) => {
265 bug!("unsafety checking should happen before promotion")
267 &Place::Static(box Static { def_id, ty: _ }) => {
268 if self.tcx.is_static(def_id) == Some(hir::Mutability::MutMutable) {
269 self.require_unsafe("use of mutable static",
270 "mutable statics can be mutated by multiple threads: aliasing violations \
271 or data races will cause undefined behavior",
272 UnsafetyViolationKind::General);
273 } else if self.tcx.is_foreign_item(def_id) {
274 let source_info = self.source_info;
276 self.source_scope_local_data[source_info.scope].lint_root;
277 self.register_violations(&[UnsafetyViolation {
279 description: Symbol::intern("use of extern static").as_interned_str(),
281 Symbol::intern("extern statics are not controlled by the Rust type \
282 system: invalid data, aliasing violations or data \
283 races will cause undefined behavior")
285 kind: UnsafetyViolationKind::ExternStatic(lint_root)
290 self.super_place(place, context, location);
294 impl<'a, 'tcx> UnsafetyChecker<'a, 'tcx> {
297 description: &'static str,
298 details: &'static str,
299 kind: UnsafetyViolationKind,
301 let source_info = self.source_info;
302 self.register_violations(&[UnsafetyViolation {
304 description: Symbol::intern(description).as_interned_str(),
305 details: Symbol::intern(details).as_interned_str(),
310 fn register_violations(&mut self,
311 violations: &[UnsafetyViolation],
312 unsafe_blocks: &[(ast::NodeId, bool)]) {
313 let safety = self.source_scope_local_data[self.source_info.scope].safety;
314 let within_unsafe = match (safety, self.min_const_fn) {
315 // Erring on the safe side, pun intended
316 (Safety::BuiltinUnsafe, true) |
317 // mir building encodes const fn bodies as safe, even for `const unsafe fn`
318 (Safety::FnUnsafe, true) => bug!("const unsafe fn body treated as inherently unsafe"),
319 // `unsafe` blocks are required in safe code
320 (Safety::Safe, _) => {
321 for violation in violations {
322 let mut violation = violation.clone();
323 match violation.kind {
324 UnsafetyViolationKind::GeneralAndConstFn |
325 UnsafetyViolationKind::General => {},
326 UnsafetyViolationKind::BorrowPacked(_) |
327 UnsafetyViolationKind::ExternStatic(_) => if self.min_const_fn {
328 // const fns don't need to be backwards compatible and can
329 // emit these violations as a hard error instead of a backwards
331 violation.kind = UnsafetyViolationKind::General;
333 UnsafetyViolationKind::GatedConstFnCall => {
334 // safe code can't call unsafe const fns, this `UnsafetyViolationKind`
335 // is only relevant for `Safety::ExplicitUnsafe` in `unsafe const fn`s
336 violation.kind = UnsafetyViolationKind::General;
339 if !self.violations.contains(&violation) {
340 self.violations.push(violation)
345 // regular `unsafe` function bodies allow unsafe without additional unsafe blocks
346 (Safety::BuiltinUnsafe, false) | (Safety::FnUnsafe, false) => true,
347 (Safety::ExplicitUnsafe(node_id), _) => {
348 // mark unsafe block as used if there are any unsafe operations inside
349 if !violations.is_empty() {
350 self.used_unsafe.insert(node_id);
352 // only some unsafety is allowed in const fn
353 if self.min_const_fn {
354 for violation in violations {
355 match violation.kind {
357 UnsafetyViolationKind::GatedConstFnCall => {
358 // if `#![feature(min_const_unsafe_fn)]` is active
359 if !self.tcx.sess.features_untracked().min_const_unsafe_fn {
360 if !self.violations.contains(&violation) {
361 self.violations.push(violation.clone())
365 // these unsafe things are stable in const fn
366 UnsafetyViolationKind::GeneralAndConstFn => {},
367 UnsafetyViolationKind::General |
368 UnsafetyViolationKind::BorrowPacked(_) |
369 UnsafetyViolationKind::ExternStatic(_) => {
370 let mut violation = violation.clone();
371 // const fns don't need to be backwards compatible and can
372 // emit these violations as a hard error instead of a backwards
374 violation.kind = UnsafetyViolationKind::General;
375 if !self.violations.contains(&violation) {
376 self.violations.push(violation)
385 self.inherited_blocks.extend(unsafe_blocks.iter().map(|&(node_id, is_used)| {
386 (node_id, is_used && !within_unsafe)
389 fn check_mut_borrowing_layout_constrained_field(
391 mut place: &Place<'tcx>,
394 while let &Place::Projection(box Projection {
398 ProjectionElem::Field(..) => {
399 let ty = base.ty(&self.mir.local_decls, self.tcx).to_ty(self.tcx);
401 ty::Adt(def, _) => match self.tcx.layout_scalar_valid_range(def.did) {
402 (Bound::Unbounded, Bound::Unbounded) => {},
404 let (description, details) = if is_mut_use {
406 "mutation of layout constrained field",
407 "mutating layout constrained fields cannot statically be \
408 checked for valid values",
412 "borrow of layout constrained field with interior \
414 "references to fields of layout constrained fields \
415 lose the constraints. Coupled with interior mutability, \
416 the field can be changed to invalid values",
419 let source_info = self.source_info;
420 self.register_violations(&[UnsafetyViolation {
422 description: Symbol::intern(description).as_interned_str(),
423 details: Symbol::intern(details).as_interned_str(),
424 kind: UnsafetyViolationKind::GeneralAndConstFn,
438 pub(crate) fn provide(providers: &mut Providers) {
439 *providers = Providers {
440 unsafety_check_result,
441 unsafe_derive_on_repr_packed,
446 struct UnusedUnsafeVisitor<'a> {
447 used_unsafe: &'a FxHashSet<ast::NodeId>,
448 unsafe_blocks: &'a mut Vec<(ast::NodeId, bool)>,
451 impl<'a, 'tcx> hir::intravisit::Visitor<'tcx> for UnusedUnsafeVisitor<'a> {
452 fn nested_visit_map<'this>(&'this mut self) ->
453 hir::intravisit::NestedVisitorMap<'this, 'tcx>
455 hir::intravisit::NestedVisitorMap::None
458 fn visit_block(&mut self, block: &'tcx hir::Block) {
459 hir::intravisit::walk_block(self, block);
461 if let hir::UnsafeBlock(hir::UserProvided) = block.rules {
462 self.unsafe_blocks.push((block.id, self.used_unsafe.contains(&block.id)));
467 fn check_unused_unsafe<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>,
469 used_unsafe: &FxHashSet<ast::NodeId>,
470 unsafe_blocks: &'a mut Vec<(ast::NodeId, bool)>)
473 tcx.hir.as_local_node_id(def_id).and_then(|node_id| {
474 tcx.hir.maybe_body_owned_by(node_id)
477 let body_id = match body_id {
480 debug!("check_unused_unsafe({:?}) - no body found", def_id);
484 let body = tcx.hir.body(body_id);
485 debug!("check_unused_unsafe({:?}, body={:?}, used_unsafe={:?})",
486 def_id, body, used_unsafe);
488 let mut visitor = UnusedUnsafeVisitor { used_unsafe, unsafe_blocks };
489 hir::intravisit::Visitor::visit_body(&mut visitor, body);
492 fn unsafety_check_result<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>, def_id: DefId)
493 -> UnsafetyCheckResult
495 debug!("unsafety_violations({:?})", def_id);
497 // NB: this borrow is valid because all the consumers of
498 // `mir_built` force this.
499 let mir = &tcx.mir_built(def_id).borrow();
501 let source_scope_local_data = match mir.source_scope_local_data {
502 ClearCrossCrate::Set(ref data) => data,
503 ClearCrossCrate::Clear => {
504 debug!("unsafety_violations: {:?} - remote, skipping", def_id);
505 return UnsafetyCheckResult {
506 violations: Lrc::new([]),
507 unsafe_blocks: Lrc::new([])
512 let param_env = tcx.param_env(def_id);
513 let mut checker = UnsafetyChecker::new(
514 tcx.is_const_fn(def_id) && tcx.is_min_const_fn(def_id),
515 mir, source_scope_local_data, tcx, param_env);
516 checker.visit_mir(mir);
518 check_unused_unsafe(tcx, def_id, &checker.used_unsafe, &mut checker.inherited_blocks);
519 UnsafetyCheckResult {
520 violations: checker.violations.into(),
521 unsafe_blocks: checker.inherited_blocks.into()
525 fn unsafe_derive_on_repr_packed<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>, def_id: DefId) {
526 let lint_node_id = match tcx.hir.as_local_node_id(def_id) {
527 Some(node_id) => node_id,
528 None => bug!("checking unsafety for non-local def id {:?}", def_id)
531 // FIXME: when we make this a hard error, this should have its
533 let message = if tcx.generics_of(def_id).own_counts().types != 0 {
534 "#[derive] can't be used on a #[repr(packed)] struct with \
535 type parameters (error E0133)".to_string()
537 "#[derive] can't be used on a #[repr(packed)] struct that \
538 does not derive Copy (error E0133)".to_string()
540 tcx.lint_node(SAFE_PACKED_BORROWS,
542 tcx.def_span(def_id),
546 /// Return the NodeId for an enclosing scope that is also `unsafe`
547 fn is_enclosed(tcx: TyCtxt,
548 used_unsafe: &FxHashSet<ast::NodeId>,
549 id: ast::NodeId) -> Option<(String, ast::NodeId)> {
550 let parent_id = tcx.hir.get_parent_node(id);
552 if used_unsafe.contains(&parent_id) {
553 Some(("block".to_string(), parent_id))
554 } else if let Some(Node::Item(&hir::Item {
555 node: hir::ItemKind::Fn(_, header, _, _),
557 })) = tcx.hir.find(parent_id) {
558 match header.unsafety {
559 hir::Unsafety::Unsafe => Some(("fn".to_string(), parent_id)),
560 hir::Unsafety::Normal => None,
563 is_enclosed(tcx, used_unsafe, parent_id)
570 fn report_unused_unsafe(tcx: TyCtxt, used_unsafe: &FxHashSet<ast::NodeId>, id: ast::NodeId) {
571 let span = tcx.sess.source_map().def_span(tcx.hir.span(id));
572 let msg = "unnecessary `unsafe` block";
573 let mut db = tcx.struct_span_lint_node(UNUSED_UNSAFE, id, span, msg);
574 db.span_label(span, msg);
575 if let Some((kind, id)) = is_enclosed(tcx, used_unsafe, id) {
576 db.span_label(tcx.sess.source_map().def_span(tcx.hir.span(id)),
577 format!("because it's nested under this `unsafe` {}", kind));
582 fn builtin_derive_def_id<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>, def_id: DefId) -> Option<DefId> {
583 debug!("builtin_derive_def_id({:?})", def_id);
584 if let Some(impl_def_id) = tcx.impl_of_method(def_id) {
585 if tcx.has_attr(impl_def_id, "automatically_derived") {
586 debug!("builtin_derive_def_id({:?}) - is {:?}", def_id, impl_def_id);
589 debug!("builtin_derive_def_id({:?}) - not automatically derived", def_id);
593 debug!("builtin_derive_def_id({:?}) - not a method", def_id);
598 pub fn check_unsafety<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>, def_id: DefId) {
599 debug!("check_unsafety({:?})", def_id);
601 // closures are handled by their parent fn.
602 if tcx.is_closure(def_id) {
606 let UnsafetyCheckResult {
609 } = tcx.unsafety_check_result(def_id);
611 for &UnsafetyViolation {
612 source_info, description, details, kind
613 } in violations.iter() {
616 UnsafetyViolationKind::General if tcx.is_min_const_fn(def_id) => {
617 tcx.sess.struct_span_err(
619 &format!("{} is unsafe and unsafe operations \
620 are not allowed in const fn", description))
621 .span_label(source_info.span, &description.as_str()[..])
622 .note(&details.as_str()[..])
625 UnsafetyViolationKind::GeneralAndConstFn |
626 UnsafetyViolationKind::General => {
628 tcx.sess, source_info.span, E0133,
629 "{} is unsafe and requires unsafe function or block", description)
630 .span_label(source_info.span, &description.as_str()[..])
631 .note(&details.as_str()[..])
634 UnsafetyViolationKind::GatedConstFnCall => {
636 &tcx.sess.parse_sess,
637 "min_const_unsafe_fn",
640 "calls to `const unsafe fn` in const fns are unstable",
644 UnsafetyViolationKind::ExternStatic(lint_node_id) => {
645 tcx.lint_node_note(SAFE_EXTERN_STATICS,
648 &format!("{} is unsafe and requires unsafe function or block \
649 (error E0133)", &description.as_str()[..]),
650 &details.as_str()[..]);
652 UnsafetyViolationKind::BorrowPacked(lint_node_id) => {
653 if let Some(impl_def_id) = builtin_derive_def_id(tcx, def_id) {
654 tcx.unsafe_derive_on_repr_packed(impl_def_id);
656 tcx.lint_node_note(SAFE_PACKED_BORROWS,
659 &format!("{} is unsafe and requires unsafe function or block \
660 (error E0133)", &description.as_str()[..]),
661 &details.as_str()[..]);
667 let mut unsafe_blocks: Vec<_> = unsafe_blocks.into_iter().collect();
668 unsafe_blocks.sort();
669 let used_unsafe: FxHashSet<_> = unsafe_blocks.iter()
670 .flat_map(|&&(id, used)| if used { Some(id) } else { None })
672 for &(block_id, is_used) in unsafe_blocks {
674 report_unused_unsafe(tcx, &used_unsafe, block_id);