1 use rustc_data_structures::fx::FxHashSet;
2 use rustc_errors::struct_span_err;
4 use rustc_hir::def::DefKind;
5 use rustc_hir::def_id::{DefId, LocalDefId};
6 use rustc_hir::hir_id::HirId;
7 use rustc_hir::intravisit;
8 use rustc_hir::{BlockCheckMode, ExprKind, Node};
9 use rustc_middle::mir::visit::{MutatingUseContext, PlaceContext, Visitor};
10 use rustc_middle::mir::*;
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> {
21 violations: Vec<UnsafetyViolation>,
22 source_info: SourceInfo,
24 param_env: ty::ParamEnv<'tcx>,
26 /// Used `unsafe` blocks in this function. This is used for the "unused_unsafe" lint.
27 used_unsafe_blocks: FxHashSet<HirId>,
30 impl<'a, 'tcx> UnsafetyChecker<'a, 'tcx> {
35 param_env: ty::ParamEnv<'tcx>,
41 source_info: SourceInfo::outermost(body.span),
44 used_unsafe_blocks: Default::default(),
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);
72 if let ty::FnDef(func_id, _) = func_ty.kind() { Some(func_id) } else { None };
73 let sig = func_ty.fn_sig(self.tcx);
74 if let hir::Unsafety::Unsafe = sig.unsafety() {
76 UnsafetyViolationKind::General,
77 UnsafetyViolationDetails::CallToUnsafeFunction,
81 if let Some(func_id) = func_id {
82 self.check_target_features(*func_id);
86 TerminatorKind::InlineAsm { .. } => self.require_unsafe(
87 UnsafetyViolationKind::General,
88 UnsafetyViolationDetails::UseOfInlineAssembly,
91 self.super_terminator(terminator, location);
94 fn visit_statement(&mut self, statement: &Statement<'tcx>, location: Location) {
95 self.source_info = statement.source_info;
96 match statement.kind {
97 StatementKind::Assign(..)
98 | StatementKind::FakeRead(..)
99 | StatementKind::SetDiscriminant { .. }
100 | StatementKind::Deinit(..)
101 | StatementKind::StorageLive(..)
102 | StatementKind::StorageDead(..)
103 | StatementKind::Retag { .. }
104 | StatementKind::AscribeUserType(..)
105 | StatementKind::Coverage(..)
106 | StatementKind::Intrinsic(..)
107 | StatementKind::Nop => {
108 // safe (at least as emitted during MIR construction)
111 self.super_statement(statement, location);
114 fn visit_rvalue(&mut self, rvalue: &Rvalue<'tcx>, location: Location) {
116 Rvalue::Aggregate(box ref aggregate, _) => match aggregate {
117 &AggregateKind::Array(..) | &AggregateKind::Tuple => {}
118 &AggregateKind::Adt(adt_did, ..) => {
119 match self.tcx.layout_scalar_valid_range(adt_did) {
120 (Bound::Unbounded, Bound::Unbounded) => {}
121 _ => self.require_unsafe(
122 UnsafetyViolationKind::General,
123 UnsafetyViolationDetails::InitializingTypeWith,
127 &AggregateKind::Closure(def_id, _) | &AggregateKind::Generator(def_id, _, _) => {
128 let UnsafetyCheckResult { violations, used_unsafe_blocks, .. } =
129 self.tcx.unsafety_check_result(def_id);
130 self.register_violations(violations, used_unsafe_blocks.iter().copied());
135 self.super_rvalue(rvalue, location);
138 fn visit_operand(&mut self, op: &Operand<'tcx>, location: Location) {
139 if let Operand::Constant(constant) = op {
140 let maybe_uneval = match constant.literal {
141 ConstantKind::Val(..) | ConstantKind::Ty(_) => None,
142 ConstantKind::Unevaluated(uv, _) => Some(uv),
145 if let Some(uv) = maybe_uneval {
146 if uv.promoted.is_none() {
147 let def_id = uv.def.def_id_for_type_of();
148 if self.tcx.def_kind(def_id) == DefKind::InlineConst {
149 let local_def_id = def_id.expect_local();
150 let UnsafetyCheckResult { violations, used_unsafe_blocks, .. } =
151 self.tcx.unsafety_check_result(local_def_id);
152 self.register_violations(violations, used_unsafe_blocks.iter().copied());
157 self.super_operand(op, location);
160 fn visit_place(&mut self, place: &Place<'tcx>, context: PlaceContext, _location: Location) {
161 // On types with `scalar_valid_range`, prevent
164 // * `&x.field` if `field`'s type has interior mutability
165 // because either of these would allow modifying the layout constrained field and
166 // insert values that violate the layout constraints.
167 if context.is_mutating_use() || context.is_borrow() {
168 self.check_mut_borrowing_layout_constrained_field(*place, context.is_mutating_use());
171 // Some checks below need the extra meta info of the local declaration.
172 let decl = &self.body.local_decls[place.local];
174 // Check the base local: it might be an unsafe-to-access static. We only check derefs of the
175 // temporary holding the static pointer to avoid duplicate errors
176 // <https://github.com/rust-lang/rust/pull/78068#issuecomment-731753506>.
177 if decl.internal && place.projection.first() == Some(&ProjectionElem::Deref) {
178 // If the projection root is an artificial local that we introduced when
179 // desugaring `static`, give a more specific error message
180 // (avoid the general "raw pointer" clause below, that would only be confusing).
181 if let Some(box LocalInfo::StaticRef { def_id, .. }) = decl.local_info {
182 if self.tcx.is_mutable_static(def_id) {
184 UnsafetyViolationKind::General,
185 UnsafetyViolationDetails::UseOfMutableStatic,
188 } else if self.tcx.is_foreign_item(def_id) {
190 UnsafetyViolationKind::General,
191 UnsafetyViolationDetails::UseOfExternStatic,
198 // Check for raw pointer `Deref`.
199 for (base, proj) in place.iter_projections() {
200 if proj == ProjectionElem::Deref {
201 let base_ty = base.ty(self.body, self.tcx).ty;
202 if base_ty.is_unsafe_ptr() {
204 UnsafetyViolationKind::General,
205 UnsafetyViolationDetails::DerefOfRawPointer,
211 // Check for union fields. For this we traverse right-to-left, as the last `Deref` changes
212 // whether we *read* the union field or potentially *write* to it (if this place is being assigned to).
213 let mut saw_deref = false;
214 for (base, proj) in place.iter_projections().rev() {
215 if proj == ProjectionElem::Deref {
220 let base_ty = base.ty(self.body, self.tcx).ty;
221 if base_ty.is_union() {
222 // If we did not hit a `Deref` yet and the overall place use is an assignment, the
223 // rules are different.
224 let assign_to_field = !saw_deref
227 PlaceContext::MutatingUse(
228 MutatingUseContext::Store
229 | MutatingUseContext::Drop
230 | MutatingUseContext::AsmOutput
233 // If this is just an assignment, determine if the assigned type needs dropping.
235 // We have to check the actual type of the assignment, as that determines if the
236 // old value is being dropped.
237 let assigned_ty = place.ty(&self.body.local_decls, self.tcx).ty;
238 if assigned_ty.needs_drop(self.tcx, self.param_env) {
239 // This would be unsafe, but should be outright impossible since we reject such unions.
240 self.tcx.sess.delay_span_bug(
241 self.source_info.span,
242 format!("union fields that need dropping should be impossible: {assigned_ty}")
247 UnsafetyViolationKind::General,
248 UnsafetyViolationDetails::AccessToUnionField,
256 impl<'tcx> UnsafetyChecker<'_, 'tcx> {
257 fn require_unsafe(&mut self, kind: UnsafetyViolationKind, details: UnsafetyViolationDetails) {
258 // Violations can turn out to be `UnsafeFn` during analysis, but they should not start out as such.
259 assert_ne!(kind, UnsafetyViolationKind::UnsafeFn);
261 let source_info = self.source_info;
262 let lint_root = self.body.source_scopes[self.source_info.scope]
265 .assert_crate_local()
267 self.register_violations(
268 [&UnsafetyViolation { source_info, lint_root, kind, details }],
273 fn register_violations<'a>(
275 violations: impl IntoIterator<Item = &'a UnsafetyViolation>,
276 new_used_unsafe_blocks: impl IntoIterator<Item = HirId>,
278 let safety = self.body.source_scopes[self.source_info.scope]
281 .assert_crate_local()
284 // `unsafe` blocks are required in safe code
285 Safety::Safe => violations.into_iter().for_each(|&violation| {
286 match violation.kind {
287 UnsafetyViolationKind::General => {}
288 UnsafetyViolationKind::UnsafeFn => {
289 bug!("`UnsafetyViolationKind::UnsafeFn` in an `Safe` context")
292 if !self.violations.contains(&violation) {
293 self.violations.push(violation)
296 // With the RFC 2585, no longer allow `unsafe` operations in `unsafe fn`s
297 Safety::FnUnsafe => violations.into_iter().for_each(|&(mut violation)| {
298 violation.kind = UnsafetyViolationKind::UnsafeFn;
299 if !self.violations.contains(&violation) {
300 self.violations.push(violation)
303 Safety::BuiltinUnsafe => {}
304 Safety::ExplicitUnsafe(hir_id) => violations.into_iter().for_each(|_violation| {
305 self.used_unsafe_blocks.insert(hir_id);
309 new_used_unsafe_blocks.into_iter().for_each(|hir_id| {
310 self.used_unsafe_blocks.insert(hir_id);
313 fn check_mut_borrowing_layout_constrained_field(
318 for (place_base, elem) in place.iter_projections().rev() {
320 // Modifications behind a dereference don't affect the value of
322 ProjectionElem::Deref => return,
323 ProjectionElem::Field(..) => {
324 let ty = place_base.ty(&self.body.local_decls, self.tcx).ty;
325 if let ty::Adt(def, _) = ty.kind() {
326 if self.tcx.layout_scalar_valid_range(def.did())
327 != (Bound::Unbounded, Bound::Unbounded)
329 let details = if is_mut_use {
330 UnsafetyViolationDetails::MutationOfLayoutConstrainedField
332 // Check `is_freeze` as late as possible to avoid cycle errors
333 // with opaque types.
335 .ty(self.body, self.tcx)
337 .is_freeze(self.tcx, self.param_env)
339 UnsafetyViolationDetails::BorrowOfLayoutConstrainedField
343 self.require_unsafe(UnsafetyViolationKind::General, details);
352 /// Checks whether calling `func_did` needs an `unsafe` context or not, i.e. whether
353 /// the called function has target features the calling function hasn't.
354 fn check_target_features(&mut self, func_did: DefId) {
355 // Unsafety isn't required on wasm targets. For more information see
356 // the corresponding check in typeck/src/collect.rs
357 if self.tcx.sess.target.options.is_like_wasm {
361 let callee_features = &self.tcx.codegen_fn_attrs(func_did).target_features;
362 // The body might be a constant, so it doesn't have codegen attributes.
363 let self_features = &self.tcx.body_codegen_attrs(self.body_did.to_def_id()).target_features;
365 // Is `callee_features` a subset of `calling_features`?
366 if !callee_features.iter().all(|feature| self_features.contains(feature)) {
368 UnsafetyViolationKind::General,
369 UnsafetyViolationDetails::CallToFunctionWith,
375 pub(crate) fn provide(providers: &mut Providers) {
376 *providers = Providers {
377 unsafety_check_result: |tcx, def_id| {
378 if let Some(def) = ty::WithOptConstParam::try_lookup(def_id, tcx) {
379 tcx.unsafety_check_result_for_const_arg(def)
381 unsafety_check_result(tcx, ty::WithOptConstParam::unknown(def_id))
384 unsafety_check_result_for_const_arg: |tcx, (did, param_did)| {
385 unsafety_check_result(
387 ty::WithOptConstParam { did, const_param_did: Some(param_did) },
394 /// Context information for [`UnusedUnsafeVisitor`] traversal,
395 /// saves (innermost) relevant context
396 #[derive(Copy, Clone, Debug)]
399 /// in an `unsafe fn`
401 /// in a *used* `unsafe` block
402 /// (i.e. a block without unused-unsafe warning)
406 struct UnusedUnsafeVisitor<'a, 'tcx> {
408 used_unsafe_blocks: &'a FxHashSet<HirId>,
410 unused_unsafes: &'a mut Vec<(HirId, UnusedUnsafe)>,
413 impl<'tcx> intravisit::Visitor<'tcx> for UnusedUnsafeVisitor<'_, 'tcx> {
414 fn visit_block(&mut self, block: &'tcx hir::Block<'tcx>) {
415 if let hir::BlockCheckMode::UnsafeBlock(hir::UnsafeSource::UserProvided) = block.rules {
416 let used = match self.tcx.lint_level_at_node(UNUSED_UNSAFE, block.hir_id) {
417 (Level::Allow, _) => true,
418 _ => self.used_unsafe_blocks.contains(&block.hir_id),
420 let unused_unsafe = match (self.context, used) {
421 (_, false) => UnusedUnsafe::Unused,
422 (Context::Safe, true) | (Context::UnsafeFn(_), true) => {
423 let previous_context = self.context;
424 self.context = Context::UnsafeBlock(block.hir_id);
425 intravisit::walk_block(self, block);
426 self.context = previous_context;
429 (Context::UnsafeBlock(hir_id), true) => UnusedUnsafe::InUnsafeBlock(hir_id),
431 self.unused_unsafes.push((block.hir_id, unused_unsafe));
433 intravisit::walk_block(self, block);
436 fn visit_anon_const(&mut self, c: &'tcx hir::AnonConst) {
437 if matches!(self.tcx.def_kind(c.def_id), DefKind::InlineConst) {
438 self.visit_body(self.tcx.hir().body(c.body))
444 fk: intravisit::FnKind<'tcx>,
445 _fd: &'tcx hir::FnDecl<'tcx>,
447 _s: rustc_span::Span,
450 if matches!(fk, intravisit::FnKind::Closure) {
451 self.visit_body(self.tcx.hir().body(b))
456 fn check_unused_unsafe(
459 used_unsafe_blocks: &FxHashSet<HirId>,
460 ) -> Vec<(HirId, UnusedUnsafe)> {
461 let body_id = tcx.hir().maybe_body_owned_by(def_id);
463 let Some(body_id) = body_id else {
464 debug!("check_unused_unsafe({:?}) - no body found", def_id);
468 let body = tcx.hir().body(body_id);
469 let hir_id = tcx.hir().local_def_id_to_hir_id(def_id);
470 let context = match tcx.hir().fn_sig_by_hir_id(hir_id) {
471 Some(sig) if sig.header.unsafety == hir::Unsafety::Unsafe => Context::UnsafeFn(hir_id),
476 "check_unused_unsafe({:?}, context={:?}, body={:?}, used_unsafe_blocks={:?})",
477 def_id, body, context, used_unsafe_blocks
480 let mut unused_unsafes = vec![];
482 let mut visitor = UnusedUnsafeVisitor {
486 unused_unsafes: &mut unused_unsafes,
488 intravisit::Visitor::visit_body(&mut visitor, body);
493 fn unsafety_check_result<'tcx>(
495 def: ty::WithOptConstParam<LocalDefId>,
496 ) -> &'tcx UnsafetyCheckResult {
497 debug!("unsafety_violations({:?})", def);
499 // N.B., this borrow is valid because all the consumers of
500 // `mir_built` force this.
501 let body = &tcx.mir_built(def).borrow();
503 if body.should_skip() {
504 return tcx.arena.alloc(UnsafetyCheckResult {
505 violations: Vec::new(),
506 used_unsafe_blocks: FxHashSet::default(),
507 unused_unsafes: Some(Vec::new()),
511 let param_env = tcx.param_env(def.did);
513 let mut checker = UnsafetyChecker::new(body, def.did, tcx, param_env);
514 checker.visit_body(&body);
516 let unused_unsafes = (!tcx.is_typeck_child(def.did.to_def_id()))
517 .then(|| check_unused_unsafe(tcx, def.did, &checker.used_unsafe_blocks));
519 tcx.arena.alloc(UnsafetyCheckResult {
520 violations: checker.violations,
521 used_unsafe_blocks: checker.used_unsafe_blocks,
526 fn report_unused_unsafe(tcx: TyCtxt<'_>, kind: UnusedUnsafe, id: HirId) {
527 let span = tcx.sess.source_map().guess_head_span(tcx.hir().span(id));
528 let msg = "unnecessary `unsafe` block";
529 tcx.struct_span_lint_hir(UNUSED_UNSAFE, id, span, msg, |lint| {
530 lint.span_label(span, msg);
532 UnusedUnsafe::Unused => {}
533 UnusedUnsafe::InUnsafeBlock(id) => {
535 tcx.sess.source_map().guess_head_span(tcx.hir().span(id)),
536 "because it's nested under this `unsafe` block",
545 pub fn check_unsafety(tcx: TyCtxt<'_>, def_id: LocalDefId) {
546 debug!("check_unsafety({:?})", def_id);
548 // closures and inline consts are handled by their parent fn.
549 if tcx.is_typeck_child(def_id.to_def_id()) {
553 let UnsafetyCheckResult { violations, unused_unsafes, .. } = tcx.unsafety_check_result(def_id);
555 for &UnsafetyViolation { source_info, lint_root, kind, details } in violations.iter() {
556 let (description, note) = details.description_and_note();
559 UnsafetyViolationKind::General => {
561 let unsafe_fn_msg = if unsafe_op_in_unsafe_fn_allowed(tcx, lint_root) {
567 let mut err = struct_span_err!(
571 "{} is unsafe and requires unsafe{} block",
575 err.span_label(source_info.span, description).note(note);
576 let note_non_inherited = tcx.hir().parent_iter(lint_root).find(|(id, node)| {
577 if let Node::Expr(block) = node
578 && let ExprKind::Block(block, _) = block.kind
579 && let BlockCheckMode::UnsafeBlock(_) = block.rules
583 else if let Some(sig) = tcx.hir().fn_sig_by_hir_id(*id)
584 && sig.header.is_unsafe()
591 if let Some((id, _)) = note_non_inherited {
592 let span = tcx.hir().span(id);
594 tcx.sess.source_map().guess_head_span(span),
595 "items do not inherit unsafety from separate enclosing items",
601 UnsafetyViolationKind::UnsafeFn => tcx.struct_span_lint_hir(
602 UNSAFE_OP_IN_UNSAFE_FN,
605 format!("{} is unsafe and requires unsafe block (error E0133)", description,),
606 |lint| lint.span_label(source_info.span, description).note(note),
611 for &(block_id, kind) in unused_unsafes.as_ref().unwrap() {
612 report_unused_unsafe(tcx, kind, block_id);
616 fn unsafe_op_in_unsafe_fn_allowed(tcx: TyCtxt<'_>, id: HirId) -> bool {
617 tcx.lint_level_at_node(UNSAFE_OP_IN_UNSAFE_FN, id).0 == Level::Allow