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;
31 pub struct UnsafetyChecker<'a, 'tcx: 'a> {
34 source_scope_local_data: &'a IndexVec<SourceScope, SourceScopeLocalData>,
35 violations: Vec<UnsafetyViolation>,
36 source_info: SourceInfo,
37 tcx: TyCtxt<'a, 'tcx, 'tcx>,
38 param_env: ty::ParamEnv<'tcx>,
39 /// mark an `unsafe` block as used, so we don't lint it
40 used_unsafe: FxHashSet<ast::NodeId>,
41 inherited_blocks: Vec<(ast::NodeId, bool)>,
44 impl<'a, 'gcx, 'tcx> UnsafetyChecker<'a, 'tcx> {
48 source_scope_local_data: &'a IndexVec<SourceScope, SourceScopeLocalData>,
49 tcx: TyCtxt<'a, 'tcx, 'tcx>,
50 param_env: ty::ParamEnv<'tcx>,
55 source_scope_local_data,
57 source_info: SourceInfo {
59 scope: OUTERMOST_SOURCE_SCOPE
63 used_unsafe: Default::default(),
64 inherited_blocks: vec![],
69 impl<'a, 'tcx> Visitor<'tcx> for UnsafetyChecker<'a, 'tcx> {
70 fn visit_terminator(&mut self,
72 terminator: &Terminator<'tcx>,
75 self.source_info = terminator.source_info;
76 match terminator.kind {
77 TerminatorKind::Goto { .. } |
78 TerminatorKind::SwitchInt { .. } |
79 TerminatorKind::Drop { .. } |
80 TerminatorKind::Yield { .. } |
81 TerminatorKind::Assert { .. } |
82 TerminatorKind::DropAndReplace { .. } |
83 TerminatorKind::GeneratorDrop |
84 TerminatorKind::Resume |
85 TerminatorKind::Abort |
86 TerminatorKind::Return |
87 TerminatorKind::Unreachable |
88 TerminatorKind::FalseEdges { .. } |
89 TerminatorKind::FalseUnwind { .. } => {
90 // safe (at least as emitted during MIR construction)
93 TerminatorKind::Call { ref func, .. } => {
94 let func_ty = func.ty(self.mir, self.tcx);
95 let sig = func_ty.fn_sig(self.tcx);
96 if let hir::Unsafety::Unsafe = sig.unsafety() {
97 self.require_unsafe("call to unsafe function",
98 "consult the function's documentation for information on how to avoid \
99 undefined behavior", UnsafetyViolationKind::MinConstFn)
103 self.super_terminator(block, terminator, location);
106 fn visit_statement(&mut self,
108 statement: &Statement<'tcx>,
111 self.source_info = statement.source_info;
112 match statement.kind {
113 StatementKind::Assign(..) |
114 StatementKind::FakeRead(..) |
115 StatementKind::SetDiscriminant { .. } |
116 StatementKind::StorageLive(..) |
117 StatementKind::StorageDead(..) |
118 StatementKind::Retag { .. } |
119 StatementKind::EscapeToRaw { .. } |
120 StatementKind::AscribeUserType(..) |
121 StatementKind::Nop => {
122 // safe (at least as emitted during MIR construction)
125 StatementKind::InlineAsm { .. } => {
126 self.require_unsafe("use of inline assembly",
127 "inline assembly is entirely unchecked and can cause undefined behavior",
128 UnsafetyViolationKind::General)
131 self.super_statement(block, statement, location);
134 fn visit_rvalue(&mut self,
135 rvalue: &Rvalue<'tcx>,
138 if let &Rvalue::Aggregate(box ref aggregate, _) = rvalue {
140 &AggregateKind::Array(..) |
141 &AggregateKind::Tuple => {}
142 &AggregateKind::Adt(ref def, ..) => {
143 match self.tcx.layout_scalar_valid_range(def.did) {
144 (Bound::Unbounded, Bound::Unbounded) => {},
145 _ => self.require_unsafe(
146 "initializing type with `rustc_layout_scalar_valid_range` attr",
147 "initializing `NonZero` with a `0` violates layout constraints \
148 and is undefined behavior",
149 UnsafetyViolationKind::MinConstFn,
153 &AggregateKind::Closure(def_id, _) |
154 &AggregateKind::Generator(def_id, _, _) => {
155 let UnsafetyCheckResult {
156 violations, unsafe_blocks
157 } = self.tcx.unsafety_check_result(def_id);
158 self.register_violations(&violations, &unsafe_blocks);
162 self.super_rvalue(rvalue, location);
165 fn visit_place(&mut self,
167 context: PlaceContext<'tcx>,
168 location: Location) {
170 &Place::Projection(box Projection {
173 if context.is_borrow() {
174 if util::is_disaligned(self.tcx, self.mir, self.param_env, place) {
175 let source_info = self.source_info;
177 self.source_scope_local_data[source_info.scope].lint_root;
178 self.register_violations(&[UnsafetyViolation {
180 description: Symbol::intern("borrow of packed field").as_interned_str(),
182 Symbol::intern("fields of packed structs might be misaligned: \
183 dereferencing a misaligned pointer or even just \
184 creating a misaligned reference is undefined \
187 kind: UnsafetyViolationKind::BorrowPacked(lint_root)
190 if context.is_mutating_use() {
191 self.check_mut_borrowing_layout_constrained_field(place);
194 let old_source_info = self.source_info;
195 if let &Place::Local(local) = base {
196 if self.mir.local_decls[local].internal {
197 // Internal locals are used in the `move_val_init` desugaring.
198 // We want to check unsafety against the source info of the
199 // desugaring, rather than the source info of the RHS.
200 self.source_info = self.mir.local_decls[local].source_info;
203 let base_ty = base.ty(self.mir, self.tcx).to_ty(self.tcx);
206 self.require_unsafe("dereference of raw pointer",
207 "raw pointers may be NULL, dangling or unaligned; they can violate \
208 aliasing rules and cause data races: all of these are undefined \
209 behavior", UnsafetyViolationKind::General)
213 if context == PlaceContext::MutatingUse(MutatingUseContext::Store) ||
214 context == PlaceContext::MutatingUse(MutatingUseContext::Drop) ||
215 context == PlaceContext::MutatingUse(
216 MutatingUseContext::AsmOutput
219 let elem_ty = match elem {
220 &ProjectionElem::Field(_, ty) => ty,
222 self.source_info.span,
223 "non-field projection {:?} from union?",
226 if elem_ty.moves_by_default(self.tcx, self.param_env,
227 self.source_info.span) {
229 "assignment to non-`Copy` union field",
230 "the previous content of the field will be dropped, which \
231 causes undefined behavior if the field was not properly \
232 initialized", UnsafetyViolationKind::General)
234 // write to non-move union, safe
237 self.require_unsafe("access to union field",
238 "the field may not be properly initialized: using \
239 uninitialized data will cause undefined behavior",
240 UnsafetyViolationKind::General)
246 self.source_info = old_source_info;
248 &Place::Local(..) => {
251 &Place::Promoted(_) => {
252 bug!("unsafety checking should happen before promotion")
254 &Place::Static(box Static { def_id, ty: _ }) => {
255 if self.tcx.is_static(def_id) == Some(hir::Mutability::MutMutable) {
256 self.require_unsafe("use of mutable static",
257 "mutable statics can be mutated by multiple threads: aliasing violations \
258 or data races will cause undefined behavior",
259 UnsafetyViolationKind::General);
260 } else if self.tcx.is_foreign_item(def_id) {
261 let source_info = self.source_info;
263 self.source_scope_local_data[source_info.scope].lint_root;
264 self.register_violations(&[UnsafetyViolation {
266 description: Symbol::intern("use of extern static").as_interned_str(),
268 Symbol::intern("extern statics are not controlled by the Rust type \
269 system: invalid data, aliasing violations or data \
270 races will cause undefined behavior")
272 kind: UnsafetyViolationKind::ExternStatic(lint_root)
277 self.super_place(place, context, location);
281 impl<'a, 'tcx> UnsafetyChecker<'a, 'tcx> {
284 description: &'static str,
285 details: &'static str,
286 kind: UnsafetyViolationKind,
288 let source_info = self.source_info;
289 self.register_violations(&[UnsafetyViolation {
291 description: Symbol::intern(description).as_interned_str(),
292 details: Symbol::intern(details).as_interned_str(),
297 fn register_violations(&mut self,
298 violations: &[UnsafetyViolation],
299 unsafe_blocks: &[(ast::NodeId, bool)]) {
300 let safety = self.source_scope_local_data[self.source_info.scope].safety;
301 let within_unsafe = match (safety, self.min_const_fn) {
302 // Erring on the safe side, pun intended
303 (Safety::BuiltinUnsafe, true) |
304 // mir building encodes const fn bodies as safe, even for `const unsafe fn`
305 (Safety::FnUnsafe, true) => bug!("const unsafe fn body treated as inherently unsafe"),
306 // `unsafe` blocks are required in safe code
307 (Safety::Safe, _) => {
308 for violation in violations {
309 let mut violation = violation.clone();
310 if self.min_const_fn {
311 // overwrite unsafety violation in const fn with a single hard error kind
312 violation.kind = UnsafetyViolationKind::MinConstFn;
313 } else if let UnsafetyViolationKind::MinConstFn = violation.kind {
314 // outside of const fns we treat `MinConstFn` and `General` the same
315 violation.kind = UnsafetyViolationKind::General;
317 if !self.violations.contains(&violation) {
318 self.violations.push(violation)
323 // regular `unsafe` function bodies allow unsafe without additional unsafe blocks
324 (Safety::BuiltinUnsafe, false) | (Safety::FnUnsafe, false) => true,
325 (Safety::ExplicitUnsafe(node_id), _) => {
326 // mark unsafe block as used if there are any unsafe operations inside
327 if !violations.is_empty() {
328 self.used_unsafe.insert(node_id);
330 // only some unsafety is allowed in const fn
331 if self.min_const_fn {
332 for violation in violations {
333 match violation.kind {
335 UnsafetyViolationKind::MinConstFn
336 // if `#![feature(min_const_unsafe_fn)]` is active
337 if self.tcx.sess.features_untracked().min_const_unsafe_fn => {},
339 let mut violation = violation.clone();
340 // overwrite unsafety violation in const fn with a hard error
341 violation.kind = UnsafetyViolationKind::MinConstFn;
342 if !self.violations.contains(&violation) {
343 self.violations.push(violation)
352 self.inherited_blocks.extend(unsafe_blocks.iter().map(|&(node_id, is_used)| {
353 (node_id, is_used && !within_unsafe)
356 fn check_mut_borrowing_layout_constrained_field(
358 mut place: &Place<'tcx>,
360 while let &Place::Projection(box Projection {
364 ProjectionElem::Field(..) => {
365 let ty = base.ty(&self.mir.local_decls, self.tcx).to_ty(self.tcx);
367 ty::Adt(def, _) => match self.tcx.layout_scalar_valid_range(def.did) {
368 (Bound::Unbounded, Bound::Unbounded) => {},
370 let source_info = self.source_info;
371 self.register_violations(&[UnsafetyViolation {
373 description: Symbol::intern(
374 "borrow of layout constrained field",
378 "references to fields of layout constrained fields \
379 lose the constraints",
381 kind: UnsafetyViolationKind::MinConstFn,
395 pub(crate) fn provide(providers: &mut Providers) {
396 *providers = Providers {
397 unsafety_check_result,
398 unsafe_derive_on_repr_packed,
403 struct UnusedUnsafeVisitor<'a> {
404 used_unsafe: &'a FxHashSet<ast::NodeId>,
405 unsafe_blocks: &'a mut Vec<(ast::NodeId, bool)>,
408 impl<'a, 'tcx> hir::intravisit::Visitor<'tcx> for UnusedUnsafeVisitor<'a> {
409 fn nested_visit_map<'this>(&'this mut self) ->
410 hir::intravisit::NestedVisitorMap<'this, 'tcx>
412 hir::intravisit::NestedVisitorMap::None
415 fn visit_block(&mut self, block: &'tcx hir::Block) {
416 hir::intravisit::walk_block(self, block);
418 if let hir::UnsafeBlock(hir::UserProvided) = block.rules {
419 self.unsafe_blocks.push((block.id, self.used_unsafe.contains(&block.id)));
424 fn check_unused_unsafe<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>,
426 used_unsafe: &FxHashSet<ast::NodeId>,
427 unsafe_blocks: &'a mut Vec<(ast::NodeId, bool)>)
430 tcx.hir.as_local_node_id(def_id).and_then(|node_id| {
431 tcx.hir.maybe_body_owned_by(node_id)
434 let body_id = match body_id {
437 debug!("check_unused_unsafe({:?}) - no body found", def_id);
441 let body = tcx.hir.body(body_id);
442 debug!("check_unused_unsafe({:?}, body={:?}, used_unsafe={:?})",
443 def_id, body, used_unsafe);
445 let mut visitor = UnusedUnsafeVisitor { used_unsafe, unsafe_blocks };
446 hir::intravisit::Visitor::visit_body(&mut visitor, body);
449 fn unsafety_check_result<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>, def_id: DefId)
450 -> UnsafetyCheckResult
452 debug!("unsafety_violations({:?})", def_id);
454 // NB: this borrow is valid because all the consumers of
455 // `mir_built` force this.
456 let mir = &tcx.mir_built(def_id).borrow();
458 let source_scope_local_data = match mir.source_scope_local_data {
459 ClearCrossCrate::Set(ref data) => data,
460 ClearCrossCrate::Clear => {
461 debug!("unsafety_violations: {:?} - remote, skipping", def_id);
462 return UnsafetyCheckResult {
463 violations: Lrc::new([]),
464 unsafe_blocks: Lrc::new([])
469 let param_env = tcx.param_env(def_id);
470 let mut checker = UnsafetyChecker::new(
471 tcx.is_const_fn(def_id) && tcx.is_min_const_fn(def_id),
472 mir, source_scope_local_data, tcx, param_env);
473 checker.visit_mir(mir);
475 check_unused_unsafe(tcx, def_id, &checker.used_unsafe, &mut checker.inherited_blocks);
476 UnsafetyCheckResult {
477 violations: checker.violations.into(),
478 unsafe_blocks: checker.inherited_blocks.into()
482 fn unsafe_derive_on_repr_packed<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>, def_id: DefId) {
483 let lint_node_id = match tcx.hir.as_local_node_id(def_id) {
484 Some(node_id) => node_id,
485 None => bug!("checking unsafety for non-local def id {:?}", def_id)
488 // FIXME: when we make this a hard error, this should have its
490 let message = if tcx.generics_of(def_id).own_counts().types != 0 {
491 "#[derive] can't be used on a #[repr(packed)] struct with \
492 type parameters (error E0133)".to_string()
494 "#[derive] can't be used on a #[repr(packed)] struct that \
495 does not derive Copy (error E0133)".to_string()
497 tcx.lint_node(SAFE_PACKED_BORROWS,
499 tcx.def_span(def_id),
503 /// Return the NodeId for an enclosing scope that is also `unsafe`
504 fn is_enclosed(tcx: TyCtxt,
505 used_unsafe: &FxHashSet<ast::NodeId>,
506 id: ast::NodeId) -> Option<(String, ast::NodeId)> {
507 let parent_id = tcx.hir.get_parent_node(id);
509 if used_unsafe.contains(&parent_id) {
510 Some(("block".to_string(), parent_id))
511 } else if let Some(Node::Item(&hir::Item {
512 node: hir::ItemKind::Fn(_, header, _, _),
514 })) = tcx.hir.find(parent_id) {
515 match header.unsafety {
516 hir::Unsafety::Unsafe => Some(("fn".to_string(), parent_id)),
517 hir::Unsafety::Normal => None,
520 is_enclosed(tcx, used_unsafe, parent_id)
527 fn report_unused_unsafe(tcx: TyCtxt, used_unsafe: &FxHashSet<ast::NodeId>, id: ast::NodeId) {
528 let span = tcx.sess.source_map().def_span(tcx.hir.span(id));
529 let msg = "unnecessary `unsafe` block";
530 let mut db = tcx.struct_span_lint_node(UNUSED_UNSAFE, id, span, msg);
531 db.span_label(span, msg);
532 if let Some((kind, id)) = is_enclosed(tcx, used_unsafe, id) {
533 db.span_label(tcx.sess.source_map().def_span(tcx.hir.span(id)),
534 format!("because it's nested under this `unsafe` {}", kind));
539 fn builtin_derive_def_id<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>, def_id: DefId) -> Option<DefId> {
540 debug!("builtin_derive_def_id({:?})", def_id);
541 if let Some(impl_def_id) = tcx.impl_of_method(def_id) {
542 if tcx.has_attr(impl_def_id, "automatically_derived") {
543 debug!("builtin_derive_def_id({:?}) - is {:?}", def_id, impl_def_id);
546 debug!("builtin_derive_def_id({:?}) - not automatically derived", def_id);
550 debug!("builtin_derive_def_id({:?}) - not a method", def_id);
555 pub fn check_unsafety<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>, def_id: DefId) {
556 debug!("check_unsafety({:?})", def_id);
558 // closures are handled by their parent fn.
559 if tcx.is_closure(def_id) {
563 let UnsafetyCheckResult {
566 } = tcx.unsafety_check_result(def_id);
568 for &UnsafetyViolation {
569 source_info, description, details, kind
570 } in violations.iter() {
573 UnsafetyViolationKind::General => {
575 tcx.sess, source_info.span, E0133,
576 "{} is unsafe and requires unsafe function or block", description)
577 .span_label(source_info.span, &description.as_str()[..])
578 .note(&details.as_str()[..])
581 UnsafetyViolationKind::MinConstFn => {
582 tcx.sess.struct_span_err(
584 &format!("{} is unsafe and unsafe operations \
585 are not allowed in const fn", description))
586 .span_label(source_info.span, &description.as_str()[..])
587 .note(&details.as_str()[..])
590 UnsafetyViolationKind::ExternStatic(lint_node_id) => {
591 tcx.lint_node_note(SAFE_EXTERN_STATICS,
594 &format!("{} is unsafe and requires unsafe function or block \
595 (error E0133)", &description.as_str()[..]),
596 &details.as_str()[..]);
598 UnsafetyViolationKind::BorrowPacked(lint_node_id) => {
599 if let Some(impl_def_id) = builtin_derive_def_id(tcx, def_id) {
600 tcx.unsafe_derive_on_repr_packed(impl_def_id);
602 tcx.lint_node_note(SAFE_PACKED_BORROWS,
605 &format!("{} is unsafe and requires unsafe function or block \
606 (error E0133)", &description.as_str()[..]),
607 &details.as_str()[..]);
613 let mut unsafe_blocks: Vec<_> = unsafe_blocks.into_iter().collect();
614 unsafe_blocks.sort();
615 let used_unsafe: FxHashSet<_> = unsafe_blocks.iter()
616 .flat_map(|&&(id, used)| if used { Some(id) } else { None })
618 for &(block_id, is_used) in unsafe_blocks {
620 report_unused_unsafe(tcx, &used_unsafe, block_id);