1 use rustc_data_structures::fx::FxHashSet;
4 use rustc::hir::def_id::DefId;
6 use rustc::lint::builtin::{SAFE_PACKED_BORROWS, UNUSED_UNSAFE};
7 use rustc::mir::visit::{MutatingUseContext, PlaceContext, Visitor};
9 use rustc::ty::cast::CastTy;
10 use rustc::ty::query::Providers;
11 use rustc::ty::{self, TyCtxt};
13 use syntax::symbol::{sym, Symbol};
19 use rustc_error_codes::*;
21 pub struct UnsafetyChecker<'a, 'tcx> {
25 violations: Vec<UnsafetyViolation>,
26 source_info: SourceInfo,
28 param_env: ty::ParamEnv<'tcx>,
29 /// Mark an `unsafe` block as used, so we don't lint it.
30 used_unsafe: FxHashSet<hir::HirId>,
31 inherited_blocks: Vec<(hir::HirId, bool)>,
34 impl<'a, 'tcx> UnsafetyChecker<'a, 'tcx> {
40 param_env: ty::ParamEnv<'tcx>,
44 assert!(const_context);
51 source_info: SourceInfo { span: body.span, scope: OUTERMOST_SOURCE_SCOPE },
54 used_unsafe: Default::default(),
55 inherited_blocks: vec![],
60 impl<'a, 'tcx> Visitor<'tcx> for UnsafetyChecker<'a, 'tcx> {
61 fn visit_terminator(&mut self, terminator: &Terminator<'tcx>, location: Location) {
62 self.source_info = terminator.source_info;
63 match terminator.kind {
64 TerminatorKind::Goto { .. }
65 | TerminatorKind::SwitchInt { .. }
66 | TerminatorKind::Drop { .. }
67 | TerminatorKind::Yield { .. }
68 | TerminatorKind::Assert { .. }
69 | TerminatorKind::DropAndReplace { .. }
70 | TerminatorKind::GeneratorDrop
71 | TerminatorKind::Resume
72 | TerminatorKind::Abort
73 | TerminatorKind::Return
74 | TerminatorKind::Unreachable
75 | TerminatorKind::FalseEdges { .. }
76 | TerminatorKind::FalseUnwind { .. } => {
77 // safe (at least as emitted during MIR construction)
80 TerminatorKind::Call { ref func, .. } => {
81 let func_ty = func.ty(self.body, self.tcx);
82 let sig = func_ty.fn_sig(self.tcx);
83 if let hir::Unsafety::Unsafe = sig.unsafety() {
85 "call to unsafe function",
86 "consult the function's documentation for information on how to avoid \
88 UnsafetyViolationKind::GeneralAndConstFn,
93 self.super_terminator(terminator, location);
96 fn visit_statement(&mut self, statement: &Statement<'tcx>, location: Location) {
97 self.source_info = statement.source_info;
98 match statement.kind {
99 StatementKind::Assign(..)
100 | StatementKind::FakeRead(..)
101 | StatementKind::SetDiscriminant { .. }
102 | StatementKind::StorageLive(..)
103 | StatementKind::StorageDead(..)
104 | StatementKind::Retag { .. }
105 | StatementKind::AscribeUserType(..)
106 | StatementKind::Nop => {
107 // safe (at least as emitted during MIR construction)
110 StatementKind::InlineAsm { .. } => self.require_unsafe(
111 "use of inline assembly",
112 "inline assembly is entirely unchecked and can cause undefined behavior",
113 UnsafetyViolationKind::General,
116 self.super_statement(statement, location);
119 fn visit_rvalue(&mut self, rvalue: &Rvalue<'tcx>, location: Location) {
121 Rvalue::Aggregate(box ref aggregate, _) => match aggregate {
122 &AggregateKind::Array(..) | &AggregateKind::Tuple => {}
123 &AggregateKind::Adt(ref def, ..) => {
124 match self.tcx.layout_scalar_valid_range(def.did) {
125 (Bound::Unbounded, Bound::Unbounded) => {}
126 _ => self.require_unsafe(
127 "initializing type with `rustc_layout_scalar_valid_range` attr",
128 "initializing a layout restricted type's field with a value \
129 outside the valid range is undefined behavior",
130 UnsafetyViolationKind::GeneralAndConstFn,
134 &AggregateKind::Closure(def_id, _) | &AggregateKind::Generator(def_id, _, _) => {
135 let UnsafetyCheckResult { violations, unsafe_blocks } =
136 self.tcx.unsafety_check_result(def_id);
137 self.register_violations(&violations, &unsafe_blocks);
140 // casting pointers to ints is unsafe in const fn because the const evaluator cannot
141 // possibly know what the result of various operations like `address / 2` would be
142 // pointers during const evaluation have no integral address, only an abstract one
143 Rvalue::Cast(CastKind::Misc, ref operand, cast_ty)
144 if self.const_context && self.tcx.features().const_raw_ptr_to_usize_cast =>
146 let operand_ty = operand.ty(self.body, self.tcx);
147 let cast_in = CastTy::from_ty(operand_ty).expect("bad input type for cast");
148 let cast_out = CastTy::from_ty(cast_ty).expect("bad output type for cast");
149 match (cast_in, cast_out) {
150 (CastTy::Ptr(_), CastTy::Int(_)) | (CastTy::FnPtr, CastTy::Int(_)) => {
151 self.register_violations(
152 &[UnsafetyViolation {
153 source_info: self.source_info,
154 description: Symbol::intern("cast of pointer to int"),
155 details: Symbol::intern(
156 "casting pointers to integers in constants",
158 kind: UnsafetyViolationKind::General,
166 // raw pointer and fn pointer operations are unsafe as it is not clear whether one
167 // pointer would be "less" or "equal" to another, because we cannot know where llvm
168 // or the linker will place various statics in memory. Without this information the
169 // result of a comparison of addresses would differ between runtime and compile-time.
170 Rvalue::BinaryOp(_, ref lhs, _)
171 if self.const_context && self.tcx.features().const_compare_raw_pointers =>
173 if let ty::RawPtr(_) | ty::FnPtr(..) = lhs.ty(self.body, self.tcx).kind {
174 self.register_violations(
175 &[UnsafetyViolation {
176 source_info: self.source_info,
177 description: Symbol::intern("pointer operation"),
178 details: Symbol::intern("operations on pointers in constants"),
179 kind: UnsafetyViolationKind::General,
187 self.super_rvalue(rvalue, location);
190 fn visit_place(&mut self, place: &Place<'tcx>, context: PlaceContext, _location: Location) {
192 PlaceBase::Local(..) => {
195 PlaceBase::Static(box Static { kind: StaticKind::Promoted(_, _), .. }) => {
196 bug!("unsafety checking should happen before promotion");
198 PlaceBase::Static(box Static { kind: StaticKind::Static, .. }) => {
199 bug!("StaticKind::Static should not exist");
203 for (i, elem) in place.projection.iter().enumerate() {
204 let proj_base = &place.projection[..i];
206 if context.is_borrow() {
207 if util::is_disaligned(self.tcx, self.body, self.param_env, place) {
208 let source_info = self.source_info;
209 let lint_root = self.body.source_scopes[source_info.scope]
212 .assert_crate_local()
214 self.register_violations(
215 &[UnsafetyViolation {
217 description: Symbol::intern("borrow of packed field"),
218 details: Symbol::intern(
219 "fields of packed structs might be misaligned: dereferencing a \
220 misaligned pointer or even just creating a misaligned reference \
221 is undefined behavior",
223 kind: UnsafetyViolationKind::BorrowPacked(lint_root),
229 let is_borrow_of_interior_mut = context.is_borrow()
230 && !Place::ty_from(&place.base, proj_base, self.body, self.tcx).ty.is_freeze(
233 self.source_info.span,
238 // * `&x.field` if `field`'s type has interior mutability
239 // because either of these would allow modifying the layout constrained field and
240 // insert values that violate the layout constraints.
241 if context.is_mutating_use() || is_borrow_of_interior_mut {
242 self.check_mut_borrowing_layout_constrained_field(place, context.is_mutating_use());
244 let old_source_info = self.source_info;
245 if let (PlaceBase::Local(local), []) = (&place.base, proj_base) {
246 let decl = &self.body.local_decls[*local];
248 // Internal locals are used in the `move_val_init` desugaring.
249 // We want to check unsafety against the source info of the
250 // desugaring, rather than the source info of the RHS.
251 self.source_info = self.body.local_decls[*local].source_info;
252 } else if let LocalInfo::StaticRef { def_id, .. } = decl.local_info {
253 if self.tcx.is_mutable_static(def_id) {
255 "use of mutable static",
256 "mutable statics can be mutated by multiple threads: aliasing \
257 violations or data races will cause undefined behavior",
258 UnsafetyViolationKind::General,
261 } else if self.tcx.is_foreign_item(def_id) {
263 "use of extern static",
264 "extern statics are not controlled by the Rust type system: \
265 invalid data, aliasing violations or data races will cause \
267 UnsafetyViolationKind::General,
273 let base_ty = Place::ty_from(&place.base, proj_base, self.body, self.tcx).ty;
275 ty::RawPtr(..) => self.require_unsafe(
276 "dereference of raw pointer",
277 "raw pointers may be NULL, dangling or unaligned; they can violate \
278 aliasing rules and cause data races: all of these are undefined \
280 UnsafetyViolationKind::General,
284 if context == PlaceContext::MutatingUse(MutatingUseContext::Store)
285 || context == PlaceContext::MutatingUse(MutatingUseContext::Drop)
286 || context == PlaceContext::MutatingUse(MutatingUseContext::AsmOutput)
288 let elem_ty = match elem {
289 ProjectionElem::Field(_, ty) => ty,
291 self.source_info.span,
292 "non-field projection {:?} from union?",
296 if !elem_ty.is_copy_modulo_regions(
299 self.source_info.span,
302 "assignment to non-`Copy` union field",
303 "the previous content of the field will be dropped, which \
304 causes undefined behavior if the field was not properly \
306 UnsafetyViolationKind::GeneralAndConstFn,
309 // write to non-move union, safe
313 "access to union field",
314 "the field may not be properly initialized: using \
315 uninitialized data will cause undefined behavior",
316 UnsafetyViolationKind::GeneralAndConstFn,
323 self.source_info = old_source_info;
328 impl<'a, 'tcx> UnsafetyChecker<'a, 'tcx> {
331 description: &'static str,
332 details: &'static str,
333 kind: UnsafetyViolationKind,
335 let source_info = self.source_info;
336 self.register_violations(
337 &[UnsafetyViolation {
339 description: Symbol::intern(description),
340 details: Symbol::intern(details),
347 fn register_violations(
349 violations: &[UnsafetyViolation],
350 unsafe_blocks: &[(hir::HirId, bool)],
352 let safety = self.body.source_scopes[self.source_info.scope]
355 .assert_crate_local()
357 let within_unsafe = match safety {
358 // `unsafe` blocks are required in safe code
360 for violation in violations {
361 let mut violation = violation.clone();
362 match violation.kind {
363 UnsafetyViolationKind::GeneralAndConstFn
364 | UnsafetyViolationKind::General => {}
365 UnsafetyViolationKind::BorrowPacked(_) => {
366 if self.min_const_fn {
367 // const fns don't need to be backwards compatible and can
368 // emit these violations as a hard error instead of a backwards
370 violation.kind = UnsafetyViolationKind::General;
374 if !self.violations.contains(&violation) {
375 self.violations.push(violation)
380 // `unsafe` function bodies allow unsafe without additional unsafe blocks
381 Safety::BuiltinUnsafe | Safety::FnUnsafe => true,
382 Safety::ExplicitUnsafe(hir_id) => {
383 // mark unsafe block as used if there are any unsafe operations inside
384 if !violations.is_empty() {
385 self.used_unsafe.insert(hir_id);
387 // only some unsafety is allowed in const fn
388 if self.min_const_fn {
389 for violation in violations {
390 match violation.kind {
391 // these unsafe things are stable in const fn
392 UnsafetyViolationKind::GeneralAndConstFn => {}
393 // these things are forbidden in const fns
394 UnsafetyViolationKind::General
395 | UnsafetyViolationKind::BorrowPacked(_) => {
396 let mut violation = violation.clone();
397 // const fns don't need to be backwards compatible and can
398 // emit these violations as a hard error instead of a backwards
400 violation.kind = UnsafetyViolationKind::General;
401 if !self.violations.contains(&violation) {
402 self.violations.push(violation)
411 self.inherited_blocks.extend(
412 unsafe_blocks.iter().map(|&(hir_id, is_used)| (hir_id, is_used && !within_unsafe)),
415 fn check_mut_borrowing_layout_constrained_field(
420 let mut cursor = place.projection.as_ref();
421 while let &[ref proj_base @ .., elem] = cursor {
425 ProjectionElem::Field(..) => {
427 Place::ty_from(&place.base, proj_base, &self.body.local_decls, self.tcx).ty;
429 ty::Adt(def, _) => match self.tcx.layout_scalar_valid_range(def.did) {
430 (Bound::Unbounded, Bound::Unbounded) => {}
432 let (description, details) = if is_mut_use {
434 "mutation of layout constrained field",
435 "mutating layout constrained fields cannot statically be \
436 checked for valid values",
440 "borrow of layout constrained field with interior \
442 "references to fields of layout constrained fields \
443 lose the constraints. Coupled with interior mutability, \
444 the field can be changed to invalid values",
447 let source_info = self.source_info;
448 self.register_violations(
449 &[UnsafetyViolation {
451 description: Symbol::intern(description),
452 details: Symbol::intern(details),
453 kind: UnsafetyViolationKind::GeneralAndConstFn,
468 pub(crate) fn provide(providers: &mut Providers<'_>) {
469 *providers = Providers { unsafety_check_result, unsafe_derive_on_repr_packed, ..*providers };
472 struct UnusedUnsafeVisitor<'a> {
473 used_unsafe: &'a FxHashSet<hir::HirId>,
474 unsafe_blocks: &'a mut Vec<(hir::HirId, bool)>,
477 impl<'a, 'tcx> hir::intravisit::Visitor<'tcx> for UnusedUnsafeVisitor<'a> {
478 fn nested_visit_map<'this>(&'this mut self) -> hir::intravisit::NestedVisitorMap<'this, 'tcx> {
479 hir::intravisit::NestedVisitorMap::None
482 fn visit_block(&mut self, block: &'tcx hir::Block<'tcx>) {
483 hir::intravisit::walk_block(self, block);
485 if let hir::UnsafeBlock(hir::UserProvided) = block.rules {
486 self.unsafe_blocks.push((block.hir_id, self.used_unsafe.contains(&block.hir_id)));
491 fn check_unused_unsafe(
494 used_unsafe: &FxHashSet<hir::HirId>,
495 unsafe_blocks: &mut Vec<(hir::HirId, bool)>,
498 tcx.hir().as_local_hir_id(def_id).and_then(|hir_id| tcx.hir().maybe_body_owned_by(hir_id));
500 let body_id = match body_id {
503 debug!("check_unused_unsafe({:?}) - no body found", def_id);
507 let body = tcx.hir().body(body_id);
508 debug!("check_unused_unsafe({:?}, body={:?}, used_unsafe={:?})", def_id, body, used_unsafe);
510 let mut visitor = UnusedUnsafeVisitor { used_unsafe, unsafe_blocks };
511 hir::intravisit::Visitor::visit_body(&mut visitor, body);
514 fn unsafety_check_result(tcx: TyCtxt<'_>, def_id: DefId) -> UnsafetyCheckResult {
515 debug!("unsafety_violations({:?})", def_id);
517 // N.B., this borrow is valid because all the consumers of
518 // `mir_built` force this.
519 let body = &tcx.mir_built(def_id).borrow();
521 let param_env = tcx.param_env(def_id);
523 let id = tcx.hir().as_local_hir_id(def_id).unwrap();
524 let (const_context, min_const_fn) = match tcx.hir().body_owner_kind(id) {
525 hir::BodyOwnerKind::Closure => (false, false),
526 hir::BodyOwnerKind::Fn => (tcx.is_const_fn(def_id), tcx.is_min_const_fn(def_id)),
527 hir::BodyOwnerKind::Const | hir::BodyOwnerKind::Static(_) => (true, false),
529 let mut checker = UnsafetyChecker::new(const_context, min_const_fn, body, tcx, param_env);
530 // mir_built ensures that body has a computed cache, so we don't (and can't) attempt to
531 // recompute it here.
532 let body = body.unwrap_read_only();
533 checker.visit_body(body);
535 check_unused_unsafe(tcx, def_id, &checker.used_unsafe, &mut checker.inherited_blocks);
536 UnsafetyCheckResult {
537 violations: checker.violations.into(),
538 unsafe_blocks: checker.inherited_blocks.into(),
542 fn unsafe_derive_on_repr_packed(tcx: TyCtxt<'_>, def_id: DefId) {
543 let lint_hir_id = tcx
545 .as_local_hir_id(def_id)
546 .unwrap_or_else(|| bug!("checking unsafety for non-local def id {:?}", def_id));
548 // FIXME: when we make this a hard error, this should have its
550 let message = if tcx.generics_of(def_id).own_requires_monomorphization() {
551 "`#[derive]` can't be used on a `#[repr(packed)]` struct with \
552 type or const parameters (error E0133)"
555 "`#[derive]` can't be used on a `#[repr(packed)]` struct that \
556 does not derive Copy (error E0133)"
559 tcx.lint_hir(SAFE_PACKED_BORROWS, lint_hir_id, tcx.def_span(def_id), &message);
562 /// Returns the `HirId` for an enclosing scope that is also `unsafe`.
565 used_unsafe: &FxHashSet<hir::HirId>,
567 ) -> Option<(String, hir::HirId)> {
568 let parent_id = tcx.hir().get_parent_node(id);
570 if used_unsafe.contains(&parent_id) {
571 Some(("block".to_string(), parent_id))
572 } else if let Some(Node::Item(&hir::Item {
573 kind: hir::ItemKind::Fn(ref sig, _, _), ..
574 })) = tcx.hir().find(parent_id)
576 match sig.header.unsafety {
577 hir::Unsafety::Unsafe => Some(("fn".to_string(), parent_id)),
578 hir::Unsafety::Normal => None,
581 is_enclosed(tcx, used_unsafe, parent_id)
588 fn report_unused_unsafe(tcx: TyCtxt<'_>, used_unsafe: &FxHashSet<hir::HirId>, id: hir::HirId) {
589 let span = tcx.sess.source_map().def_span(tcx.hir().span(id));
590 let msg = "unnecessary `unsafe` block";
591 let mut db = tcx.struct_span_lint_hir(UNUSED_UNSAFE, id, span, msg);
592 db.span_label(span, msg);
593 if let Some((kind, id)) = is_enclosed(tcx, used_unsafe, id) {
595 tcx.sess.source_map().def_span(tcx.hir().span(id)),
596 format!("because it's nested under this `unsafe` {}", kind),
602 fn builtin_derive_def_id(tcx: TyCtxt<'_>, def_id: DefId) -> Option<DefId> {
603 debug!("builtin_derive_def_id({:?})", def_id);
604 if let Some(impl_def_id) = tcx.impl_of_method(def_id) {
605 if tcx.has_attr(impl_def_id, sym::automatically_derived) {
606 debug!("builtin_derive_def_id({:?}) - is {:?}", def_id, impl_def_id);
609 debug!("builtin_derive_def_id({:?}) - not automatically derived", def_id);
613 debug!("builtin_derive_def_id({:?}) - not a method", def_id);
618 pub fn check_unsafety(tcx: TyCtxt<'_>, def_id: DefId) {
619 debug!("check_unsafety({:?})", def_id);
621 // closures are handled by their parent fn.
622 if tcx.is_closure(def_id) {
626 let UnsafetyCheckResult { violations, unsafe_blocks } = tcx.unsafety_check_result(def_id);
628 for &UnsafetyViolation { source_info, description, details, kind } in violations.iter() {
631 UnsafetyViolationKind::GeneralAndConstFn | UnsafetyViolationKind::General => {
636 "{} is unsafe and requires unsafe function or block",
639 .span_label(source_info.span, &*description.as_str())
640 .note(&details.as_str())
643 UnsafetyViolationKind::BorrowPacked(lint_hir_id) => {
644 if let Some(impl_def_id) = builtin_derive_def_id(tcx, def_id) {
645 tcx.unsafe_derive_on_repr_packed(impl_def_id);
652 "{} is unsafe and requires unsafe function or block \
663 let mut unsafe_blocks: Vec<_> = unsafe_blocks.into_iter().collect();
664 unsafe_blocks.sort_by_cached_key(|(hir_id, _)| tcx.hir().hir_to_node_id(*hir_id));
665 let used_unsafe: FxHashSet<_> =
666 unsafe_blocks.iter().flat_map(|&&(id, used)| used.then_some(id)).collect();
667 for &(block_id, is_used) in unsafe_blocks {
669 report_unused_unsafe(tcx, &used_unsafe, block_id);