1 use rustc_data_structures::fx::FxHashMap;
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;
7 use rustc_middle::mir::visit::{MutatingUseContext, PlaceContext, Visitor};
8 use rustc_middle::ty::query::Providers;
9 use rustc_middle::ty::{self, TyCtxt};
10 use rustc_middle::{lint, mir::*};
11 use rustc_session::lint::builtin::{UNSAFE_OP_IN_UNSAFE_FN, UNUSED_UNSAFE};
12 use rustc_session::lint::Level;
14 use std::collections::hash_map;
17 pub struct UnsafetyChecker<'a, 'tcx> {
20 violations: Vec<UnsafetyViolation>,
21 source_info: SourceInfo,
23 param_env: ty::ParamEnv<'tcx>,
25 /// Used `unsafe` blocks in this function. This is used for the "unused_unsafe" lint.
27 /// The keys are the used `unsafe` blocks, the UnusedUnsafeKind indicates whether
28 /// or not any of the usages happen at a place that doesn't allow `unsafe_op_in_unsafe_fn`.
29 used_unsafe_blocks: FxHashMap<HirId, UsedUnsafeBlockData>,
32 impl<'a, 'tcx> UnsafetyChecker<'a, 'tcx> {
37 param_env: ty::ParamEnv<'tcx>,
43 source_info: SourceInfo::outermost(body.span),
46 used_unsafe_blocks: Default::default(),
51 impl<'tcx> Visitor<'tcx> for UnsafetyChecker<'_, 'tcx> {
52 fn visit_terminator(&mut self, terminator: &Terminator<'tcx>, location: Location) {
53 self.source_info = terminator.source_info;
54 match terminator.kind {
55 TerminatorKind::Goto { .. }
56 | TerminatorKind::SwitchInt { .. }
57 | TerminatorKind::Drop { .. }
58 | TerminatorKind::Yield { .. }
59 | TerminatorKind::Assert { .. }
60 | TerminatorKind::DropAndReplace { .. }
61 | TerminatorKind::GeneratorDrop
62 | TerminatorKind::Resume
63 | TerminatorKind::Abort
64 | TerminatorKind::Return
65 | TerminatorKind::Unreachable
66 | TerminatorKind::FalseEdge { .. }
67 | TerminatorKind::FalseUnwind { .. } => {
68 // safe (at least as emitted during MIR construction)
71 TerminatorKind::Call { ref func, .. } => {
72 let func_ty = func.ty(self.body, self.tcx);
74 if let ty::FnDef(func_id, _) = func_ty.kind() { Some(func_id) } else { None };
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 Some(func_id) = func_id {
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::Deinit(..)
103 | StatementKind::StorageLive(..)
104 | StatementKind::StorageDead(..)
105 | StatementKind::Retag { .. }
106 | StatementKind::AscribeUserType(..)
107 | StatementKind::Coverage(..)
108 | StatementKind::Nop => {
109 // safe (at least as emitted during MIR construction)
112 StatementKind::CopyNonOverlapping(..) => unreachable!(),
114 self.super_statement(statement, location);
117 fn visit_rvalue(&mut self, rvalue: &Rvalue<'tcx>, location: Location) {
119 Rvalue::Aggregate(box ref aggregate, _) => match aggregate {
120 &AggregateKind::Array(..) | &AggregateKind::Tuple => {}
121 &AggregateKind::Adt(adt_did, ..) => {
122 match self.tcx.layout_scalar_valid_range(adt_did) {
123 (Bound::Unbounded, Bound::Unbounded) => {}
124 _ => self.require_unsafe(
125 UnsafetyViolationKind::General,
126 UnsafetyViolationDetails::InitializingTypeWith,
130 &AggregateKind::Closure(def_id, _) | &AggregateKind::Generator(def_id, _, _) => {
131 let UnsafetyCheckResult { violations, used_unsafe_blocks, .. } =
132 self.tcx.unsafety_check_result(def_id.expect_local());
133 self.register_violations(
135 used_unsafe_blocks.iter().map(|(&h, &d)| (h, d)),
141 self.super_rvalue(rvalue, location);
144 fn visit_place(&mut self, place: &Place<'tcx>, context: PlaceContext, _location: Location) {
145 // On types with `scalar_valid_range`, prevent
148 // * `&x.field` if `field`'s type has interior mutability
149 // because either of these would allow modifying the layout constrained field and
150 // insert values that violate the layout constraints.
151 if context.is_mutating_use() || context.is_borrow() {
152 self.check_mut_borrowing_layout_constrained_field(*place, context.is_mutating_use());
155 // Some checks below need the extra meta info of the local declaration.
156 let decl = &self.body.local_decls[place.local];
158 // Check the base local: it might be an unsafe-to-access static. We only check derefs of the
159 // temporary holding the static pointer to avoid duplicate errors
160 // <https://github.com/rust-lang/rust/pull/78068#issuecomment-731753506>.
161 if decl.internal && place.projection.first() == Some(&ProjectionElem::Deref) {
162 // If the projection root is an artificial local that we introduced when
163 // desugaring `static`, give a more specific error message
164 // (avoid the general "raw pointer" clause below, that would only be confusing).
165 if let Some(box LocalInfo::StaticRef { def_id, .. }) = decl.local_info {
166 if self.tcx.is_mutable_static(def_id) {
168 UnsafetyViolationKind::General,
169 UnsafetyViolationDetails::UseOfMutableStatic,
172 } else if self.tcx.is_foreign_item(def_id) {
174 UnsafetyViolationKind::General,
175 UnsafetyViolationDetails::UseOfExternStatic,
182 // Check for raw pointer `Deref`.
183 for (base, proj) in place.iter_projections() {
184 if proj == ProjectionElem::Deref {
185 let base_ty = base.ty(self.body, self.tcx).ty;
186 if base_ty.is_unsafe_ptr() {
188 UnsafetyViolationKind::General,
189 UnsafetyViolationDetails::DerefOfRawPointer,
195 // Check for union fields. For this we traverse right-to-left, as the last `Deref` changes
196 // whether we *read* the union field or potentially *write* to it (if this place is being assigned to).
197 let mut saw_deref = false;
198 for (base, proj) in place.iter_projections().rev() {
199 if proj == ProjectionElem::Deref {
204 let base_ty = base.ty(self.body, self.tcx).ty;
205 if base_ty.is_union() {
206 // If we did not hit a `Deref` yet and the overall place use is an assignment, the
207 // rules are different.
208 let assign_to_field = !saw_deref
211 PlaceContext::MutatingUse(
212 MutatingUseContext::Store
213 | MutatingUseContext::Drop
214 | MutatingUseContext::AsmOutput
217 // If this is just an assignment, determine if the assigned type needs dropping.
219 // We have to check the actual type of the assignment, as that determines if the
220 // old value is being dropped.
221 let assigned_ty = place.ty(&self.body.local_decls, self.tcx).ty;
222 // To avoid semver hazard, we only consider `Copy` and `ManuallyDrop` non-dropping.
223 let manually_drop = assigned_ty
225 .map_or(false, |adt_def| adt_def.is_manually_drop());
226 let nodrop = manually_drop
227 || assigned_ty.is_copy_modulo_regions(
228 self.tcx.at(self.source_info.span),
233 UnsafetyViolationKind::General,
234 UnsafetyViolationDetails::AssignToDroppingUnionField,
237 // write to non-drop union field, safe
241 UnsafetyViolationKind::General,
242 UnsafetyViolationDetails::AccessToUnionField,
250 impl<'tcx> UnsafetyChecker<'_, 'tcx> {
251 fn require_unsafe(&mut self, kind: UnsafetyViolationKind, details: UnsafetyViolationDetails) {
252 // Violations can turn out to be `UnsafeFn` during analysis, but they should not start out as such.
253 assert_ne!(kind, UnsafetyViolationKind::UnsafeFn);
255 let source_info = self.source_info;
256 let lint_root = self.body.source_scopes[self.source_info.scope]
259 .assert_crate_local()
261 self.register_violations(
262 [&UnsafetyViolation { source_info, lint_root, kind, details }],
267 fn register_violations<'a>(
269 violations: impl IntoIterator<Item = &'a UnsafetyViolation>,
270 new_used_unsafe_blocks: impl IntoIterator<Item = (HirId, UsedUnsafeBlockData)>,
272 use UsedUnsafeBlockData::{AllAllowedInUnsafeFn, SomeDisallowedInUnsafeFn};
274 let update_entry = |this: &mut Self, hir_id, new_usage| {
275 match this.used_unsafe_blocks.entry(hir_id) {
276 hash_map::Entry::Occupied(mut entry) => {
277 if new_usage == SomeDisallowedInUnsafeFn {
278 *entry.get_mut() = SomeDisallowedInUnsafeFn;
281 hash_map::Entry::Vacant(entry) => {
282 entry.insert(new_usage);
286 let safety = self.body.source_scopes[self.source_info.scope]
289 .assert_crate_local()
292 // `unsafe` blocks are required in safe code
293 Safety::Safe => violations.into_iter().for_each(|&violation| {
294 match violation.kind {
295 UnsafetyViolationKind::General => {}
296 UnsafetyViolationKind::UnsafeFn => {
297 bug!("`UnsafetyViolationKind::UnsafeFn` in an `Safe` context")
300 if !self.violations.contains(&violation) {
301 self.violations.push(violation)
304 // With the RFC 2585, no longer allow `unsafe` operations in `unsafe fn`s
305 Safety::FnUnsafe => violations.into_iter().for_each(|&(mut violation)| {
306 violation.kind = UnsafetyViolationKind::UnsafeFn;
307 if !self.violations.contains(&violation) {
308 self.violations.push(violation)
311 Safety::BuiltinUnsafe => {}
312 Safety::ExplicitUnsafe(hir_id) => violations.into_iter().for_each(|violation| {
316 match self.tcx.lint_level_at_node(UNSAFE_OP_IN_UNSAFE_FN, violation.lint_root).0
318 Level::Allow => AllAllowedInUnsafeFn(violation.lint_root),
319 _ => SomeDisallowedInUnsafeFn,
325 new_used_unsafe_blocks
327 .for_each(|(hir_id, usage_data)| update_entry(self, hir_id, usage_data));
329 fn check_mut_borrowing_layout_constrained_field(
334 for (place_base, elem) in place.iter_projections().rev() {
336 // Modifications behind a dereference don't affect the value of
338 ProjectionElem::Deref => return,
339 ProjectionElem::Field(..) => {
340 let ty = place_base.ty(&self.body.local_decls, self.tcx).ty;
341 if let ty::Adt(def, _) = ty.kind() {
342 if self.tcx.layout_scalar_valid_range(def.did())
343 != (Bound::Unbounded, Bound::Unbounded)
345 let details = if is_mut_use {
346 UnsafetyViolationDetails::MutationOfLayoutConstrainedField
348 // Check `is_freeze` as late as possible to avoid cycle errors
349 // with opaque types.
351 .ty(self.body, self.tcx)
353 .is_freeze(self.tcx.at(self.source_info.span), self.param_env)
355 UnsafetyViolationDetails::BorrowOfLayoutConstrainedField
359 self.require_unsafe(UnsafetyViolationKind::General, details);
368 /// Checks whether calling `func_did` needs an `unsafe` context or not, i.e. whether
369 /// the called function has target features the calling function hasn't.
370 fn check_target_features(&mut self, func_did: DefId) {
371 // Unsafety isn't required on wasm targets. For more information see
372 // the corresponding check in typeck/src/collect.rs
373 if self.tcx.sess.target.options.is_like_wasm {
377 let callee_features = &self.tcx.codegen_fn_attrs(func_did).target_features;
378 // The body might be a constant, so it doesn't have codegen attributes.
379 let self_features = &self.tcx.body_codegen_attrs(self.body_did.to_def_id()).target_features;
381 // Is `callee_features` a subset of `calling_features`?
382 if !callee_features.iter().all(|feature| self_features.contains(feature)) {
384 UnsafetyViolationKind::General,
385 UnsafetyViolationDetails::CallToFunctionWith,
391 pub(crate) fn provide(providers: &mut Providers) {
392 *providers = Providers {
393 unsafety_check_result: |tcx, def_id| {
394 if let Some(def) = ty::WithOptConstParam::try_lookup(def_id, tcx) {
395 tcx.unsafety_check_result_for_const_arg(def)
397 unsafety_check_result(tcx, ty::WithOptConstParam::unknown(def_id))
400 unsafety_check_result_for_const_arg: |tcx, (did, param_did)| {
401 unsafety_check_result(
403 ty::WithOptConstParam { did, const_param_did: Some(param_did) },
410 /// Context information for [`UnusedUnsafeVisitor`] traversal,
411 /// saves (innermost) relevant context
412 #[derive(Copy, Clone, Debug)]
415 /// in an `unsafe fn`
417 /// in a *used* `unsafe` block
418 /// (i.e. a block without unused-unsafe warning)
422 struct UnusedUnsafeVisitor<'a, 'tcx> {
424 used_unsafe_blocks: &'a FxHashMap<HirId, UsedUnsafeBlockData>,
426 unused_unsafes: &'a mut Vec<(HirId, UnusedUnsafe)>,
429 impl<'tcx> intravisit::Visitor<'tcx> for UnusedUnsafeVisitor<'_, 'tcx> {
430 fn visit_block(&mut self, block: &'tcx hir::Block<'tcx>) {
431 use UsedUnsafeBlockData::{AllAllowedInUnsafeFn, SomeDisallowedInUnsafeFn};
433 if let hir::BlockCheckMode::UnsafeBlock(hir::UnsafeSource::UserProvided) = block.rules {
434 let used = match self.tcx.lint_level_at_node(UNUSED_UNSAFE, block.hir_id) {
435 (Level::Allow, _) => Some(SomeDisallowedInUnsafeFn),
436 _ => self.used_unsafe_blocks.get(&block.hir_id).copied(),
438 let unused_unsafe = match (self.context, used) {
439 (_, None) => UnusedUnsafe::Unused,
440 (Context::Safe, Some(_))
441 | (Context::UnsafeFn(_), Some(SomeDisallowedInUnsafeFn)) => {
442 let previous_context = self.context;
443 self.context = Context::UnsafeBlock(block.hir_id);
444 intravisit::walk_block(self, block);
445 self.context = previous_context;
448 (Context::UnsafeFn(hir_id), Some(AllAllowedInUnsafeFn(lint_root))) => {
449 UnusedUnsafe::InUnsafeFn(hir_id, lint_root)
451 (Context::UnsafeBlock(hir_id), Some(_)) => UnusedUnsafe::InUnsafeBlock(hir_id),
453 self.unused_unsafes.push((block.hir_id, unused_unsafe));
455 intravisit::walk_block(self, block);
460 fk: intravisit::FnKind<'tcx>,
461 _fd: &'tcx hir::FnDecl<'tcx>,
463 _s: rustc_span::Span,
466 if matches!(fk, intravisit::FnKind::Closure) {
467 self.visit_body(self.tcx.hir().body(b))
472 fn check_unused_unsafe(
475 used_unsafe_blocks: &FxHashMap<HirId, UsedUnsafeBlockData>,
476 ) -> Vec<(HirId, UnusedUnsafe)> {
477 let hir_id = tcx.hir().local_def_id_to_hir_id(def_id);
478 let body_id = tcx.hir().maybe_body_owned_by(hir_id);
480 let Some(body_id) = body_id else {
481 debug!("check_unused_unsafe({:?}) - no body found", def_id);
484 let body = tcx.hir().body(body_id);
486 let context = match tcx.hir().fn_sig_by_hir_id(hir_id) {
487 Some(sig) if sig.header.unsafety == hir::Unsafety::Unsafe => Context::UnsafeFn(hir_id),
492 "check_unused_unsafe({:?}, context={:?}, body={:?}, used_unsafe_blocks={:?})",
493 def_id, body, context, used_unsafe_blocks
496 let mut unused_unsafes = vec![];
498 let mut visitor = UnusedUnsafeVisitor {
502 unused_unsafes: &mut unused_unsafes,
504 intravisit::Visitor::visit_body(&mut visitor, body);
509 fn unsafety_check_result<'tcx>(
511 def: ty::WithOptConstParam<LocalDefId>,
512 ) -> &'tcx UnsafetyCheckResult {
513 debug!("unsafety_violations({:?})", def);
515 // N.B., this borrow is valid because all the consumers of
516 // `mir_built` force this.
517 let body = &tcx.mir_built(def).borrow();
519 let param_env = tcx.param_env(def.did);
521 let mut checker = UnsafetyChecker::new(body, def.did, tcx, param_env);
522 checker.visit_body(&body);
524 let unused_unsafes = (!tcx.is_closure(def.did.to_def_id()))
525 .then(|| check_unused_unsafe(tcx, def.did, &checker.used_unsafe_blocks));
527 tcx.arena.alloc(UnsafetyCheckResult {
528 violations: checker.violations,
529 used_unsafe_blocks: checker.used_unsafe_blocks,
534 fn report_unused_unsafe(tcx: TyCtxt<'_>, kind: UnusedUnsafe, id: HirId) {
535 let span = tcx.sess.source_map().guess_head_span(tcx.hir().span(id));
536 tcx.struct_span_lint_hir(UNUSED_UNSAFE, id, span, |lint| {
537 let msg = "unnecessary `unsafe` block";
538 let mut db = lint.build(msg);
539 db.span_label(span, msg);
541 UnusedUnsafe::Unused => {}
542 UnusedUnsafe::InUnsafeBlock(id) => {
544 tcx.sess.source_map().guess_head_span(tcx.hir().span(id)),
545 "because it's nested under this `unsafe` block",
548 UnusedUnsafe::InUnsafeFn(id, usage_lint_root) => {
550 tcx.sess.source_map().guess_head_span(tcx.hir().span(id)),
551 "because it's nested under this `unsafe` fn",
554 "this `unsafe` block does contain unsafe operations, \
555 but those are already allowed in an `unsafe fn`",
557 let (level, source) =
558 tcx.lint_level_at_node(UNSAFE_OP_IN_UNSAFE_FN, usage_lint_root);
559 assert_eq!(level, Level::Allow);
560 lint::explain_lint_level_source(
561 UNSAFE_OP_IN_UNSAFE_FN,
573 pub fn check_unsafety(tcx: TyCtxt<'_>, def_id: LocalDefId) {
574 debug!("check_unsafety({:?})", def_id);
576 // closures are handled by their parent fn.
577 if tcx.is_closure(def_id.to_def_id()) {
581 let UnsafetyCheckResult { violations, unused_unsafes, .. } = tcx.unsafety_check_result(def_id);
583 for &UnsafetyViolation { source_info, lint_root, kind, details } in violations.iter() {
584 let (description, note) = details.description_and_note();
588 if unsafe_op_in_unsafe_fn_allowed(tcx, lint_root) { " function or" } else { "" };
591 UnsafetyViolationKind::General => {
597 "{} is unsafe and requires unsafe{} block",
601 .span_label(source_info.span, description)
605 UnsafetyViolationKind::UnsafeFn => tcx.struct_span_lint_hir(
606 UNSAFE_OP_IN_UNSAFE_FN,
611 "{} is unsafe and requires unsafe block (error E0133)",
614 .span_label(source_info.span, description)
622 for &(block_id, kind) in unused_unsafes.as_ref().unwrap() {
623 report_unused_unsafe(tcx, kind, block_id);
627 fn unsafe_op_in_unsafe_fn_allowed(tcx: TyCtxt<'_>, id: HirId) -> bool {
628 tcx.lint_level_at_node(UNSAFE_OP_IN_UNSAFE_FN, id).0 == Level::Allow