1 use rustc_data_structures::fx::FxHashSet;
2 use rustc_errors::struct_span_err;
4 use rustc_hir::def_id::{DefId, LocalDefId};
5 use rustc_hir::hir_id::HirId;
6 use rustc_hir::intravisit;
8 use rustc_middle::mir::visit::{MutatingUseContext, PlaceContext, Visitor};
9 use rustc_middle::mir::*;
10 use rustc_middle::ty::cast::CastTy;
11 use rustc_middle::ty::query::Providers;
12 use rustc_middle::ty::{self, TyCtxt};
13 use rustc_session::lint::builtin::{UNSAFE_OP_IN_UNSAFE_FN, UNUSED_UNSAFE};
14 use rustc_session::lint::Level;
18 pub struct UnsafetyChecker<'a, 'tcx> {
22 violations: Vec<UnsafetyViolation>,
23 source_info: SourceInfo,
25 param_env: ty::ParamEnv<'tcx>,
26 /// Mark an `unsafe` block as used, so we don't lint it.
27 used_unsafe: FxHashSet<hir::HirId>,
28 inherited_blocks: Vec<(hir::HirId, bool)>,
31 impl<'a, 'tcx> UnsafetyChecker<'a, 'tcx> {
37 param_env: ty::ParamEnv<'tcx>,
44 source_info: SourceInfo::outermost(body.span),
47 used_unsafe: Default::default(),
48 inherited_blocks: vec![],
53 impl<'a, 'tcx> Visitor<'tcx> for UnsafetyChecker<'a, 'tcx> {
54 fn visit_terminator(&mut self, terminator: &Terminator<'tcx>, location: Location) {
55 self.source_info = terminator.source_info;
56 match terminator.kind {
57 TerminatorKind::Goto { .. }
58 | TerminatorKind::SwitchInt { .. }
59 | TerminatorKind::Drop { .. }
60 | TerminatorKind::Yield { .. }
61 | TerminatorKind::Assert { .. }
62 | TerminatorKind::DropAndReplace { .. }
63 | TerminatorKind::GeneratorDrop
64 | TerminatorKind::Resume
65 | TerminatorKind::Abort
66 | TerminatorKind::Return
67 | TerminatorKind::Unreachable
68 | TerminatorKind::FalseEdge { .. }
69 | TerminatorKind::FalseUnwind { .. } => {
70 // safe (at least as emitted during MIR construction)
73 TerminatorKind::Call { ref func, .. } => {
74 let func_ty = func.ty(self.body, self.tcx);
75 let sig = func_ty.fn_sig(self.tcx);
76 if let hir::Unsafety::Unsafe = sig.unsafety() {
78 UnsafetyViolationKind::General,
79 UnsafetyViolationDetails::CallToUnsafeFunction,
83 if let ty::FnDef(func_id, _) = func_ty.kind() {
84 self.check_target_features(*func_id);
88 TerminatorKind::InlineAsm { .. } => self.require_unsafe(
89 UnsafetyViolationKind::General,
90 UnsafetyViolationDetails::UseOfInlineAssembly,
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::Coverage(..)
107 | StatementKind::Nop => {
108 // safe (at least as emitted during MIR construction)
111 StatementKind::LlvmInlineAsm { .. } => self.require_unsafe(
112 UnsafetyViolationKind::General,
113 UnsafetyViolationDetails::UseOfInlineAssembly,
115 StatementKind::CopyNonOverlapping(..) => unreachable!(),
117 self.super_statement(statement, location);
120 fn visit_rvalue(&mut self, rvalue: &Rvalue<'tcx>, location: Location) {
122 Rvalue::Aggregate(box ref aggregate, _) => match aggregate {
123 &AggregateKind::Array(..) | &AggregateKind::Tuple => {}
124 &AggregateKind::Adt(ref def, ..) => {
125 match self.tcx.layout_scalar_valid_range(def.did) {
126 (Bound::Unbounded, Bound::Unbounded) => {}
127 _ => self.require_unsafe(
128 UnsafetyViolationKind::General,
129 UnsafetyViolationDetails::InitializingTypeWith,
133 &AggregateKind::Closure(def_id, _) | &AggregateKind::Generator(def_id, _, _) => {
134 let UnsafetyCheckResult { violations, unsafe_blocks } =
135 self.tcx.unsafety_check_result(def_id.expect_local());
136 self.register_violations(&violations, &unsafe_blocks);
139 // casting pointers to ints is unsafe in const fn because the const evaluator cannot
140 // possibly know what the result of various operations like `address / 2` would be
141 // pointers during const evaluation have no integral address, only an abstract one
142 Rvalue::Cast(CastKind::Misc, ref operand, cast_ty)
143 if self.const_context && self.tcx.features().const_raw_ptr_to_usize_cast =>
145 let operand_ty = operand.ty(self.body, self.tcx);
146 let cast_in = CastTy::from_ty(operand_ty).expect("bad input type for cast");
147 let cast_out = CastTy::from_ty(cast_ty).expect("bad output type for cast");
148 match (cast_in, cast_out) {
149 (CastTy::Ptr(_) | CastTy::FnPtr, CastTy::Int(_)) => {
151 UnsafetyViolationKind::General,
152 UnsafetyViolationDetails::CastOfPointerToInt,
160 self.super_rvalue(rvalue, location);
163 fn visit_place(&mut self, place: &Place<'tcx>, context: PlaceContext, _location: Location) {
164 // On types with `scalar_valid_range`, prevent
167 // * `&x.field` if `field`'s type has interior mutability
168 // because either of these would allow modifying the layout constrained field and
169 // insert values that violate the layout constraints.
170 if context.is_mutating_use() || context.is_borrow() {
171 self.check_mut_borrowing_layout_constrained_field(*place, context.is_mutating_use());
174 // Some checks below need the extra metainfo of the local declaration.
175 let decl = &self.body.local_decls[place.local];
177 // Check the base local: it might be an unsafe-to-access static. We only check derefs of the
178 // temporary holding the static pointer to avoid duplicate errors
179 // <https://github.com/rust-lang/rust/pull/78068#issuecomment-731753506>.
180 if decl.internal && place.projection.first() == Some(&ProjectionElem::Deref) {
181 // If the projection root is an artifical local that we introduced when
182 // desugaring `static`, give a more specific error message
183 // (avoid the general "raw pointer" clause below, that would only be confusing).
184 if let Some(box LocalInfo::StaticRef { def_id, .. }) = decl.local_info {
185 if self.tcx.is_mutable_static(def_id) {
187 UnsafetyViolationKind::General,
188 UnsafetyViolationDetails::UseOfMutableStatic,
191 } else if self.tcx.is_foreign_item(def_id) {
193 UnsafetyViolationKind::General,
194 UnsafetyViolationDetails::UseOfExternStatic,
201 // Check for raw pointer `Deref`.
202 for (base, proj) in place.iter_projections() {
203 if proj == ProjectionElem::Deref {
204 let base_ty = base.ty(self.body, self.tcx).ty;
205 if base_ty.is_unsafe_ptr() {
207 UnsafetyViolationKind::General,
208 UnsafetyViolationDetails::DerefOfRawPointer,
214 // Check for union fields. For this we traverse right-to-left, as the last `Deref` changes
215 // whether we *read* the union field or potentially *write* to it (if this place is being assigned to).
216 let mut saw_deref = false;
217 for (base, proj) in place.iter_projections().rev() {
218 if proj == ProjectionElem::Deref {
223 let base_ty = base.ty(self.body, self.tcx).ty;
224 if base_ty.is_union() {
225 // If we did not hit a `Deref` yet and the overall place use is an assignment, the
226 // rules are different.
227 let assign_to_field = !saw_deref
230 PlaceContext::MutatingUse(
231 MutatingUseContext::Store
232 | MutatingUseContext::Drop
233 | MutatingUseContext::AsmOutput
236 // If this is just an assignment, determine if the assigned type needs dropping.
238 // We have to check the actual type of the assignment, as that determines if the
239 // old value is being dropped.
240 let assigned_ty = place.ty(&self.body.local_decls, self.tcx).ty;
241 // To avoid semver hazard, we only consider `Copy` and `ManuallyDrop` non-dropping.
242 let manually_drop = assigned_ty
244 .map_or(false, |adt_def| adt_def.is_manually_drop());
245 let nodrop = manually_drop
246 || assigned_ty.is_copy_modulo_regions(
247 self.tcx.at(self.source_info.span),
252 UnsafetyViolationKind::General,
253 UnsafetyViolationDetails::AssignToDroppingUnionField,
256 // write to non-drop union field, safe
260 UnsafetyViolationKind::General,
261 UnsafetyViolationDetails::AccessToUnionField,
269 impl<'a, 'tcx> UnsafetyChecker<'a, 'tcx> {
270 fn require_unsafe(&mut self, kind: UnsafetyViolationKind, details: UnsafetyViolationDetails) {
271 // Violations can turn out to be `UnsafeFn` during analysis, but they should not start out as such.
272 assert_ne!(kind, UnsafetyViolationKind::UnsafeFn);
274 let source_info = self.source_info;
275 let lint_root = self.body.source_scopes[self.source_info.scope]
278 .assert_crate_local()
280 self.register_violations(
281 &[UnsafetyViolation { source_info, lint_root, kind, details }],
286 fn register_violations(
288 violations: &[UnsafetyViolation],
289 unsafe_blocks: &[(hir::HirId, bool)],
291 let safety = self.body.source_scopes[self.source_info.scope]
294 .assert_crate_local()
296 let within_unsafe = match safety {
297 // `unsafe` blocks are required in safe code
299 for violation in violations {
300 match violation.kind {
301 UnsafetyViolationKind::General => {}
302 UnsafetyViolationKind::UnsafeFn => {
303 bug!("`UnsafetyViolationKind::UnsafeFn` in an `Safe` context")
306 if !self.violations.contains(violation) {
307 self.violations.push(*violation)
312 // With the RFC 2585, no longer allow `unsafe` operations in `unsafe fn`s
313 Safety::FnUnsafe => {
314 for violation in violations {
315 let mut violation = *violation;
317 violation.kind = UnsafetyViolationKind::UnsafeFn;
318 if !self.violations.contains(&violation) {
319 self.violations.push(violation)
324 Safety::BuiltinUnsafe => true,
325 Safety::ExplicitUnsafe(hir_id) => {
326 // mark unsafe block as used if there are any unsafe operations inside
327 if !violations.is_empty() {
328 self.used_unsafe.insert(hir_id);
333 self.inherited_blocks.extend(
334 unsafe_blocks.iter().map(|&(hir_id, is_used)| (hir_id, is_used && !within_unsafe)),
337 fn check_mut_borrowing_layout_constrained_field(
342 for (place_base, elem) in place.iter_projections().rev() {
344 // Modifications behind a dereference don't affect the value of
346 ProjectionElem::Deref => return,
347 ProjectionElem::Field(..) => {
348 let ty = place_base.ty(&self.body.local_decls, self.tcx).ty;
349 if let ty::Adt(def, _) = ty.kind() {
350 if self.tcx.layout_scalar_valid_range(def.did)
351 != (Bound::Unbounded, Bound::Unbounded)
353 let details = if is_mut_use {
354 UnsafetyViolationDetails::MutationOfLayoutConstrainedField
356 // Check `is_freeze` as late as possible to avoid cycle errors
357 // with opaque types.
359 .ty(self.body, self.tcx)
361 .is_freeze(self.tcx.at(self.source_info.span), self.param_env)
363 UnsafetyViolationDetails::BorrowOfLayoutConstrainedField
367 self.require_unsafe(UnsafetyViolationKind::General, details);
376 /// Checks whether calling `func_did` needs an `unsafe` context or not, i.e. whether
377 /// the called function has target features the calling function hasn't.
378 fn check_target_features(&mut self, func_did: DefId) {
379 // Unsafety isn't required on wasm targets. For more information see
380 // the corresponding check in typeck/src/collect.rs
381 if self.tcx.sess.target.options.is_like_wasm {
385 let callee_features = &self.tcx.codegen_fn_attrs(func_did).target_features;
386 let self_features = &self.tcx.codegen_fn_attrs(self.body_did).target_features;
388 // Is `callee_features` a subset of `calling_features`?
389 if !callee_features.iter().all(|feature| self_features.contains(feature)) {
391 UnsafetyViolationKind::General,
392 UnsafetyViolationDetails::CallToFunctionWith,
398 pub(crate) fn provide(providers: &mut Providers) {
399 *providers = Providers {
400 unsafety_check_result: |tcx, def_id| {
401 if let Some(def) = ty::WithOptConstParam::try_lookup(def_id, tcx) {
402 tcx.unsafety_check_result_for_const_arg(def)
404 unsafety_check_result(tcx, ty::WithOptConstParam::unknown(def_id))
407 unsafety_check_result_for_const_arg: |tcx, (did, param_did)| {
408 unsafety_check_result(
410 ty::WithOptConstParam { did, const_param_did: Some(param_did) },
417 struct UnusedUnsafeVisitor<'a> {
418 used_unsafe: &'a FxHashSet<hir::HirId>,
419 unsafe_blocks: &'a mut Vec<(hir::HirId, bool)>,
422 impl<'a, 'tcx> intravisit::Visitor<'tcx> for UnusedUnsafeVisitor<'a> {
423 type Map = intravisit::ErasedMap<'tcx>;
425 fn nested_visit_map(&mut self) -> intravisit::NestedVisitorMap<Self::Map> {
426 intravisit::NestedVisitorMap::None
429 fn visit_block(&mut self, block: &'tcx hir::Block<'tcx>) {
430 intravisit::walk_block(self, block);
432 if let hir::BlockCheckMode::UnsafeBlock(hir::UnsafeSource::UserProvided) = block.rules {
433 self.unsafe_blocks.push((block.hir_id, self.used_unsafe.contains(&block.hir_id)));
438 fn check_unused_unsafe(
441 used_unsafe: &FxHashSet<hir::HirId>,
442 unsafe_blocks: &mut Vec<(hir::HirId, bool)>,
444 let body_id = tcx.hir().maybe_body_owned_by(tcx.hir().local_def_id_to_hir_id(def_id));
446 let body_id = match body_id {
449 debug!("check_unused_unsafe({:?}) - no body found", def_id);
453 let body = tcx.hir().body(body_id);
454 debug!("check_unused_unsafe({:?}, body={:?}, used_unsafe={:?})", def_id, body, used_unsafe);
456 let mut visitor = UnusedUnsafeVisitor { used_unsafe, unsafe_blocks };
457 intravisit::Visitor::visit_body(&mut visitor, body);
460 fn unsafety_check_result<'tcx>(
462 def: ty::WithOptConstParam<LocalDefId>,
463 ) -> &'tcx UnsafetyCheckResult {
464 debug!("unsafety_violations({:?})", def);
466 // N.B., this borrow is valid because all the consumers of
467 // `mir_built` force this.
468 let body = &tcx.mir_built(def).borrow();
470 let param_env = tcx.param_env(def.did);
472 let id = tcx.hir().local_def_id_to_hir_id(def.did);
473 let const_context = match tcx.hir().body_owner_kind(id) {
474 hir::BodyOwnerKind::Closure => false,
475 hir::BodyOwnerKind::Fn => tcx.is_const_fn_raw(def.did.to_def_id()),
476 hir::BodyOwnerKind::Const | hir::BodyOwnerKind::Static(_) => true,
478 let mut checker = UnsafetyChecker::new(const_context, body, def.did, tcx, param_env);
479 checker.visit_body(&body);
481 check_unused_unsafe(tcx, def.did, &checker.used_unsafe, &mut checker.inherited_blocks);
483 tcx.arena.alloc(UnsafetyCheckResult {
484 violations: checker.violations.into(),
485 unsafe_blocks: checker.inherited_blocks.into(),
489 /// Returns the `HirId` for an enclosing scope that is also `unsafe`.
492 used_unsafe: &FxHashSet<hir::HirId>,
494 unsafe_op_in_unsafe_fn_allowed: bool,
495 ) -> Option<(&'static str, hir::HirId)> {
496 let parent_id = tcx.hir().get_parent_node(id);
498 if used_unsafe.contains(&parent_id) {
499 Some(("block", parent_id))
500 } else if let Some(Node::Item(&hir::Item {
501 kind: hir::ItemKind::Fn(ref sig, _, _), ..
502 })) = tcx.hir().find(parent_id)
504 if sig.header.unsafety == hir::Unsafety::Unsafe && unsafe_op_in_unsafe_fn_allowed {
505 Some(("fn", parent_id))
510 is_enclosed(tcx, used_unsafe, parent_id, unsafe_op_in_unsafe_fn_allowed)
517 fn report_unused_unsafe(tcx: TyCtxt<'_>, used_unsafe: &FxHashSet<hir::HirId>, id: hir::HirId) {
518 let span = tcx.sess.source_map().guess_head_span(tcx.hir().span(id));
519 tcx.struct_span_lint_hir(UNUSED_UNSAFE, id, span, |lint| {
520 let msg = "unnecessary `unsafe` block";
521 let mut db = lint.build(msg);
522 db.span_label(span, msg);
523 if let Some((kind, id)) =
524 is_enclosed(tcx, used_unsafe, id, unsafe_op_in_unsafe_fn_allowed(tcx, id))
527 tcx.sess.source_map().guess_head_span(tcx.hir().span(id)),
528 format!("because it's nested under this `unsafe` {}", kind),
535 pub fn check_unsafety(tcx: TyCtxt<'_>, def_id: LocalDefId) {
536 debug!("check_unsafety({:?})", def_id);
538 // closures are handled by their parent fn.
539 if tcx.is_closure(def_id.to_def_id()) {
543 let UnsafetyCheckResult { violations, unsafe_blocks } = tcx.unsafety_check_result(def_id);
545 for &UnsafetyViolation { source_info, lint_root, kind, details } in violations.iter() {
546 let (description, note) = details.description_and_note();
550 if unsafe_op_in_unsafe_fn_allowed(tcx, lint_root) { " function or" } else { "" };
553 UnsafetyViolationKind::General => {
559 "{} is unsafe and requires unsafe{} block",
563 .span_label(source_info.span, description)
567 UnsafetyViolationKind::UnsafeFn => tcx.struct_span_lint_hir(
568 UNSAFE_OP_IN_UNSAFE_FN,
573 "{} is unsafe and requires unsafe block (error E0133)",
576 .span_label(source_info.span, description)
584 let (mut unsafe_used, mut unsafe_unused): (FxHashSet<_>, Vec<_>) = Default::default();
585 for &(block_id, is_used) in unsafe_blocks.iter() {
587 unsafe_used.insert(block_id);
589 unsafe_unused.push(block_id);
592 // The unused unsafe blocks might not be in source order; sort them so that the unused unsafe
593 // error messages are properly aligned and the issue-45107 and lint-unused-unsafe tests pass.
594 unsafe_unused.sort_by_cached_key(|hir_id| tcx.hir().span(*hir_id));
596 for &block_id in &unsafe_unused {
597 report_unused_unsafe(tcx, &unsafe_used, block_id);
601 fn unsafe_op_in_unsafe_fn_allowed(tcx: TyCtxt<'_>, id: HirId) -> bool {
602 tcx.lint_level_at_node(UNSAFE_OP_IN_UNSAFE_FN, id).0 == Level::Allow