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::LlvmInlineAsm { .. } => self.require_unsafe(
108 UnsafetyViolationKind::General,
109 UnsafetyViolationDetails::UseOfInlineAssembly,
111 StatementKind::CopyNonOverlapping(..) => unreachable!(),
113 self.super_statement(statement, location);
116 fn visit_rvalue(&mut self, rvalue: &Rvalue<'tcx>, location: Location) {
118 Rvalue::Aggregate(box ref aggregate, _) => match aggregate {
119 &AggregateKind::Array(..) | &AggregateKind::Tuple => {}
120 &AggregateKind::Adt(ref def, ..) => {
121 match self.tcx.layout_scalar_valid_range(def.did) {
122 (Bound::Unbounded, Bound::Unbounded) => {}
123 _ => self.require_unsafe(
124 UnsafetyViolationKind::General,
125 UnsafetyViolationDetails::InitializingTypeWith,
129 &AggregateKind::Closure(def_id, _) | &AggregateKind::Generator(def_id, _, _) => {
130 let UnsafetyCheckResult { violations, unsafe_blocks } =
131 self.tcx.unsafety_check_result(def_id.expect_local());
132 self.register_violations(&violations, &unsafe_blocks);
137 self.super_rvalue(rvalue, location);
140 fn visit_place(&mut self, place: &Place<'tcx>, context: PlaceContext, _location: Location) {
141 // On types with `scalar_valid_range`, prevent
144 // * `&x.field` if `field`'s type has interior mutability
145 // because either of these would allow modifying the layout constrained field and
146 // insert values that violate the layout constraints.
147 if context.is_mutating_use() || context.is_borrow() {
148 self.check_mut_borrowing_layout_constrained_field(*place, context.is_mutating_use());
151 // Some checks below need the extra metainfo of the local declaration.
152 let decl = &self.body.local_decls[place.local];
154 // Check the base local: it might be an unsafe-to-access static. We only check derefs of the
155 // temporary holding the static pointer to avoid duplicate errors
156 // <https://github.com/rust-lang/rust/pull/78068#issuecomment-731753506>.
157 if decl.internal && place.projection.first() == Some(&ProjectionElem::Deref) {
158 // If the projection root is an artifical local that we introduced when
159 // desugaring `static`, give a more specific error message
160 // (avoid the general "raw pointer" clause below, that would only be confusing).
161 if let Some(box LocalInfo::StaticRef { def_id, .. }) = decl.local_info {
162 if self.tcx.is_mutable_static(def_id) {
164 UnsafetyViolationKind::General,
165 UnsafetyViolationDetails::UseOfMutableStatic,
168 } else if self.tcx.is_foreign_item(def_id) {
170 UnsafetyViolationKind::General,
171 UnsafetyViolationDetails::UseOfExternStatic,
178 // Check for raw pointer `Deref`.
179 for (base, proj) in place.iter_projections() {
180 if proj == ProjectionElem::Deref {
181 let base_ty = base.ty(self.body, self.tcx).ty;
182 if base_ty.is_unsafe_ptr() {
184 UnsafetyViolationKind::General,
185 UnsafetyViolationDetails::DerefOfRawPointer,
191 // Check for union fields. For this we traverse right-to-left, as the last `Deref` changes
192 // whether we *read* the union field or potentially *write* to it (if this place is being assigned to).
193 let mut saw_deref = false;
194 for (base, proj) in place.iter_projections().rev() {
195 if proj == ProjectionElem::Deref {
200 let base_ty = base.ty(self.body, self.tcx).ty;
201 if base_ty.is_union() {
202 // If we did not hit a `Deref` yet and the overall place use is an assignment, the
203 // rules are different.
204 let assign_to_field = !saw_deref
207 PlaceContext::MutatingUse(
208 MutatingUseContext::Store
209 | MutatingUseContext::Drop
210 | MutatingUseContext::AsmOutput
211 | MutatingUseContext::LlvmAsmOutput
214 // If this is just an assignment, determine if the assigned type needs dropping.
216 // We have to check the actual type of the assignment, as that determines if the
217 // old value is being dropped.
218 let assigned_ty = place.ty(&self.body.local_decls, self.tcx).ty;
219 // To avoid semver hazard, we only consider `Copy` and `ManuallyDrop` non-dropping.
220 let manually_drop = assigned_ty
222 .map_or(false, |adt_def| adt_def.is_manually_drop());
223 let nodrop = manually_drop
224 || assigned_ty.is_copy_modulo_regions(
225 self.tcx.at(self.source_info.span),
230 UnsafetyViolationKind::General,
231 UnsafetyViolationDetails::AssignToDroppingUnionField,
234 // write to non-drop union field, safe
238 UnsafetyViolationKind::General,
239 UnsafetyViolationDetails::AccessToUnionField,
247 impl<'tcx> UnsafetyChecker<'_, 'tcx> {
248 fn require_unsafe(&mut self, kind: UnsafetyViolationKind, details: UnsafetyViolationDetails) {
249 // Violations can turn out to be `UnsafeFn` during analysis, but they should not start out as such.
250 assert_ne!(kind, UnsafetyViolationKind::UnsafeFn);
252 let source_info = self.source_info;
253 let lint_root = self.body.source_scopes[self.source_info.scope]
256 .assert_crate_local()
258 self.register_violations(
259 &[UnsafetyViolation { source_info, lint_root, kind, details }],
264 fn register_violations(
266 violations: &[UnsafetyViolation],
267 unsafe_blocks: &[(hir::HirId, bool)],
269 let safety = self.body.source_scopes[self.source_info.scope]
272 .assert_crate_local()
274 let within_unsafe = match safety {
275 // `unsafe` blocks are required in safe code
277 for violation in violations {
278 match violation.kind {
279 UnsafetyViolationKind::General => {}
280 UnsafetyViolationKind::UnsafeFn => {
281 bug!("`UnsafetyViolationKind::UnsafeFn` in an `Safe` context")
284 if !self.violations.contains(violation) {
285 self.violations.push(*violation)
290 // With the RFC 2585, no longer allow `unsafe` operations in `unsafe fn`s
291 Safety::FnUnsafe => {
292 for violation in violations {
293 let mut violation = *violation;
295 violation.kind = UnsafetyViolationKind::UnsafeFn;
296 if !self.violations.contains(&violation) {
297 self.violations.push(violation)
302 Safety::BuiltinUnsafe => true,
303 Safety::ExplicitUnsafe(hir_id) => {
304 // mark unsafe block as used if there are any unsafe operations inside
305 if !violations.is_empty() {
306 self.used_unsafe.insert(hir_id);
311 self.inherited_blocks.extend(
312 unsafe_blocks.iter().map(|&(hir_id, is_used)| (hir_id, is_used && !within_unsafe)),
315 fn check_mut_borrowing_layout_constrained_field(
320 for (place_base, elem) in place.iter_projections().rev() {
322 // Modifications behind a dereference don't affect the value of
324 ProjectionElem::Deref => return,
325 ProjectionElem::Field(..) => {
326 let ty = place_base.ty(&self.body.local_decls, self.tcx).ty;
327 if let ty::Adt(def, _) = ty.kind() {
328 if self.tcx.layout_scalar_valid_range(def.did)
329 != (Bound::Unbounded, Bound::Unbounded)
331 let details = if is_mut_use {
332 UnsafetyViolationDetails::MutationOfLayoutConstrainedField
334 // Check `is_freeze` as late as possible to avoid cycle errors
335 // with opaque types.
337 .ty(self.body, self.tcx)
339 .is_freeze(self.tcx.at(self.source_info.span), self.param_env)
341 UnsafetyViolationDetails::BorrowOfLayoutConstrainedField
345 self.require_unsafe(UnsafetyViolationKind::General, details);
354 /// Checks whether calling `func_did` needs an `unsafe` context or not, i.e. whether
355 /// the called function has target features the calling function hasn't.
356 fn check_target_features(&mut self, func_did: DefId) {
357 // Unsafety isn't required on wasm targets. For more information see
358 // the corresponding check in typeck/src/collect.rs
359 if self.tcx.sess.target.options.is_like_wasm {
363 let callee_features = &self.tcx.codegen_fn_attrs(func_did).target_features;
364 let self_features = &self.tcx.codegen_fn_attrs(self.body_did).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 struct UnusedUnsafeVisitor<'a> {
396 used_unsafe: &'a FxHashSet<hir::HirId>,
397 unsafe_blocks: &'a mut Vec<(hir::HirId, bool)>,
400 impl<'tcx> intravisit::Visitor<'tcx> for UnusedUnsafeVisitor<'_> {
401 type Map = intravisit::ErasedMap<'tcx>;
403 fn nested_visit_map(&mut self) -> intravisit::NestedVisitorMap<Self::Map> {
404 intravisit::NestedVisitorMap::None
407 fn visit_block(&mut self, block: &'tcx hir::Block<'tcx>) {
408 intravisit::walk_block(self, block);
410 if let hir::BlockCheckMode::UnsafeBlock(hir::UnsafeSource::UserProvided) = block.rules {
411 self.unsafe_blocks.push((block.hir_id, self.used_unsafe.contains(&block.hir_id)));
416 fn check_unused_unsafe(
419 used_unsafe: &FxHashSet<hir::HirId>,
420 unsafe_blocks: &mut Vec<(hir::HirId, bool)>,
422 let body_id = tcx.hir().maybe_body_owned_by(tcx.hir().local_def_id_to_hir_id(def_id));
424 let body_id = match body_id {
427 debug!("check_unused_unsafe({:?}) - no body found", def_id);
431 let body = tcx.hir().body(body_id);
432 debug!("check_unused_unsafe({:?}, body={:?}, used_unsafe={:?})", def_id, body, used_unsafe);
434 let mut visitor = UnusedUnsafeVisitor { used_unsafe, unsafe_blocks };
435 intravisit::Visitor::visit_body(&mut visitor, body);
438 fn unsafety_check_result<'tcx>(
440 def: ty::WithOptConstParam<LocalDefId>,
441 ) -> &'tcx UnsafetyCheckResult {
442 debug!("unsafety_violations({:?})", def);
444 // N.B., this borrow is valid because all the consumers of
445 // `mir_built` force this.
446 let body = &tcx.mir_built(def).borrow();
448 let param_env = tcx.param_env(def.did);
450 let mut checker = UnsafetyChecker::new(body, def.did, tcx, param_env);
451 checker.visit_body(&body);
453 check_unused_unsafe(tcx, def.did, &checker.used_unsafe, &mut checker.inherited_blocks);
455 tcx.arena.alloc(UnsafetyCheckResult {
456 violations: checker.violations.into(),
457 unsafe_blocks: checker.inherited_blocks.into(),
461 /// Returns the `HirId` for an enclosing scope that is also `unsafe`.
464 used_unsafe: &FxHashSet<hir::HirId>,
466 unsafe_op_in_unsafe_fn_allowed: bool,
467 ) -> Option<(&'static str, hir::HirId)> {
468 let parent_id = tcx.hir().get_parent_node(id);
470 if used_unsafe.contains(&parent_id) {
471 Some(("block", parent_id))
472 } else if let Some(Node::Item(&hir::Item {
473 kind: hir::ItemKind::Fn(ref sig, _, _), ..
474 })) = tcx.hir().find(parent_id)
476 if sig.header.unsafety == hir::Unsafety::Unsafe && unsafe_op_in_unsafe_fn_allowed {
477 Some(("fn", parent_id))
482 is_enclosed(tcx, used_unsafe, parent_id, unsafe_op_in_unsafe_fn_allowed)
489 fn report_unused_unsafe(tcx: TyCtxt<'_>, used_unsafe: &FxHashSet<hir::HirId>, id: hir::HirId) {
490 let span = tcx.sess.source_map().guess_head_span(tcx.hir().span(id));
491 tcx.struct_span_lint_hir(UNUSED_UNSAFE, id, span, |lint| {
492 let msg = "unnecessary `unsafe` block";
493 let mut db = lint.build(msg);
494 db.span_label(span, msg);
495 if let Some((kind, id)) =
496 is_enclosed(tcx, used_unsafe, id, unsafe_op_in_unsafe_fn_allowed(tcx, id))
499 tcx.sess.source_map().guess_head_span(tcx.hir().span(id)),
500 format!("because it's nested under this `unsafe` {}", kind),
507 pub fn check_unsafety(tcx: TyCtxt<'_>, def_id: LocalDefId) {
508 debug!("check_unsafety({:?})", def_id);
510 // closures are handled by their parent fn.
511 if tcx.is_closure(def_id.to_def_id()) {
515 let UnsafetyCheckResult { violations, unsafe_blocks } = tcx.unsafety_check_result(def_id);
517 for &UnsafetyViolation { source_info, lint_root, kind, details } in violations.iter() {
518 let (description, note) = details.description_and_note();
522 if unsafe_op_in_unsafe_fn_allowed(tcx, lint_root) { " function or" } else { "" };
525 UnsafetyViolationKind::General => {
531 "{} is unsafe and requires unsafe{} block",
535 .span_label(source_info.span, description)
539 UnsafetyViolationKind::UnsafeFn => tcx.struct_span_lint_hir(
540 UNSAFE_OP_IN_UNSAFE_FN,
545 "{} is unsafe and requires unsafe block (error E0133)",
548 .span_label(source_info.span, description)
556 let (mut unsafe_used, mut unsafe_unused): (FxHashSet<_>, Vec<_>) = Default::default();
557 for &(block_id, is_used) in unsafe_blocks.iter() {
559 unsafe_used.insert(block_id);
561 unsafe_unused.push(block_id);
564 // The unused unsafe blocks might not be in source order; sort them so that the unused unsafe
565 // error messages are properly aligned and the issue-45107 and lint-unused-unsafe tests pass.
566 unsafe_unused.sort_by_cached_key(|hir_id| tcx.hir().span(*hir_id));
568 for &block_id in &unsafe_unused {
569 report_unused_unsafe(tcx, &unsafe_used, block_id);
573 fn unsafe_op_in_unsafe_fn_allowed(tcx: TyCtxt<'_>, id: HirId) -> bool {
574 tcx.lint_level_at_node(UNSAFE_OP_IN_UNSAFE_FN, id).0 == Level::Allow