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 let min_const_unsafe_fn = self.tcx.features().min_const_unsafe_fn;
355 for violation in violations {
356 match violation.kind {
357 UnsafetyViolationKind::GatedConstFnCall if min_const_unsafe_fn => {
358 // these function calls to unsafe functions are allowed
359 // if `#![feature(min_const_unsafe_fn)]` is active
361 UnsafetyViolationKind::GatedConstFnCall => {
362 // without the feature gate, we report errors
363 if !self.violations.contains(&violation) {
364 self.violations.push(violation.clone())
367 // these unsafe things are stable in const fn
368 UnsafetyViolationKind::GeneralAndConstFn => {},
369 // these things are forbidden in const fns
370 UnsafetyViolationKind::General |
371 UnsafetyViolationKind::BorrowPacked(_) |
372 UnsafetyViolationKind::ExternStatic(_) => {
373 let mut violation = violation.clone();
374 // const fns don't need to be backwards compatible and can
375 // emit these violations as a hard error instead of a backwards
377 violation.kind = UnsafetyViolationKind::General;
378 if !self.violations.contains(&violation) {
379 self.violations.push(violation)
388 self.inherited_blocks.extend(unsafe_blocks.iter().map(|&(node_id, is_used)| {
389 (node_id, is_used && !within_unsafe)
392 fn check_mut_borrowing_layout_constrained_field(
394 mut place: &Place<'tcx>,
397 while let &Place::Projection(box Projection {
401 ProjectionElem::Field(..) => {
402 let ty = base.ty(&self.mir.local_decls, self.tcx).to_ty(self.tcx);
404 ty::Adt(def, _) => match self.tcx.layout_scalar_valid_range(def.did) {
405 (Bound::Unbounded, Bound::Unbounded) => {},
407 let (description, details) = if is_mut_use {
409 "mutation of layout constrained field",
410 "mutating layout constrained fields cannot statically be \
411 checked for valid values",
415 "borrow of layout constrained field with interior \
417 "references to fields of layout constrained fields \
418 lose the constraints. Coupled with interior mutability, \
419 the field can be changed to invalid values",
422 let source_info = self.source_info;
423 self.register_violations(&[UnsafetyViolation {
425 description: Symbol::intern(description).as_interned_str(),
426 details: Symbol::intern(details).as_interned_str(),
427 kind: UnsafetyViolationKind::GeneralAndConstFn,
441 pub(crate) fn provide(providers: &mut Providers) {
442 *providers = Providers {
443 unsafety_check_result,
444 unsafe_derive_on_repr_packed,
449 struct UnusedUnsafeVisitor<'a> {
450 used_unsafe: &'a FxHashSet<ast::NodeId>,
451 unsafe_blocks: &'a mut Vec<(ast::NodeId, bool)>,
454 impl<'a, 'tcx> hir::intravisit::Visitor<'tcx> for UnusedUnsafeVisitor<'a> {
455 fn nested_visit_map<'this>(&'this mut self) ->
456 hir::intravisit::NestedVisitorMap<'this, 'tcx>
458 hir::intravisit::NestedVisitorMap::None
461 fn visit_block(&mut self, block: &'tcx hir::Block) {
462 hir::intravisit::walk_block(self, block);
464 if let hir::UnsafeBlock(hir::UserProvided) = block.rules {
465 self.unsafe_blocks.push((block.id, self.used_unsafe.contains(&block.id)));
470 fn check_unused_unsafe<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>,
472 used_unsafe: &FxHashSet<ast::NodeId>,
473 unsafe_blocks: &'a mut Vec<(ast::NodeId, bool)>)
476 tcx.hir.as_local_node_id(def_id).and_then(|node_id| {
477 tcx.hir.maybe_body_owned_by(node_id)
480 let body_id = match body_id {
483 debug!("check_unused_unsafe({:?}) - no body found", def_id);
487 let body = tcx.hir.body(body_id);
488 debug!("check_unused_unsafe({:?}, body={:?}, used_unsafe={:?})",
489 def_id, body, used_unsafe);
491 let mut visitor = UnusedUnsafeVisitor { used_unsafe, unsafe_blocks };
492 hir::intravisit::Visitor::visit_body(&mut visitor, body);
495 fn unsafety_check_result<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>, def_id: DefId)
496 -> UnsafetyCheckResult
498 debug!("unsafety_violations({:?})", def_id);
500 // NB: this borrow is valid because all the consumers of
501 // `mir_built` force this.
502 let mir = &tcx.mir_built(def_id).borrow();
504 let source_scope_local_data = match mir.source_scope_local_data {
505 ClearCrossCrate::Set(ref data) => data,
506 ClearCrossCrate::Clear => {
507 debug!("unsafety_violations: {:?} - remote, skipping", def_id);
508 return UnsafetyCheckResult {
509 violations: Lrc::new([]),
510 unsafe_blocks: Lrc::new([])
515 let param_env = tcx.param_env(def_id);
516 let mut checker = UnsafetyChecker::new(
517 tcx.is_const_fn(def_id) && tcx.is_min_const_fn(def_id),
518 mir, source_scope_local_data, tcx, param_env);
519 checker.visit_mir(mir);
521 check_unused_unsafe(tcx, def_id, &checker.used_unsafe, &mut checker.inherited_blocks);
522 UnsafetyCheckResult {
523 violations: checker.violations.into(),
524 unsafe_blocks: checker.inherited_blocks.into()
528 fn unsafe_derive_on_repr_packed<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>, def_id: DefId) {
529 let lint_node_id = match tcx.hir.as_local_node_id(def_id) {
530 Some(node_id) => node_id,
531 None => bug!("checking unsafety for non-local def id {:?}", def_id)
534 // FIXME: when we make this a hard error, this should have its
536 let message = if tcx.generics_of(def_id).own_counts().types != 0 {
537 "#[derive] can't be used on a #[repr(packed)] struct with \
538 type parameters (error E0133)".to_string()
540 "#[derive] can't be used on a #[repr(packed)] struct that \
541 does not derive Copy (error E0133)".to_string()
543 tcx.lint_node(SAFE_PACKED_BORROWS,
545 tcx.def_span(def_id),
549 /// Return the NodeId for an enclosing scope that is also `unsafe`
550 fn is_enclosed(tcx: TyCtxt,
551 used_unsafe: &FxHashSet<ast::NodeId>,
552 id: ast::NodeId) -> Option<(String, ast::NodeId)> {
553 let parent_id = tcx.hir.get_parent_node(id);
555 if used_unsafe.contains(&parent_id) {
556 Some(("block".to_string(), parent_id))
557 } else if let Some(Node::Item(&hir::Item {
558 node: hir::ItemKind::Fn(_, header, _, _),
560 })) = tcx.hir.find(parent_id) {
561 match header.unsafety {
562 hir::Unsafety::Unsafe => Some(("fn".to_string(), parent_id)),
563 hir::Unsafety::Normal => None,
566 is_enclosed(tcx, used_unsafe, parent_id)
573 fn report_unused_unsafe(tcx: TyCtxt, used_unsafe: &FxHashSet<ast::NodeId>, id: ast::NodeId) {
574 let span = tcx.sess.source_map().def_span(tcx.hir.span(id));
575 let msg = "unnecessary `unsafe` block";
576 let mut db = tcx.struct_span_lint_node(UNUSED_UNSAFE, id, span, msg);
577 db.span_label(span, msg);
578 if let Some((kind, id)) = is_enclosed(tcx, used_unsafe, id) {
579 db.span_label(tcx.sess.source_map().def_span(tcx.hir.span(id)),
580 format!("because it's nested under this `unsafe` {}", kind));
585 fn builtin_derive_def_id<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>, def_id: DefId) -> Option<DefId> {
586 debug!("builtin_derive_def_id({:?})", def_id);
587 if let Some(impl_def_id) = tcx.impl_of_method(def_id) {
588 if tcx.has_attr(impl_def_id, "automatically_derived") {
589 debug!("builtin_derive_def_id({:?}) - is {:?}", def_id, impl_def_id);
592 debug!("builtin_derive_def_id({:?}) - not automatically derived", def_id);
596 debug!("builtin_derive_def_id({:?}) - not a method", def_id);
601 pub fn check_unsafety<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>, def_id: DefId) {
602 debug!("check_unsafety({:?})", def_id);
604 // closures are handled by their parent fn.
605 if tcx.is_closure(def_id) {
609 let UnsafetyCheckResult {
612 } = tcx.unsafety_check_result(def_id);
614 for &UnsafetyViolation {
615 source_info, description, details, kind
616 } in violations.iter() {
619 UnsafetyViolationKind::General if tcx.is_min_const_fn(def_id) => {
620 tcx.sess.struct_span_err(
622 &format!("{} is unsafe and unsafe operations \
623 are not allowed in const fn", description))
624 .span_label(source_info.span, &description.as_str()[..])
625 .note(&details.as_str()[..])
628 UnsafetyViolationKind::GeneralAndConstFn |
629 UnsafetyViolationKind::General => {
631 tcx.sess, source_info.span, E0133,
632 "{} is unsafe and requires unsafe function or block", description)
633 .span_label(source_info.span, &description.as_str()[..])
634 .note(&details.as_str()[..])
637 UnsafetyViolationKind::GatedConstFnCall => {
639 &tcx.sess.parse_sess,
640 "min_const_unsafe_fn",
643 "calls to `const unsafe fn` in const fns are unstable",
647 UnsafetyViolationKind::ExternStatic(lint_node_id) => {
648 tcx.lint_node_note(SAFE_EXTERN_STATICS,
651 &format!("{} is unsafe and requires unsafe function or block \
652 (error E0133)", &description.as_str()[..]),
653 &details.as_str()[..]);
655 UnsafetyViolationKind::BorrowPacked(lint_node_id) => {
656 if let Some(impl_def_id) = builtin_derive_def_id(tcx, def_id) {
657 tcx.unsafe_derive_on_repr_packed(impl_def_id);
659 tcx.lint_node_note(SAFE_PACKED_BORROWS,
662 &format!("{} is unsafe and requires unsafe function or block \
663 (error E0133)", &description.as_str()[..]),
664 &details.as_str()[..]);
670 let mut unsafe_blocks: Vec<_> = unsafe_blocks.into_iter().collect();
671 unsafe_blocks.sort();
672 let used_unsafe: FxHashSet<_> = unsafe_blocks.iter()
673 .flat_map(|&&(id, used)| if used { Some(id) } else { None })
675 for &(block_id, is_used) in unsafe_blocks {
677 report_unused_unsafe(tcx, &used_unsafe, block_id);