1 use rustc::hir::map::Map;
2 use rustc::lint::builtin::{SAFE_PACKED_BORROWS, UNUSED_UNSAFE};
3 use rustc::mir::visit::{MutatingUseContext, PlaceContext, Visitor};
5 use rustc::ty::cast::CastTy;
6 use rustc::ty::query::Providers;
7 use rustc::ty::{self, TyCtxt};
8 use rustc_data_structures::fx::FxHashSet;
9 use rustc_errors::struct_span_err;
11 use rustc_hir::def_id::DefId;
12 use rustc_hir::intravisit;
14 use rustc_span::symbol::{sym, Symbol};
18 use crate::const_eval::{is_const_fn, is_min_const_fn};
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(_)) => {
152 "cast of pointer to int",
153 "casting pointers to integers in constants",
154 UnsafetyViolationKind::General,
160 // raw pointer and fn pointer operations are unsafe as it is not clear whether one
161 // pointer would be "less" or "equal" to another, because we cannot know where llvm
162 // or the linker will place various statics in memory. Without this information the
163 // result of a comparison of addresses would differ between runtime and compile-time.
164 Rvalue::BinaryOp(_, ref lhs, _)
165 if self.const_context && self.tcx.features().const_compare_raw_pointers =>
167 if let ty::RawPtr(_) | ty::FnPtr(..) = lhs.ty(self.body, self.tcx).kind {
170 "operations on pointers in constants",
171 UnsafetyViolationKind::General,
177 self.super_rvalue(rvalue, location);
180 fn visit_place(&mut self, place: &Place<'tcx>, context: PlaceContext, _location: Location) {
184 // * `&x.field` if `field`'s type has interior mutability
185 // because either of these would allow modifying the layout constrained field and
186 // insert values that violate the layout constraints.
187 if context.is_mutating_use() || context.is_borrow() {
188 self.check_mut_borrowing_layout_constrained_field(place, context.is_mutating_use());
191 for (i, elem) in place.projection.iter().enumerate() {
192 let proj_base = &place.projection[..i];
194 if context.is_borrow() {
195 if util::is_disaligned(self.tcx, self.body, self.param_env, place) {
196 let source_info = self.source_info;
197 let lint_root = self.body.source_scopes[source_info.scope]
200 .assert_crate_local()
203 "borrow of packed field",
204 "fields of packed structs might be misaligned: dereferencing a \
205 misaligned pointer or even just creating a misaligned reference \
206 is undefined behavior",
207 UnsafetyViolationKind::BorrowPacked(lint_root),
211 let old_source_info = self.source_info;
212 if let [] = proj_base {
213 let decl = &self.body.local_decls[place.local];
215 if let LocalInfo::StaticRef { def_id, .. } = decl.local_info {
216 if self.tcx.is_mutable_static(def_id) {
218 "use of mutable static",
219 "mutable statics can be mutated by multiple threads: aliasing \
220 violations or data races will cause undefined behavior",
221 UnsafetyViolationKind::General,
224 } else if self.tcx.is_foreign_item(def_id) {
226 "use of extern static",
227 "extern statics are not controlled by the Rust type system: \
228 invalid data, aliasing violations or data races will cause \
230 UnsafetyViolationKind::General,
235 // Internal locals are used in the `move_val_init` desugaring.
236 // We want to check unsafety against the source info of the
237 // desugaring, rather than the source info of the RHS.
238 self.source_info = self.body.local_decls[place.local].source_info;
242 let base_ty = Place::ty_from(place.local, proj_base, self.body, self.tcx).ty;
244 ty::RawPtr(..) => self.require_unsafe(
245 "dereference of raw pointer",
246 "raw pointers may be NULL, dangling or unaligned; they can violate \
247 aliasing rules and cause data races: all of these are undefined \
249 UnsafetyViolationKind::General,
253 if context == PlaceContext::MutatingUse(MutatingUseContext::Store)
254 || context == PlaceContext::MutatingUse(MutatingUseContext::Drop)
255 || context == PlaceContext::MutatingUse(MutatingUseContext::AsmOutput)
257 let elem_ty = match elem {
258 ProjectionElem::Field(_, ty) => ty,
260 self.source_info.span,
261 "non-field projection {:?} from union?",
265 if !elem_ty.is_copy_modulo_regions(
268 self.source_info.span,
271 "assignment to non-`Copy` union field",
272 "the previous content of the field will be dropped, which \
273 causes undefined behavior if the field was not properly \
275 UnsafetyViolationKind::GeneralAndConstFn,
278 // write to non-move union, safe
282 "access to union field",
283 "the field may not be properly initialized: using \
284 uninitialized data will cause undefined behavior",
285 UnsafetyViolationKind::GeneralAndConstFn,
292 self.source_info = old_source_info;
297 impl<'a, 'tcx> UnsafetyChecker<'a, 'tcx> {
300 description: &'static str,
301 details: &'static str,
302 kind: UnsafetyViolationKind,
304 let source_info = self.source_info;
305 self.register_violations(
306 &[UnsafetyViolation {
308 description: Symbol::intern(description),
309 details: Symbol::intern(details),
316 fn register_violations(
318 violations: &[UnsafetyViolation],
319 unsafe_blocks: &[(hir::HirId, bool)],
321 let safety = self.body.source_scopes[self.source_info.scope]
324 .assert_crate_local()
326 let within_unsafe = match safety {
327 // `unsafe` blocks are required in safe code
329 for violation in violations {
330 let mut violation = *violation;
331 match violation.kind {
332 UnsafetyViolationKind::GeneralAndConstFn
333 | UnsafetyViolationKind::General => {}
334 UnsafetyViolationKind::BorrowPacked(_) => {
335 if self.min_const_fn {
336 // const fns don't need to be backwards compatible and can
337 // emit these violations as a hard error instead of a backwards
339 violation.kind = UnsafetyViolationKind::General;
343 if !self.violations.contains(&violation) {
344 self.violations.push(violation)
349 // `unsafe` function bodies allow unsafe without additional unsafe blocks
350 Safety::BuiltinUnsafe | Safety::FnUnsafe => true,
351 Safety::ExplicitUnsafe(hir_id) => {
352 // mark unsafe block as used if there are any unsafe operations inside
353 if !violations.is_empty() {
354 self.used_unsafe.insert(hir_id);
356 // only some unsafety is allowed in const fn
357 if self.min_const_fn {
358 for violation in violations {
359 match violation.kind {
360 // these unsafe things are stable in const fn
361 UnsafetyViolationKind::GeneralAndConstFn => {}
362 // these things are forbidden in const fns
363 UnsafetyViolationKind::General
364 | UnsafetyViolationKind::BorrowPacked(_) => {
365 let mut violation = *violation;
366 // const fns don't need to be backwards compatible and can
367 // emit these violations as a hard error instead of a backwards
369 violation.kind = UnsafetyViolationKind::General;
370 if !self.violations.contains(&violation) {
371 self.violations.push(violation)
380 self.inherited_blocks.extend(
381 unsafe_blocks.iter().map(|&(hir_id, is_used)| (hir_id, is_used && !within_unsafe)),
384 fn check_mut_borrowing_layout_constrained_field(
389 let mut cursor = place.projection.as_ref();
390 while let &[ref proj_base @ .., elem] = cursor {
394 // Modifications behind a dereference don't affect the value of
396 ProjectionElem::Deref => return,
397 ProjectionElem::Field(..) => {
399 Place::ty_from(place.local, proj_base, &self.body.local_decls, self.tcx).ty;
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",
411 // Check `is_freeze` as late as possible to avoid cycle errors
412 // with opaque types.
413 } else if !place.ty(self.body, self.tcx).ty.is_freeze(
416 self.source_info.span,
419 "borrow of layout constrained field with interior \
421 "references to fields of layout constrained fields \
422 lose the constraints. Coupled with interior mutability, \
423 the field can be changed to invalid values",
431 UnsafetyViolationKind::GeneralAndConstFn,
444 pub(crate) fn provide(providers: &mut Providers<'_>) {
445 *providers = Providers { unsafety_check_result, unsafe_derive_on_repr_packed, ..*providers };
448 struct UnusedUnsafeVisitor<'a> {
449 used_unsafe: &'a FxHashSet<hir::HirId>,
450 unsafe_blocks: &'a mut Vec<(hir::HirId, bool)>,
453 impl<'a, 'tcx> intravisit::Visitor<'tcx> for UnusedUnsafeVisitor<'a> {
454 type Map = Map<'tcx>;
456 fn nested_visit_map<'this>(&'this mut self) -> intravisit::NestedVisitorMap<'this, Self::Map> {
457 intravisit::NestedVisitorMap::None
460 fn visit_block(&mut self, block: &'tcx hir::Block<'tcx>) {
461 intravisit::walk_block(self, block);
463 if let hir::BlockCheckMode::UnsafeBlock(hir::UnsafeSource::UserProvided) = block.rules {
464 self.unsafe_blocks.push((block.hir_id, self.used_unsafe.contains(&block.hir_id)));
469 fn check_unused_unsafe(
472 used_unsafe: &FxHashSet<hir::HirId>,
473 unsafe_blocks: &mut Vec<(hir::HirId, bool)>,
476 tcx.hir().as_local_hir_id(def_id).and_then(|hir_id| tcx.hir().maybe_body_owned_by(hir_id));
478 let body_id = match body_id {
481 debug!("check_unused_unsafe({:?}) - no body found", def_id);
485 let body = tcx.hir().body(body_id);
486 debug!("check_unused_unsafe({:?}, body={:?}, used_unsafe={:?})", def_id, body, used_unsafe);
488 let mut visitor = UnusedUnsafeVisitor { used_unsafe, unsafe_blocks };
489 intravisit::Visitor::visit_body(&mut visitor, body);
492 fn unsafety_check_result(tcx: TyCtxt<'_>, def_id: DefId) -> UnsafetyCheckResult {
493 debug!("unsafety_violations({:?})", def_id);
495 // N.B., this borrow is valid because all the consumers of
496 // `mir_built` force this.
497 let body = &tcx.mir_built(def_id).borrow();
499 let param_env = tcx.param_env(def_id);
501 let id = tcx.hir().as_local_hir_id(def_id).unwrap();
502 let (const_context, min_const_fn) = match tcx.hir().body_owner_kind(id) {
503 hir::BodyOwnerKind::Closure => (false, false),
504 hir::BodyOwnerKind::Fn => (is_const_fn(tcx, def_id), is_min_const_fn(tcx, def_id)),
505 hir::BodyOwnerKind::Const | hir::BodyOwnerKind::Static(_) => (true, false),
507 let mut checker = UnsafetyChecker::new(const_context, min_const_fn, body, tcx, param_env);
508 // mir_built ensures that body has a computed cache, so we don't (and can't) attempt to
509 // recompute it here.
510 let body = body.unwrap_read_only();
511 checker.visit_body(body);
513 check_unused_unsafe(tcx, def_id, &checker.used_unsafe, &mut checker.inherited_blocks);
514 UnsafetyCheckResult {
515 violations: checker.violations.into(),
516 unsafe_blocks: checker.inherited_blocks.into(),
520 fn unsafe_derive_on_repr_packed(tcx: TyCtxt<'_>, def_id: DefId) {
521 let lint_hir_id = tcx
523 .as_local_hir_id(def_id)
524 .unwrap_or_else(|| bug!("checking unsafety for non-local def id {:?}", def_id));
526 tcx.struct_span_lint_hir(SAFE_PACKED_BORROWS, lint_hir_id, tcx.def_span(def_id), |lint| {
527 // FIXME: when we make this a hard error, this should have its
529 let message = if tcx.generics_of(def_id).own_requires_monomorphization() {
530 "`#[derive]` can't be used on a `#[repr(packed)]` struct with \
531 type or const parameters (error E0133)"
534 "`#[derive]` can't be used on a `#[repr(packed)]` struct that \
535 does not derive Copy (error E0133)"
538 lint.build(&message).emit()
542 /// Returns the `HirId` for an enclosing scope that is also `unsafe`.
545 used_unsafe: &FxHashSet<hir::HirId>,
547 ) -> Option<(String, hir::HirId)> {
548 let parent_id = tcx.hir().get_parent_node(id);
550 if used_unsafe.contains(&parent_id) {
551 Some(("block".to_string(), parent_id))
552 } else if let Some(Node::Item(&hir::Item {
553 kind: hir::ItemKind::Fn(ref sig, _, _), ..
554 })) = tcx.hir().find(parent_id)
556 match sig.header.unsafety {
557 hir::Unsafety::Unsafe => Some(("fn".to_string(), parent_id)),
558 hir::Unsafety::Normal => None,
561 is_enclosed(tcx, used_unsafe, parent_id)
568 fn report_unused_unsafe(tcx: TyCtxt<'_>, used_unsafe: &FxHashSet<hir::HirId>, id: hir::HirId) {
569 let span = tcx.sess.source_map().def_span(tcx.hir().span(id));
570 tcx.struct_span_lint_hir(UNUSED_UNSAFE, id, span, |lint| {
571 let msg = "unnecessary `unsafe` block";
572 let mut db = lint.build(msg);
573 db.span_label(span, msg);
574 if let Some((kind, id)) = is_enclosed(tcx, used_unsafe, id) {
576 tcx.sess.source_map().def_span(tcx.hir().span(id)),
577 format!("because it's nested under this `unsafe` {}", kind),
584 fn builtin_derive_def_id(tcx: TyCtxt<'_>, def_id: DefId) -> Option<DefId> {
585 debug!("builtin_derive_def_id({:?})", def_id);
586 if let Some(impl_def_id) = tcx.impl_of_method(def_id) {
587 if tcx.has_attr(impl_def_id, sym::automatically_derived) {
588 debug!("builtin_derive_def_id({:?}) - is {:?}", def_id, impl_def_id);
591 debug!("builtin_derive_def_id({:?}) - not automatically derived", def_id);
595 debug!("builtin_derive_def_id({:?}) - not a method", def_id);
600 pub fn check_unsafety(tcx: TyCtxt<'_>, def_id: DefId) {
601 debug!("check_unsafety({:?})", def_id);
603 // closures are handled by their parent fn.
604 if tcx.is_closure(def_id) {
608 let UnsafetyCheckResult { violations, unsafe_blocks } = tcx.unsafety_check_result(def_id);
610 for &UnsafetyViolation { source_info, description, details, kind } in violations.iter() {
613 UnsafetyViolationKind::GeneralAndConstFn | UnsafetyViolationKind::General => {
618 "{} is unsafe and requires unsafe function or block",
621 .span_label(source_info.span, &*description.as_str())
622 .note(&details.as_str())
625 UnsafetyViolationKind::BorrowPacked(lint_hir_id) => {
626 if let Some(impl_def_id) = builtin_derive_def_id(tcx, def_id) {
627 tcx.unsafe_derive_on_repr_packed(impl_def_id);
629 tcx.struct_span_lint_hir(
635 "{} is unsafe and requires unsafe function or block (error E0133)",
638 .note(&details.as_str())
647 let mut unsafe_blocks: Vec<_> = unsafe_blocks.iter().collect();
648 unsafe_blocks.sort_by_cached_key(|(hir_id, _)| tcx.hir().hir_to_node_id(*hir_id));
649 let used_unsafe: FxHashSet<_> =
650 unsafe_blocks.iter().flat_map(|&&(id, used)| used.then_some(id)).collect();
651 for &(block_id, is_used) in unsafe_blocks {
653 report_unused_unsafe(tcx, &used_unsafe, block_id);