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::ConstEvalCounter
108 | StatementKind::Nop => {
109 // safe (at least as emitted during MIR construction)
112 self.super_statement(statement, location);
115 fn visit_rvalue(&mut self, rvalue: &Rvalue<'tcx>, location: Location) {
117 Rvalue::Aggregate(box ref aggregate, _) => match aggregate {
118 &AggregateKind::Array(..) | &AggregateKind::Tuple => {}
119 &AggregateKind::Adt(adt_did, ..) => {
120 match self.tcx.layout_scalar_valid_range(adt_did) {
121 (Bound::Unbounded, Bound::Unbounded) => {}
122 _ => self.require_unsafe(
123 UnsafetyViolationKind::General,
124 UnsafetyViolationDetails::InitializingTypeWith,
128 &AggregateKind::Closure(def_id, _) | &AggregateKind::Generator(def_id, _, _) => {
129 let UnsafetyCheckResult { violations, used_unsafe_blocks, .. } =
130 self.tcx.unsafety_check_result(def_id);
131 self.register_violations(violations, used_unsafe_blocks.iter().copied());
136 self.super_rvalue(rvalue, location);
139 fn visit_operand(&mut self, op: &Operand<'tcx>, location: Location) {
140 if let Operand::Constant(constant) = op {
141 let maybe_uneval = match constant.literal {
142 ConstantKind::Val(..) | ConstantKind::Ty(_) => None,
143 ConstantKind::Unevaluated(uv, _) => Some(uv),
146 if let Some(uv) = maybe_uneval {
147 if uv.promoted.is_none() {
148 let def_id = uv.def.def_id_for_type_of();
149 if self.tcx.def_kind(def_id) == DefKind::InlineConst {
150 let local_def_id = def_id.expect_local();
151 let UnsafetyCheckResult { violations, used_unsafe_blocks, .. } =
152 self.tcx.unsafety_check_result(local_def_id);
153 self.register_violations(violations, used_unsafe_blocks.iter().copied());
158 self.super_operand(op, location);
161 fn visit_place(&mut self, place: &Place<'tcx>, context: PlaceContext, _location: Location) {
162 // On types with `scalar_valid_range`, prevent
165 // * `&x.field` if `field`'s type has interior mutability
166 // because either of these would allow modifying the layout constrained field and
167 // insert values that violate the layout constraints.
168 if context.is_mutating_use() || context.is_borrow() {
169 self.check_mut_borrowing_layout_constrained_field(*place, context.is_mutating_use());
172 // Some checks below need the extra meta info of the local declaration.
173 let decl = &self.body.local_decls[place.local];
175 // Check the base local: it might be an unsafe-to-access static. We only check derefs of the
176 // temporary holding the static pointer to avoid duplicate errors
177 // <https://github.com/rust-lang/rust/pull/78068#issuecomment-731753506>.
178 if decl.internal && place.projection.first() == Some(&ProjectionElem::Deref) {
179 // If the projection root is an artificial local that we introduced when
180 // desugaring `static`, give a more specific error message
181 // (avoid the general "raw pointer" clause below, that would only be confusing).
182 if let Some(box LocalInfo::StaticRef { def_id, .. }) = decl.local_info {
183 if self.tcx.is_mutable_static(def_id) {
185 UnsafetyViolationKind::General,
186 UnsafetyViolationDetails::UseOfMutableStatic,
189 } else if self.tcx.is_foreign_item(def_id) {
191 UnsafetyViolationKind::General,
192 UnsafetyViolationDetails::UseOfExternStatic,
199 // Check for raw pointer `Deref`.
200 for (base, proj) in place.iter_projections() {
201 if proj == ProjectionElem::Deref {
202 let base_ty = base.ty(self.body, self.tcx).ty;
203 if base_ty.is_unsafe_ptr() {
205 UnsafetyViolationKind::General,
206 UnsafetyViolationDetails::DerefOfRawPointer,
212 // Check for union fields. For this we traverse right-to-left, as the last `Deref` changes
213 // whether we *read* the union field or potentially *write* to it (if this place is being assigned to).
214 let mut saw_deref = false;
215 for (base, proj) in place.iter_projections().rev() {
216 if proj == ProjectionElem::Deref {
221 let base_ty = base.ty(self.body, self.tcx).ty;
222 if base_ty.is_union() {
223 // If we did not hit a `Deref` yet and the overall place use is an assignment, the
224 // rules are different.
225 let assign_to_field = !saw_deref
228 PlaceContext::MutatingUse(
229 MutatingUseContext::Store
230 | MutatingUseContext::Drop
231 | MutatingUseContext::AsmOutput
234 // If this is just an assignment, determine if the assigned type needs dropping.
236 // We have to check the actual type of the assignment, as that determines if the
237 // old value is being dropped.
238 let assigned_ty = place.ty(&self.body.local_decls, self.tcx).ty;
239 if assigned_ty.needs_drop(self.tcx, self.param_env) {
240 // This would be unsafe, but should be outright impossible since we reject such unions.
241 self.tcx.sess.delay_span_bug(
242 self.source_info.span,
243 format!("union fields that need dropping should be impossible: {assigned_ty}")
248 UnsafetyViolationKind::General,
249 UnsafetyViolationDetails::AccessToUnionField,
257 impl<'tcx> UnsafetyChecker<'_, 'tcx> {
258 fn require_unsafe(&mut self, kind: UnsafetyViolationKind, details: UnsafetyViolationDetails) {
259 // Violations can turn out to be `UnsafeFn` during analysis, but they should not start out as such.
260 assert_ne!(kind, UnsafetyViolationKind::UnsafeFn);
262 let source_info = self.source_info;
263 let lint_root = self.body.source_scopes[self.source_info.scope]
266 .assert_crate_local()
268 self.register_violations(
269 [&UnsafetyViolation { source_info, lint_root, kind, details }],
274 fn register_violations<'a>(
276 violations: impl IntoIterator<Item = &'a UnsafetyViolation>,
277 new_used_unsafe_blocks: impl IntoIterator<Item = HirId>,
279 let safety = self.body.source_scopes[self.source_info.scope]
282 .assert_crate_local()
285 // `unsafe` blocks are required in safe code
286 Safety::Safe => violations.into_iter().for_each(|&violation| {
287 match violation.kind {
288 UnsafetyViolationKind::General => {}
289 UnsafetyViolationKind::UnsafeFn => {
290 bug!("`UnsafetyViolationKind::UnsafeFn` in an `Safe` context")
293 if !self.violations.contains(&violation) {
294 self.violations.push(violation)
297 // With the RFC 2585, no longer allow `unsafe` operations in `unsafe fn`s
298 Safety::FnUnsafe => violations.into_iter().for_each(|&(mut violation)| {
299 violation.kind = UnsafetyViolationKind::UnsafeFn;
300 if !self.violations.contains(&violation) {
301 self.violations.push(violation)
304 Safety::BuiltinUnsafe => {}
305 Safety::ExplicitUnsafe(hir_id) => violations.into_iter().for_each(|_violation| {
306 self.used_unsafe_blocks.insert(hir_id);
310 new_used_unsafe_blocks.into_iter().for_each(|hir_id| {
311 self.used_unsafe_blocks.insert(hir_id);
314 fn check_mut_borrowing_layout_constrained_field(
319 for (place_base, elem) in place.iter_projections().rev() {
321 // Modifications behind a dereference don't affect the value of
323 ProjectionElem::Deref => return,
324 ProjectionElem::Field(..) => {
325 let ty = place_base.ty(&self.body.local_decls, self.tcx).ty;
326 if let ty::Adt(def, _) = ty.kind() {
327 if self.tcx.layout_scalar_valid_range(def.did())
328 != (Bound::Unbounded, Bound::Unbounded)
330 let details = if is_mut_use {
331 UnsafetyViolationDetails::MutationOfLayoutConstrainedField
333 // Check `is_freeze` as late as possible to avoid cycle errors
334 // with opaque types.
336 .ty(self.body, self.tcx)
338 .is_freeze(self.tcx, self.param_env)
340 UnsafetyViolationDetails::BorrowOfLayoutConstrainedField
344 self.require_unsafe(UnsafetyViolationKind::General, details);
353 /// Checks whether calling `func_did` needs an `unsafe` context or not, i.e. whether
354 /// the called function has target features the calling function hasn't.
355 fn check_target_features(&mut self, func_did: DefId) {
356 // Unsafety isn't required on wasm targets. For more information see
357 // the corresponding check in typeck/src/collect.rs
358 if self.tcx.sess.target.options.is_like_wasm {
362 let callee_features = &self.tcx.codegen_fn_attrs(func_did).target_features;
363 // The body might be a constant, so it doesn't have codegen attributes.
364 let self_features = &self.tcx.body_codegen_attrs(self.body_did.to_def_id()).target_features;
366 // Is `callee_features` a subset of `calling_features`?
367 if !callee_features.iter().all(|feature| self_features.contains(feature)) {
369 UnsafetyViolationKind::General,
370 UnsafetyViolationDetails::CallToFunctionWith,
376 pub(crate) fn provide(providers: &mut Providers) {
377 *providers = Providers {
378 unsafety_check_result: |tcx, def_id| {
379 if let Some(def) = ty::WithOptConstParam::try_lookup(def_id, tcx) {
380 tcx.unsafety_check_result_for_const_arg(def)
382 unsafety_check_result(tcx, ty::WithOptConstParam::unknown(def_id))
385 unsafety_check_result_for_const_arg: |tcx, (did, param_did)| {
386 unsafety_check_result(
388 ty::WithOptConstParam { did, const_param_did: Some(param_did) },
395 /// Context information for [`UnusedUnsafeVisitor`] traversal,
396 /// saves (innermost) relevant context
397 #[derive(Copy, Clone, Debug)]
400 /// in an `unsafe fn`
402 /// in a *used* `unsafe` block
403 /// (i.e. a block without unused-unsafe warning)
407 struct UnusedUnsafeVisitor<'a, 'tcx> {
409 used_unsafe_blocks: &'a FxHashSet<HirId>,
411 unused_unsafes: &'a mut Vec<(HirId, UnusedUnsafe)>,
414 impl<'tcx> intravisit::Visitor<'tcx> for UnusedUnsafeVisitor<'_, 'tcx> {
415 fn visit_block(&mut self, block: &'tcx hir::Block<'tcx>) {
416 if let hir::BlockCheckMode::UnsafeBlock(hir::UnsafeSource::UserProvided) = block.rules {
417 let used = match self.tcx.lint_level_at_node(UNUSED_UNSAFE, block.hir_id) {
418 (Level::Allow, _) => true,
419 _ => self.used_unsafe_blocks.contains(&block.hir_id),
421 let unused_unsafe = match (self.context, used) {
422 (_, false) => UnusedUnsafe::Unused,
423 (Context::Safe, true) | (Context::UnsafeFn(_), true) => {
424 let previous_context = self.context;
425 self.context = Context::UnsafeBlock(block.hir_id);
426 intravisit::walk_block(self, block);
427 self.context = previous_context;
430 (Context::UnsafeBlock(hir_id), true) => UnusedUnsafe::InUnsafeBlock(hir_id),
432 self.unused_unsafes.push((block.hir_id, unused_unsafe));
434 intravisit::walk_block(self, block);
437 fn visit_anon_const(&mut self, c: &'tcx hir::AnonConst) {
438 if matches!(self.tcx.def_kind(c.def_id), DefKind::InlineConst) {
439 self.visit_body(self.tcx.hir().body(c.body))
445 fk: intravisit::FnKind<'tcx>,
446 _fd: &'tcx hir::FnDecl<'tcx>,
448 _s: rustc_span::Span,
451 if matches!(fk, intravisit::FnKind::Closure) {
452 self.visit_body(self.tcx.hir().body(b))
457 fn check_unused_unsafe(
460 used_unsafe_blocks: &FxHashSet<HirId>,
461 ) -> Vec<(HirId, UnusedUnsafe)> {
462 let body_id = tcx.hir().maybe_body_owned_by(def_id);
464 let Some(body_id) = body_id else {
465 debug!("check_unused_unsafe({:?}) - no body found", def_id);
469 let body = tcx.hir().body(body_id);
470 let hir_id = tcx.hir().local_def_id_to_hir_id(def_id);
471 let context = match tcx.hir().fn_sig_by_hir_id(hir_id) {
472 Some(sig) if sig.header.unsafety == hir::Unsafety::Unsafe => Context::UnsafeFn(hir_id),
477 "check_unused_unsafe({:?}, context={:?}, body={:?}, used_unsafe_blocks={:?})",
478 def_id, body, context, used_unsafe_blocks
481 let mut unused_unsafes = vec![];
483 let mut visitor = UnusedUnsafeVisitor {
487 unused_unsafes: &mut unused_unsafes,
489 intravisit::Visitor::visit_body(&mut visitor, body);
494 fn unsafety_check_result(
496 def: ty::WithOptConstParam<LocalDefId>,
497 ) -> &UnsafetyCheckResult {
498 debug!("unsafety_violations({:?})", def);
500 // N.B., this borrow is valid because all the consumers of
501 // `mir_built` force this.
502 let body = &tcx.mir_built(def).borrow();
504 if body.is_custom_mir() {
505 return tcx.arena.alloc(UnsafetyCheckResult {
506 violations: Vec::new(),
507 used_unsafe_blocks: FxHashSet::default(),
508 unused_unsafes: Some(Vec::new()),
512 let param_env = tcx.param_env(def.did);
514 let mut checker = UnsafetyChecker::new(body, def.did, tcx, param_env);
515 checker.visit_body(&body);
517 let unused_unsafes = (!tcx.is_typeck_child(def.did.to_def_id()))
518 .then(|| check_unused_unsafe(tcx, def.did, &checker.used_unsafe_blocks));
520 tcx.arena.alloc(UnsafetyCheckResult {
521 violations: checker.violations,
522 used_unsafe_blocks: checker.used_unsafe_blocks,
527 fn report_unused_unsafe(tcx: TyCtxt<'_>, kind: UnusedUnsafe, id: HirId) {
528 let span = tcx.sess.source_map().guess_head_span(tcx.hir().span(id));
529 let msg = "unnecessary `unsafe` block";
530 tcx.struct_span_lint_hir(UNUSED_UNSAFE, id, span, msg, |lint| {
531 lint.span_label(span, msg);
533 UnusedUnsafe::Unused => {}
534 UnusedUnsafe::InUnsafeBlock(id) => {
536 tcx.sess.source_map().guess_head_span(tcx.hir().span(id)),
537 "because it's nested under this `unsafe` block",
546 pub fn check_unsafety(tcx: TyCtxt<'_>, def_id: LocalDefId) {
547 debug!("check_unsafety({:?})", def_id);
549 // closures and inline consts are handled by their parent fn.
550 if tcx.is_typeck_child(def_id.to_def_id()) {
554 let UnsafetyCheckResult { violations, unused_unsafes, .. } = tcx.unsafety_check_result(def_id);
556 for &UnsafetyViolation { source_info, lint_root, kind, details } in violations.iter() {
557 let (description, note) = details.description_and_note();
560 UnsafetyViolationKind::General => {
562 let unsafe_fn_msg = if unsafe_op_in_unsafe_fn_allowed(tcx, lint_root) {
568 let mut err = struct_span_err!(
572 "{} is unsafe and requires unsafe{} block",
576 err.span_label(source_info.span, description).note(note);
577 let note_non_inherited = tcx.hir().parent_iter(lint_root).find(|(id, node)| {
578 if let Node::Expr(block) = node
579 && let ExprKind::Block(block, _) = block.kind
580 && let BlockCheckMode::UnsafeBlock(_) = block.rules
584 else if let Some(sig) = tcx.hir().fn_sig_by_hir_id(*id)
585 && sig.header.is_unsafe()
592 if let Some((id, _)) = note_non_inherited {
593 let span = tcx.hir().span(id);
595 tcx.sess.source_map().guess_head_span(span),
596 "items do not inherit unsafety from separate enclosing items",
602 UnsafetyViolationKind::UnsafeFn => tcx.struct_span_lint_hir(
603 UNSAFE_OP_IN_UNSAFE_FN,
606 format!("{} is unsafe and requires unsafe block (error E0133)", description,),
607 |lint| lint.span_label(source_info.span, description).note(note),
612 for &(block_id, kind) in unused_unsafes.as_ref().unwrap() {
613 report_unused_unsafe(tcx, kind, block_id);
617 fn unsafe_op_in_unsafe_fn_allowed(tcx: TyCtxt<'_>, id: HirId) -> bool {
618 tcx.lint_level_at_node(UNSAFE_OP_IN_UNSAFE_FN, id).0 == Level::Allow