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::query::Providers;
11 use rustc_middle::ty::{self, TyCtxt};
12 use rustc_session::lint::builtin::{UNSAFE_OP_IN_UNSAFE_FN, UNUSED_UNSAFE};
13 use rustc_session::lint::Level;
17 pub struct UnsafetyChecker<'a, 'tcx> {
20 violations: Vec<UnsafetyViolation>,
21 source_info: SourceInfo,
23 param_env: ty::ParamEnv<'tcx>,
24 /// Mark an `unsafe` block as used, so we don't lint it.
25 used_unsafe: FxHashSet<hir::HirId>,
26 inherited_blocks: Vec<(hir::HirId, bool)>,
29 impl<'a, 'tcx> UnsafetyChecker<'a, 'tcx> {
34 param_env: ty::ParamEnv<'tcx>,
40 source_info: SourceInfo::outermost(body.span),
43 used_unsafe: Default::default(),
44 inherited_blocks: vec![],
49 impl<'tcx> Visitor<'tcx> for UnsafetyChecker<'_, 'tcx> {
50 fn visit_terminator(&mut self, terminator: &Terminator<'tcx>, location: Location) {
51 self.source_info = terminator.source_info;
52 match terminator.kind {
53 TerminatorKind::Goto { .. }
54 | TerminatorKind::SwitchInt { .. }
55 | TerminatorKind::Drop { .. }
56 | TerminatorKind::Yield { .. }
57 | TerminatorKind::Assert { .. }
58 | TerminatorKind::DropAndReplace { .. }
59 | TerminatorKind::GeneratorDrop
60 | TerminatorKind::Resume
61 | TerminatorKind::Abort
62 | TerminatorKind::Return
63 | TerminatorKind::Unreachable
64 | TerminatorKind::FalseEdge { .. }
65 | TerminatorKind::FalseUnwind { .. } => {
66 // safe (at least as emitted during MIR construction)
69 TerminatorKind::Call { ref func, .. } => {
70 let func_ty = func.ty(self.body, self.tcx);
71 let sig = func_ty.fn_sig(self.tcx);
72 if let hir::Unsafety::Unsafe = sig.unsafety() {
74 UnsafetyViolationKind::General,
75 UnsafetyViolationDetails::CallToUnsafeFunction,
79 if let ty::FnDef(func_id, _) = func_ty.kind() {
80 self.check_target_features(*func_id);
84 TerminatorKind::InlineAsm { .. } => self.require_unsafe(
85 UnsafetyViolationKind::General,
86 UnsafetyViolationDetails::UseOfInlineAssembly,
89 self.super_terminator(terminator, location);
92 fn visit_statement(&mut self, statement: &Statement<'tcx>, location: Location) {
93 self.source_info = statement.source_info;
94 match statement.kind {
95 StatementKind::Assign(..)
96 | StatementKind::FakeRead(..)
97 | StatementKind::SetDiscriminant { .. }
98 | StatementKind::StorageLive(..)
99 | StatementKind::StorageDead(..)
100 | StatementKind::Retag { .. }
101 | StatementKind::AscribeUserType(..)
102 | StatementKind::Coverage(..)
103 | StatementKind::Nop => {
104 // safe (at least as emitted during MIR construction)
107 StatementKind::CopyNonOverlapping(..) => unreachable!(),
109 self.super_statement(statement, location);
112 fn visit_rvalue(&mut self, rvalue: &Rvalue<'tcx>, location: Location) {
114 Rvalue::Aggregate(box ref aggregate, _) => match aggregate {
115 &AggregateKind::Array(..) | &AggregateKind::Tuple => {}
116 &AggregateKind::Adt(adt_did, ..) => {
117 match self.tcx.layout_scalar_valid_range(adt_did) {
118 (Bound::Unbounded, Bound::Unbounded) => {}
119 _ => self.require_unsafe(
120 UnsafetyViolationKind::General,
121 UnsafetyViolationDetails::InitializingTypeWith,
125 &AggregateKind::Closure(def_id, _) | &AggregateKind::Generator(def_id, _, _) => {
126 let UnsafetyCheckResult { violations, unsafe_blocks } =
127 self.tcx.unsafety_check_result(def_id.expect_local());
128 self.register_violations(&violations, &unsafe_blocks);
133 self.super_rvalue(rvalue, location);
136 fn visit_place(&mut self, place: &Place<'tcx>, context: PlaceContext, _location: Location) {
137 // On types with `scalar_valid_range`, prevent
140 // * `&x.field` if `field`'s type has interior mutability
141 // because either of these would allow modifying the layout constrained field and
142 // insert values that violate the layout constraints.
143 if context.is_mutating_use() || context.is_borrow() {
144 self.check_mut_borrowing_layout_constrained_field(*place, context.is_mutating_use());
147 // Some checks below need the extra metainfo of the local declaration.
148 let decl = &self.body.local_decls[place.local];
150 // Check the base local: it might be an unsafe-to-access static. We only check derefs of the
151 // temporary holding the static pointer to avoid duplicate errors
152 // <https://github.com/rust-lang/rust/pull/78068#issuecomment-731753506>.
153 if decl.internal && place.projection.first() == Some(&ProjectionElem::Deref) {
154 // If the projection root is an artifical local that we introduced when
155 // desugaring `static`, give a more specific error message
156 // (avoid the general "raw pointer" clause below, that would only be confusing).
157 if let Some(box LocalInfo::StaticRef { def_id, .. }) = decl.local_info {
158 if self.tcx.is_mutable_static(def_id) {
160 UnsafetyViolationKind::General,
161 UnsafetyViolationDetails::UseOfMutableStatic,
164 } else if self.tcx.is_foreign_item(def_id) {
166 UnsafetyViolationKind::General,
167 UnsafetyViolationDetails::UseOfExternStatic,
174 // Check for raw pointer `Deref`.
175 for (base, proj) in place.iter_projections() {
176 if proj == ProjectionElem::Deref {
177 let base_ty = base.ty(self.body, self.tcx).ty;
178 if base_ty.is_unsafe_ptr() {
180 UnsafetyViolationKind::General,
181 UnsafetyViolationDetails::DerefOfRawPointer,
187 // Check for union fields. For this we traverse right-to-left, as the last `Deref` changes
188 // whether we *read* the union field or potentially *write* to it (if this place is being assigned to).
189 let mut saw_deref = false;
190 for (base, proj) in place.iter_projections().rev() {
191 if proj == ProjectionElem::Deref {
196 let base_ty = base.ty(self.body, self.tcx).ty;
197 if base_ty.is_union() {
198 // If we did not hit a `Deref` yet and the overall place use is an assignment, the
199 // rules are different.
200 let assign_to_field = !saw_deref
203 PlaceContext::MutatingUse(
204 MutatingUseContext::Store
205 | MutatingUseContext::Drop
206 | MutatingUseContext::AsmOutput
209 // If this is just an assignment, determine if the assigned type needs dropping.
211 // We have to check the actual type of the assignment, as that determines if the
212 // old value is being dropped.
213 let assigned_ty = place.ty(&self.body.local_decls, self.tcx).ty;
214 // To avoid semver hazard, we only consider `Copy` and `ManuallyDrop` non-dropping.
215 let manually_drop = assigned_ty
217 .map_or(false, |adt_def| adt_def.is_manually_drop());
218 let nodrop = manually_drop
219 || assigned_ty.is_copy_modulo_regions(
220 self.tcx.at(self.source_info.span),
225 UnsafetyViolationKind::General,
226 UnsafetyViolationDetails::AssignToDroppingUnionField,
229 // write to non-drop union field, safe
233 UnsafetyViolationKind::General,
234 UnsafetyViolationDetails::AccessToUnionField,
242 impl<'tcx> UnsafetyChecker<'_, 'tcx> {
243 fn require_unsafe(&mut self, kind: UnsafetyViolationKind, details: UnsafetyViolationDetails) {
244 // Violations can turn out to be `UnsafeFn` during analysis, but they should not start out as such.
245 assert_ne!(kind, UnsafetyViolationKind::UnsafeFn);
247 let source_info = self.source_info;
248 let lint_root = self.body.source_scopes[self.source_info.scope]
251 .assert_crate_local()
253 self.register_violations(
254 &[UnsafetyViolation { source_info, lint_root, kind, details }],
259 fn register_violations(
261 violations: &[UnsafetyViolation],
262 unsafe_blocks: &[(hir::HirId, bool)],
264 let safety = self.body.source_scopes[self.source_info.scope]
267 .assert_crate_local()
269 let within_unsafe = match safety {
270 // `unsafe` blocks are required in safe code
272 for violation in violations {
273 match violation.kind {
274 UnsafetyViolationKind::General => {}
275 UnsafetyViolationKind::UnsafeFn => {
276 bug!("`UnsafetyViolationKind::UnsafeFn` in an `Safe` context")
279 if !self.violations.contains(violation) {
280 self.violations.push(*violation)
285 // With the RFC 2585, no longer allow `unsafe` operations in `unsafe fn`s
286 Safety::FnUnsafe => {
287 for violation in violations {
288 let mut violation = *violation;
290 violation.kind = UnsafetyViolationKind::UnsafeFn;
291 if !self.violations.contains(&violation) {
292 self.violations.push(violation)
297 Safety::BuiltinUnsafe => true,
298 Safety::ExplicitUnsafe(hir_id) => {
299 // mark unsafe block as used if there are any unsafe operations inside
300 if !violations.is_empty() {
301 self.used_unsafe.insert(hir_id);
306 self.inherited_blocks.extend(
307 unsafe_blocks.iter().map(|&(hir_id, is_used)| (hir_id, is_used && !within_unsafe)),
310 fn check_mut_borrowing_layout_constrained_field(
315 for (place_base, elem) in place.iter_projections().rev() {
317 // Modifications behind a dereference don't affect the value of
319 ProjectionElem::Deref => return,
320 ProjectionElem::Field(..) => {
321 let ty = place_base.ty(&self.body.local_decls, self.tcx).ty;
322 if let ty::Adt(def, _) = ty.kind() {
323 if self.tcx.layout_scalar_valid_range(def.did)
324 != (Bound::Unbounded, Bound::Unbounded)
326 let details = if is_mut_use {
327 UnsafetyViolationDetails::MutationOfLayoutConstrainedField
329 // Check `is_freeze` as late as possible to avoid cycle errors
330 // with opaque types.
332 .ty(self.body, self.tcx)
334 .is_freeze(self.tcx.at(self.source_info.span), self.param_env)
336 UnsafetyViolationDetails::BorrowOfLayoutConstrainedField
340 self.require_unsafe(UnsafetyViolationKind::General, details);
349 /// Checks whether calling `func_did` needs an `unsafe` context or not, i.e. whether
350 /// the called function has target features the calling function hasn't.
351 fn check_target_features(&mut self, func_did: DefId) {
352 // Unsafety isn't required on wasm targets. For more information see
353 // the corresponding check in typeck/src/collect.rs
354 if self.tcx.sess.target.options.is_like_wasm {
358 let callee_features = &self.tcx.codegen_fn_attrs(func_did).target_features;
359 let self_features = &self.tcx.codegen_fn_attrs(self.body_did).target_features;
361 // Is `callee_features` a subset of `calling_features`?
362 if !callee_features.iter().all(|feature| self_features.contains(feature)) {
364 UnsafetyViolationKind::General,
365 UnsafetyViolationDetails::CallToFunctionWith,
371 pub(crate) fn provide(providers: &mut Providers) {
372 *providers = Providers {
373 unsafety_check_result: |tcx, def_id| {
374 if let Some(def) = ty::WithOptConstParam::try_lookup(def_id, tcx) {
375 tcx.unsafety_check_result_for_const_arg(def)
377 unsafety_check_result(tcx, ty::WithOptConstParam::unknown(def_id))
380 unsafety_check_result_for_const_arg: |tcx, (did, param_did)| {
381 unsafety_check_result(
383 ty::WithOptConstParam { did, const_param_did: Some(param_did) },
390 struct UnusedUnsafeVisitor<'a> {
391 used_unsafe: &'a FxHashSet<hir::HirId>,
392 unsafe_blocks: &'a mut Vec<(hir::HirId, bool)>,
395 impl<'tcx> intravisit::Visitor<'tcx> for UnusedUnsafeVisitor<'_> {
396 fn visit_block(&mut self, block: &'tcx hir::Block<'tcx>) {
397 intravisit::walk_block(self, block);
399 if let hir::BlockCheckMode::UnsafeBlock(hir::UnsafeSource::UserProvided) = block.rules {
400 self.unsafe_blocks.push((block.hir_id, self.used_unsafe.contains(&block.hir_id)));
405 fn check_unused_unsafe(
408 used_unsafe: &FxHashSet<hir::HirId>,
409 unsafe_blocks: &mut Vec<(hir::HirId, bool)>,
411 let body_id = tcx.hir().maybe_body_owned_by(tcx.hir().local_def_id_to_hir_id(def_id));
413 let body_id = match body_id {
416 debug!("check_unused_unsafe({:?}) - no body found", def_id);
420 let body = tcx.hir().body(body_id);
421 debug!("check_unused_unsafe({:?}, body={:?}, used_unsafe={:?})", def_id, body, used_unsafe);
423 let mut visitor = UnusedUnsafeVisitor { used_unsafe, unsafe_blocks };
424 intravisit::Visitor::visit_body(&mut visitor, body);
427 fn unsafety_check_result<'tcx>(
429 def: ty::WithOptConstParam<LocalDefId>,
430 ) -> &'tcx UnsafetyCheckResult {
431 debug!("unsafety_violations({:?})", def);
433 // N.B., this borrow is valid because all the consumers of
434 // `mir_built` force this.
435 let body = &tcx.mir_built(def).borrow();
437 let param_env = tcx.param_env(def.did);
439 let mut checker = UnsafetyChecker::new(body, def.did, tcx, param_env);
440 checker.visit_body(&body);
442 check_unused_unsafe(tcx, def.did, &checker.used_unsafe, &mut checker.inherited_blocks);
444 tcx.arena.alloc(UnsafetyCheckResult {
445 violations: checker.violations.into(),
446 unsafe_blocks: checker.inherited_blocks.into(),
450 /// Returns the `HirId` for an enclosing scope that is also `unsafe`.
453 used_unsafe: &FxHashSet<hir::HirId>,
455 unsafe_op_in_unsafe_fn_allowed: bool,
456 ) -> Option<(&'static str, hir::HirId)> {
457 let parent_id = tcx.hir().get_parent_node(id);
459 if used_unsafe.contains(&parent_id) {
460 Some(("block", parent_id))
461 } else if let Some(Node::Item(&hir::Item {
462 kind: hir::ItemKind::Fn(ref sig, _, _), ..
463 })) = tcx.hir().find(parent_id)
465 if sig.header.unsafety == hir::Unsafety::Unsafe && unsafe_op_in_unsafe_fn_allowed {
466 Some(("fn", parent_id))
471 is_enclosed(tcx, used_unsafe, parent_id, unsafe_op_in_unsafe_fn_allowed)
478 fn report_unused_unsafe(tcx: TyCtxt<'_>, used_unsafe: &FxHashSet<hir::HirId>, id: hir::HirId) {
479 let span = tcx.sess.source_map().guess_head_span(tcx.hir().span(id));
480 tcx.struct_span_lint_hir(UNUSED_UNSAFE, id, span, |lint| {
481 let msg = "unnecessary `unsafe` block";
482 let mut db = lint.build(msg);
483 db.span_label(span, msg);
484 if let Some((kind, id)) =
485 is_enclosed(tcx, used_unsafe, id, unsafe_op_in_unsafe_fn_allowed(tcx, id))
488 tcx.sess.source_map().guess_head_span(tcx.hir().span(id)),
489 format!("because it's nested under this `unsafe` {}", kind),
496 pub fn check_unsafety(tcx: TyCtxt<'_>, def_id: LocalDefId) {
497 debug!("check_unsafety({:?})", def_id);
499 // closures are handled by their parent fn.
500 if tcx.is_closure(def_id.to_def_id()) {
504 let UnsafetyCheckResult { violations, unsafe_blocks } = tcx.unsafety_check_result(def_id);
506 for &UnsafetyViolation { source_info, lint_root, kind, details } in violations.iter() {
507 let (description, note) = details.description_and_note();
511 if unsafe_op_in_unsafe_fn_allowed(tcx, lint_root) { " function or" } else { "" };
514 UnsafetyViolationKind::General => {
520 "{} is unsafe and requires unsafe{} block",
524 .span_label(source_info.span, description)
528 UnsafetyViolationKind::UnsafeFn => tcx.struct_span_lint_hir(
529 UNSAFE_OP_IN_UNSAFE_FN,
534 "{} is unsafe and requires unsafe block (error E0133)",
537 .span_label(source_info.span, description)
545 let (mut unsafe_used, mut unsafe_unused): (FxHashSet<_>, Vec<_>) = Default::default();
546 for &(block_id, is_used) in unsafe_blocks.iter() {
548 unsafe_used.insert(block_id);
550 unsafe_unused.push(block_id);
553 // The unused unsafe blocks might not be in source order; sort them so that the unused unsafe
554 // error messages are properly aligned and the issue-45107 and lint-unused-unsafe tests pass.
555 unsafe_unused.sort_by_cached_key(|hir_id| tcx.hir().span(*hir_id));
557 for &block_id in &unsafe_unused {
558 report_unused_unsafe(tcx, &unsafe_used, block_id);
562 fn unsafe_op_in_unsafe_fn_allowed(tcx: TyCtxt<'_>, id: HirId) -> bool {
563 tcx.lint_level_at_node(UNSAFE_OP_IN_UNSAFE_FN, id).0 == Level::Allow