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;
29 pub struct UnsafetyChecker<'a, 'tcx: 'a> {
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)>,
41 impl<'a, 'gcx, 'tcx> UnsafetyChecker<'a, 'tcx> {
45 source_scope_local_data: &'a IndexVec<SourceScope, SourceScopeLocalData>,
46 tcx: TyCtxt<'a, 'tcx, 'tcx>,
47 param_env: ty::ParamEnv<'tcx>,
52 source_scope_local_data,
54 source_info: SourceInfo {
56 scope: OUTERMOST_SOURCE_SCOPE
60 used_unsafe: Default::default(),
61 inherited_blocks: vec![],
66 impl<'a, 'tcx> Visitor<'tcx> for UnsafetyChecker<'a, 'tcx> {
67 fn visit_terminator(&mut self,
69 terminator: &Terminator<'tcx>,
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)
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 \
100 self.super_terminator(block, terminator, location);
103 fn visit_statement(&mut self,
105 statement: &Statement<'tcx>,
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::EndRegion(..) |
116 StatementKind::Retag { .. } |
117 StatementKind::EscapeToRaw { .. } |
118 StatementKind::AscribeUserType(..) |
119 StatementKind::Nop => {
120 // safe (at least as emitted during MIR construction)
123 StatementKind::InlineAsm { .. } => {
124 self.require_unsafe("use of inline assembly",
125 "inline assembly is entirely unchecked and can cause undefined behavior")
128 self.super_statement(block, statement, location);
131 fn visit_rvalue(&mut self,
132 rvalue: &Rvalue<'tcx>,
135 if let &Rvalue::Aggregate(box ref aggregate, _) = rvalue {
137 &AggregateKind::Array(..) |
138 &AggregateKind::Tuple |
139 &AggregateKind::Adt(..) => {}
140 &AggregateKind::Closure(def_id, _) |
141 &AggregateKind::Generator(def_id, _, _) => {
142 let UnsafetyCheckResult {
143 violations, unsafe_blocks
144 } = self.tcx.unsafety_check_result(def_id);
145 self.register_violations(&violations, &unsafe_blocks);
149 self.super_rvalue(rvalue, location);
152 fn visit_place(&mut self,
154 context: PlaceContext<'tcx>,
155 location: Location) {
156 if context.is_borrow() {
157 if util::is_disaligned(self.tcx, self.mir, self.param_env, place) {
158 let source_info = self.source_info;
160 self.source_scope_local_data[source_info.scope].lint_root;
161 self.register_violations(&[UnsafetyViolation {
163 description: Symbol::intern("borrow of packed field").as_interned_str(),
165 Symbol::intern("fields of packed structs might be misaligned: \
166 dereferencing a misaligned pointer or even just creating a \
167 misaligned reference is undefined behavior")
169 kind: UnsafetyViolationKind::BorrowPacked(lint_root)
175 &Place::Projection(box Projection {
178 let old_source_info = self.source_info;
179 if let &Place::Local(local) = base {
180 if self.mir.local_decls[local].internal {
181 // Internal locals are used in the `move_val_init` desugaring.
182 // We want to check unsafety against the source info of the
183 // desugaring, rather than the source info of the RHS.
184 self.source_info = self.mir.local_decls[local].source_info;
187 let base_ty = base.ty(self.mir, self.tcx).to_ty(self.tcx);
190 self.require_unsafe("dereference of raw pointer",
191 "raw pointers may be NULL, dangling or unaligned; they can violate \
192 aliasing rules and cause data races: all of these are undefined \
197 if context == PlaceContext::MutatingUse(MutatingUseContext::Store) ||
198 context == PlaceContext::MutatingUse(MutatingUseContext::Drop) ||
199 context == PlaceContext::MutatingUse(
200 MutatingUseContext::AsmOutput
203 let elem_ty = match elem {
204 &ProjectionElem::Field(_, ty) => ty,
206 self.source_info.span,
207 "non-field projection {:?} from union?",
210 if elem_ty.moves_by_default(self.tcx, self.param_env,
211 self.source_info.span) {
213 "assignment to non-`Copy` union field",
214 "the previous content of the field will be dropped, which \
215 causes undefined behavior if the field was not properly \
218 // write to non-move union, safe
221 self.require_unsafe("access to union field",
222 "the field may not be properly initialized: using \
223 uninitialized data will cause undefined behavior")
229 self.source_info = old_source_info;
231 &Place::Local(..) => {
234 &Place::Promoted(_) => {
235 bug!("unsafety checking should happen before promotion")
237 &Place::Static(box Static { def_id, ty: _ }) => {
238 if self.tcx.is_static(def_id) == Some(hir::Mutability::MutMutable) {
239 self.require_unsafe("use of mutable static",
240 "mutable statics can be mutated by multiple threads: aliasing violations \
241 or data races will cause undefined behavior");
242 } else if self.tcx.is_foreign_item(def_id) {
243 let source_info = self.source_info;
245 self.source_scope_local_data[source_info.scope].lint_root;
246 self.register_violations(&[UnsafetyViolation {
248 description: Symbol::intern("use of extern static").as_interned_str(),
250 Symbol::intern("extern statics are not controlled by the Rust type \
251 system: invalid data, aliasing violations or data \
252 races will cause undefined behavior")
254 kind: UnsafetyViolationKind::ExternStatic(lint_root)
259 self.super_place(place, context, location);
263 impl<'a, 'tcx> UnsafetyChecker<'a, 'tcx> {
264 fn require_unsafe(&mut self,
265 description: &'static str,
266 details: &'static str)
268 let source_info = self.source_info;
269 self.register_violations(&[UnsafetyViolation {
271 description: Symbol::intern(description).as_interned_str(),
272 details: Symbol::intern(details).as_interned_str(),
273 kind: UnsafetyViolationKind::General,
277 fn register_violations(&mut self,
278 violations: &[UnsafetyViolation],
279 unsafe_blocks: &[(ast::NodeId, bool)]) {
280 if self.min_const_fn {
281 for violation in violations {
282 let mut violation = violation.clone();
283 violation.kind = UnsafetyViolationKind::MinConstFn;
284 if !self.violations.contains(&violation) {
285 self.violations.push(violation)
289 let within_unsafe = match self.source_scope_local_data[self.source_info.scope].safety {
291 for violation in violations {
292 if !self.violations.contains(violation) {
293 self.violations.push(violation.clone())
298 Safety::BuiltinUnsafe | Safety::FnUnsafe => true,
299 Safety::ExplicitUnsafe(node_id) => {
300 if !violations.is_empty() {
301 self.used_unsafe.insert(node_id);
306 self.inherited_blocks.extend(unsafe_blocks.iter().map(|&(node_id, is_used)| {
307 (node_id, is_used && !within_unsafe)
312 pub(crate) fn provide(providers: &mut Providers) {
313 *providers = Providers {
314 unsafety_check_result,
315 unsafe_derive_on_repr_packed,
320 struct UnusedUnsafeVisitor<'a> {
321 used_unsafe: &'a FxHashSet<ast::NodeId>,
322 unsafe_blocks: &'a mut Vec<(ast::NodeId, bool)>,
325 impl<'a, 'tcx> hir::intravisit::Visitor<'tcx> for UnusedUnsafeVisitor<'a> {
326 fn nested_visit_map<'this>(&'this mut self) ->
327 hir::intravisit::NestedVisitorMap<'this, 'tcx>
329 hir::intravisit::NestedVisitorMap::None
332 fn visit_block(&mut self, block: &'tcx hir::Block) {
333 hir::intravisit::walk_block(self, block);
335 if let hir::UnsafeBlock(hir::UserProvided) = block.rules {
336 self.unsafe_blocks.push((block.id, self.used_unsafe.contains(&block.id)));
341 fn check_unused_unsafe<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>,
343 used_unsafe: &FxHashSet<ast::NodeId>,
344 unsafe_blocks: &'a mut Vec<(ast::NodeId, bool)>)
347 tcx.hir.as_local_node_id(def_id).and_then(|node_id| {
348 tcx.hir.maybe_body_owned_by(node_id)
351 let body_id = match body_id {
354 debug!("check_unused_unsafe({:?}) - no body found", def_id);
358 let body = tcx.hir.body(body_id);
359 debug!("check_unused_unsafe({:?}, body={:?}, used_unsafe={:?})",
360 def_id, body, used_unsafe);
362 let mut visitor = UnusedUnsafeVisitor { used_unsafe, unsafe_blocks };
363 hir::intravisit::Visitor::visit_body(&mut visitor, body);
366 fn unsafety_check_result<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>, def_id: DefId)
367 -> UnsafetyCheckResult
369 debug!("unsafety_violations({:?})", def_id);
371 // NB: this borrow is valid because all the consumers of
372 // `mir_built` force this.
373 let mir = &tcx.mir_built(def_id).borrow();
375 let source_scope_local_data = match mir.source_scope_local_data {
376 ClearCrossCrate::Set(ref data) => data,
377 ClearCrossCrate::Clear => {
378 debug!("unsafety_violations: {:?} - remote, skipping", def_id);
379 return UnsafetyCheckResult {
380 violations: Lrc::new([]),
381 unsafe_blocks: Lrc::new([])
386 let param_env = tcx.param_env(def_id);
387 let mut checker = UnsafetyChecker::new(
388 tcx.is_const_fn(def_id) && tcx.is_min_const_fn(def_id),
389 mir, source_scope_local_data, tcx, param_env);
390 checker.visit_mir(mir);
392 check_unused_unsafe(tcx, def_id, &checker.used_unsafe, &mut checker.inherited_blocks);
393 UnsafetyCheckResult {
394 violations: checker.violations.into(),
395 unsafe_blocks: checker.inherited_blocks.into()
399 fn unsafe_derive_on_repr_packed<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>, def_id: DefId) {
400 let lint_node_id = match tcx.hir.as_local_node_id(def_id) {
401 Some(node_id) => node_id,
402 None => bug!("checking unsafety for non-local def id {:?}", def_id)
405 // FIXME: when we make this a hard error, this should have its
407 let message = if tcx.generics_of(def_id).own_counts().types != 0 {
408 "#[derive] can't be used on a #[repr(packed)] struct with \
409 type parameters (error E0133)".to_string()
411 "#[derive] can't be used on a #[repr(packed)] struct that \
412 does not derive Copy (error E0133)".to_string()
414 tcx.lint_node(SAFE_PACKED_BORROWS,
416 tcx.def_span(def_id),
420 /// Return the NodeId for an enclosing scope that is also `unsafe`
421 fn is_enclosed(tcx: TyCtxt,
422 used_unsafe: &FxHashSet<ast::NodeId>,
423 id: ast::NodeId) -> Option<(String, ast::NodeId)> {
424 let parent_id = tcx.hir.get_parent_node(id);
426 if used_unsafe.contains(&parent_id) {
427 Some(("block".to_string(), parent_id))
428 } else if let Some(Node::Item(&hir::Item {
429 node: hir::ItemKind::Fn(_, header, _, _),
431 })) = tcx.hir.find(parent_id) {
432 match header.unsafety {
433 hir::Unsafety::Unsafe => Some(("fn".to_string(), parent_id)),
434 hir::Unsafety::Normal => None,
437 is_enclosed(tcx, used_unsafe, parent_id)
444 fn report_unused_unsafe(tcx: TyCtxt, used_unsafe: &FxHashSet<ast::NodeId>, id: ast::NodeId) {
445 let span = tcx.sess.source_map().def_span(tcx.hir.span(id));
446 let msg = "unnecessary `unsafe` block";
447 let mut db = tcx.struct_span_lint_node(UNUSED_UNSAFE, id, span, msg);
448 db.span_label(span, msg);
449 if let Some((kind, id)) = is_enclosed(tcx, used_unsafe, id) {
450 db.span_label(tcx.sess.source_map().def_span(tcx.hir.span(id)),
451 format!("because it's nested under this `unsafe` {}", kind));
456 fn builtin_derive_def_id<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>, def_id: DefId) -> Option<DefId> {
457 debug!("builtin_derive_def_id({:?})", def_id);
458 if let Some(impl_def_id) = tcx.impl_of_method(def_id) {
459 if tcx.has_attr(impl_def_id, "automatically_derived") {
460 debug!("builtin_derive_def_id({:?}) - is {:?}", def_id, impl_def_id);
463 debug!("builtin_derive_def_id({:?}) - not automatically derived", def_id);
467 debug!("builtin_derive_def_id({:?}) - not a method", def_id);
472 pub fn check_unsafety<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>, def_id: DefId) {
473 debug!("check_unsafety({:?})", def_id);
475 // closures are handled by their parent fn.
476 if tcx.is_closure(def_id) {
480 let UnsafetyCheckResult {
483 } = tcx.unsafety_check_result(def_id);
485 for &UnsafetyViolation {
486 source_info, description, details, kind
487 } in violations.iter() {
490 UnsafetyViolationKind::General => {
492 tcx.sess, source_info.span, E0133,
493 "{} is unsafe and requires unsafe function or block", description)
494 .span_label(source_info.span, &description.as_str()[..])
495 .note(&details.as_str()[..])
498 UnsafetyViolationKind::MinConstFn => {
499 tcx.sess.struct_span_err(
501 &format!("{} is unsafe and unsafe operations \
502 are not allowed in const fn", description))
503 .span_label(source_info.span, &description.as_str()[..])
504 .note(&details.as_str()[..])
507 UnsafetyViolationKind::ExternStatic(lint_node_id) => {
508 tcx.lint_node_note(SAFE_EXTERN_STATICS,
511 &format!("{} is unsafe and requires unsafe function or block \
512 (error E0133)", &description.as_str()[..]),
513 &details.as_str()[..]);
515 UnsafetyViolationKind::BorrowPacked(lint_node_id) => {
516 if let Some(impl_def_id) = builtin_derive_def_id(tcx, def_id) {
517 tcx.unsafe_derive_on_repr_packed(impl_def_id);
519 tcx.lint_node_note(SAFE_PACKED_BORROWS,
522 &format!("{} is unsafe and requires unsafe function or block \
523 (error E0133)", &description.as_str()[..]),
524 &details.as_str()[..]);
530 let mut unsafe_blocks: Vec<_> = unsafe_blocks.into_iter().collect();
531 unsafe_blocks.sort();
532 let used_unsafe: FxHashSet<_> = unsafe_blocks.iter()
533 .flat_map(|&&(id, used)| if used { Some(id) } else { None })
535 for &(block_id, is_used) in unsafe_blocks {
537 report_unused_unsafe(tcx, &used_unsafe, block_id);