1 use crate::build::ExprCategory;
2 use rustc_middle::thir::visit::{self, Visitor};
4 use rustc_errors::struct_span_err;
6 use rustc_middle::mir::BorrowKind;
7 use rustc_middle::thir::*;
8 use rustc_middle::ty::{self, ParamEnv, Ty, TyCtxt};
9 use rustc_session::lint::builtin::{UNSAFE_OP_IN_UNSAFE_FN, UNUSED_UNSAFE};
10 use rustc_session::lint::Level;
11 use rustc_span::def_id::{DefId, LocalDefId};
12 use rustc_span::symbol::Symbol;
18 struct UnsafetyVisitor<'a, 'tcx> {
21 /// The `HirId` of the current scope, which would be the `HirId`
22 /// of the current HIR node, modulo adjustments. Used for lint levels.
23 hir_context: hir::HirId,
24 /// The current "safety context". This notably tracks whether we are in an
25 /// `unsafe` block, and whether it has been used.
26 safety_context: SafetyContext,
27 body_unsafety: BodyUnsafety,
28 /// The `#[target_feature]` attributes of the body. Used for checking
29 /// calls to functions with `#[target_feature]` (RFC 2396).
30 body_target_features: &'tcx [Symbol],
31 /// When inside the LHS of an assignment to a field, this is the type
32 /// of the LHS and the span of the assignment expression.
33 assignment_info: Option<(Ty<'tcx>, Span)>,
34 in_union_destructure: bool,
35 param_env: ParamEnv<'tcx>,
39 impl<'tcx> UnsafetyVisitor<'_, 'tcx> {
40 fn in_safety_context(&mut self, safety_context: SafetyContext, f: impl FnOnce(&mut Self)) {
42 SafetyContext::UnsafeBlock { span: enclosing_span, .. },
43 SafetyContext::UnsafeBlock { span: block_span, hir_id, .. },
44 ) = (self.safety_context, safety_context)
46 self.warn_unused_unsafe(
49 Some((self.tcx.sess.source_map().guess_head_span(enclosing_span), "block")),
53 let prev_context = self.safety_context;
54 self.safety_context = safety_context;
58 if let SafetyContext::UnsafeBlock { used: false, span, hir_id } = self.safety_context {
59 self.warn_unused_unsafe(
62 if self.unsafe_op_in_unsafe_fn_allowed() {
63 self.body_unsafety.unsafe_fn_sig_span().map(|span| (span, "fn"))
69 self.safety_context = prev_context;
73 fn requires_unsafe(&mut self, span: Span, kind: UnsafeOpKind) {
74 let unsafe_op_in_unsafe_fn_allowed = self.unsafe_op_in_unsafe_fn_allowed();
75 match self.safety_context {
76 SafetyContext::BuiltinUnsafeBlock => {}
77 SafetyContext::UnsafeBlock { ref mut used, .. } => {
78 // Mark this block as useful (even inside `unsafe fn`, where it is technically
79 // redundant -- but we want to eventually enable `unsafe_op_in_unsafe_fn` by
80 // default which will require those blocks:
81 // https://github.com/rust-lang/rust/issues/71668#issuecomment-1203075594).
84 SafetyContext::UnsafeFn if unsafe_op_in_unsafe_fn_allowed => {}
85 SafetyContext::UnsafeFn => {
86 let (description, note) = kind.description_and_note(self.tcx);
87 // unsafe_op_in_unsafe_fn is disallowed
88 self.tcx.struct_span_lint_hir(
89 UNSAFE_OP_IN_UNSAFE_FN,
94 "{} is unsafe and requires unsafe block (error E0133)",
97 .span_label(span, kind.simple_description())
103 SafetyContext::Safe => {
104 let (description, note) = kind.description_and_note(self.tcx);
105 let fn_sugg = if unsafe_op_in_unsafe_fn_allowed { " function or" } else { "" };
110 "{} is unsafe and requires unsafe{} block",
114 .span_label(span, kind.simple_description())
121 fn warn_unused_unsafe(
125 enclosing_unsafe: Option<(Span, &'static str)>,
127 let block_span = self.tcx.sess.source_map().guess_head_span(block_span);
128 self.tcx.struct_span_lint_hir(UNUSED_UNSAFE, hir_id, block_span, |lint| {
129 let msg = "unnecessary `unsafe` block";
130 let mut db = lint.build(msg);
131 db.span_label(block_span, msg);
132 if let Some((span, kind)) = enclosing_unsafe {
133 db.span_label(span, format!("because it's nested under this `unsafe` {}", kind));
139 /// Whether the `unsafe_op_in_unsafe_fn` lint is `allow`ed at the current HIR node.
140 fn unsafe_op_in_unsafe_fn_allowed(&self) -> bool {
141 self.tcx.lint_level_at_node(UNSAFE_OP_IN_UNSAFE_FN, self.hir_context).0 == Level::Allow
145 // Searches for accesses to layout constrained fields.
146 struct LayoutConstrainedPlaceVisitor<'a, 'tcx> {
148 thir: &'a Thir<'tcx>,
152 impl<'a, 'tcx> LayoutConstrainedPlaceVisitor<'a, 'tcx> {
153 fn new(thir: &'a Thir<'tcx>, tcx: TyCtxt<'tcx>) -> Self {
154 Self { found: false, thir, tcx }
158 impl<'a, 'tcx> Visitor<'a, 'tcx> for LayoutConstrainedPlaceVisitor<'a, 'tcx> {
159 fn thir(&self) -> &'a Thir<'tcx> {
163 fn visit_expr(&mut self, expr: &Expr<'tcx>) {
165 ExprKind::Field { lhs, .. } => {
166 if let ty::Adt(adt_def, _) = self.thir[lhs].ty.kind() {
167 if (Bound::Unbounded, Bound::Unbounded)
168 != self.tcx.layout_scalar_valid_range(adt_def.did())
173 visit::walk_expr(self, expr);
176 // Keep walking through the expression as long as we stay in the same
177 // place, i.e. the expression is a place expression and not a dereference
178 // (since dereferencing something leads us to a different place).
179 ExprKind::Deref { .. } => {}
180 ref kind if ExprCategory::of(kind).map_or(true, |cat| cat == ExprCategory::Place) => {
181 visit::walk_expr(self, expr);
189 impl<'a, 'tcx> Visitor<'a, 'tcx> for UnsafetyVisitor<'a, 'tcx> {
190 fn thir(&self) -> &'a Thir<'tcx> {
194 fn visit_block(&mut self, block: &Block) {
195 match block.safety_mode {
196 // compiler-generated unsafe code should not count towards the usefulness of
197 // an outer unsafe block
198 BlockSafety::BuiltinUnsafe => {
199 self.in_safety_context(SafetyContext::BuiltinUnsafeBlock, |this| {
200 visit::walk_block(this, block)
203 BlockSafety::ExplicitUnsafe(hir_id) => {
204 self.in_safety_context(
205 SafetyContext::UnsafeBlock { span: block.span, hir_id, used: false },
206 |this| visit::walk_block(this, block),
209 BlockSafety::Safe => {
210 visit::walk_block(self, block);
215 fn visit_pat(&mut self, pat: &Pat<'tcx>) {
216 if self.in_union_destructure {
218 // binding to a variable allows getting stuff out of variable
219 PatKind::Binding { .. }
220 // match is conditional on having this value
221 | PatKind::Constant { .. }
222 | PatKind::Variant { .. }
223 | PatKind::Leaf { .. }
224 | PatKind::Deref { .. }
225 | PatKind::Range { .. }
226 | PatKind::Slice { .. }
227 | PatKind::Array { .. } => {
228 self.requires_unsafe(pat.span, AccessToUnionField);
229 return; // we can return here since this already requires unsafe
231 // wildcard doesn't take anything
233 // these just wrap other patterns
235 PatKind::AscribeUserType { .. } => {}
240 PatKind::Leaf { .. } => {
241 if let ty::Adt(adt_def, ..) = pat.ty.kind() {
242 if adt_def.is_union() {
243 let old_in_union_destructure =
244 std::mem::replace(&mut self.in_union_destructure, true);
245 visit::walk_pat(self, pat);
246 self.in_union_destructure = old_in_union_destructure;
247 } else if (Bound::Unbounded, Bound::Unbounded)
248 != self.tcx.layout_scalar_valid_range(adt_def.did())
250 let old_inside_adt = std::mem::replace(&mut self.inside_adt, true);
251 visit::walk_pat(self, pat);
252 self.inside_adt = old_inside_adt;
254 visit::walk_pat(self, pat);
257 visit::walk_pat(self, pat);
260 PatKind::Binding { mode: BindingMode::ByRef(borrow_kind), ty, .. } => {
262 let ty::Ref(_, ty, _) = ty.kind() else {
265 "BindingMode::ByRef in pattern, but found non-reference type {}",
270 BorrowKind::Shallow | BorrowKind::Shared | BorrowKind::Unique => {
271 if !ty.is_freeze(self.tcx.at(pat.span), self.param_env) {
272 self.requires_unsafe(pat.span, BorrowOfLayoutConstrainedField);
275 BorrowKind::Mut { .. } => {
276 self.requires_unsafe(pat.span, MutationOfLayoutConstrainedField);
280 visit::walk_pat(self, pat);
282 PatKind::Deref { .. } => {
283 let old_inside_adt = std::mem::replace(&mut self.inside_adt, false);
284 visit::walk_pat(self, pat);
285 self.inside_adt = old_inside_adt;
288 visit::walk_pat(self, pat);
293 fn visit_expr(&mut self, expr: &Expr<'tcx>) {
294 // could we be in the LHS of an assignment to a field?
296 ExprKind::Field { .. }
297 | ExprKind::VarRef { .. }
298 | ExprKind::UpvarRef { .. }
299 | ExprKind::Scope { .. }
300 | ExprKind::Cast { .. } => {}
302 ExprKind::AddressOf { .. }
303 | ExprKind::Adt { .. }
304 | ExprKind::Array { .. }
305 | ExprKind::Binary { .. }
306 | ExprKind::Block { .. }
307 | ExprKind::Borrow { .. }
308 | ExprKind::Literal { .. }
309 | ExprKind::NamedConst { .. }
310 | ExprKind::NonHirLiteral { .. }
311 | ExprKind::ZstLiteral { .. }
312 | ExprKind::ConstParam { .. }
313 | ExprKind::ConstBlock { .. }
314 | ExprKind::Deref { .. }
315 | ExprKind::Index { .. }
316 | ExprKind::NeverToAny { .. }
317 | ExprKind::PlaceTypeAscription { .. }
318 | ExprKind::ValueTypeAscription { .. }
319 | ExprKind::Pointer { .. }
320 | ExprKind::Repeat { .. }
321 | ExprKind::StaticRef { .. }
322 | ExprKind::ThreadLocalRef { .. }
323 | ExprKind::Tuple { .. }
324 | ExprKind::Unary { .. }
325 | ExprKind::Call { .. }
326 | ExprKind::Assign { .. }
327 | ExprKind::AssignOp { .. }
328 | ExprKind::Break { .. }
329 | ExprKind::Closure { .. }
330 | ExprKind::Continue { .. }
331 | ExprKind::Return { .. }
332 | ExprKind::Yield { .. }
333 | ExprKind::Loop { .. }
334 | ExprKind::Let { .. }
335 | ExprKind::Match { .. }
336 | ExprKind::Box { .. }
337 | ExprKind::If { .. }
338 | ExprKind::InlineAsm { .. }
339 | ExprKind::LogicalOp { .. }
340 | ExprKind::Use { .. } => {
341 // We don't need to save the old value and restore it
342 // because all the place expressions can't have more
344 self.assignment_info = None;
348 ExprKind::Scope { value, lint_level: LintLevel::Explicit(hir_id), region_scope: _ } => {
349 let prev_id = self.hir_context;
350 self.hir_context = hir_id;
351 self.visit_expr(&self.thir[value]);
352 self.hir_context = prev_id;
353 return; // don't visit the whole expression
355 ExprKind::Call { fun, ty: _, args: _, from_hir_call: _, fn_span: _ } => {
356 if self.thir[fun].ty.fn_sig(self.tcx).unsafety() == hir::Unsafety::Unsafe {
357 let func_id = if let ty::FnDef(func_id, _) = self.thir[fun].ty.kind() {
362 self.requires_unsafe(expr.span, CallToUnsafeFunction(func_id));
363 } else if let &ty::FnDef(func_did, _) = self.thir[fun].ty.kind() {
364 // If the called function has target features the calling function hasn't,
365 // the call requires `unsafe`. Don't check this on wasm
366 // targets, though. For more information on wasm see the
367 // is_like_wasm check in typeck/src/collect.rs
368 if !self.tcx.sess.target.options.is_like_wasm
371 .codegen_fn_attrs(func_did)
374 .all(|feature| self.body_target_features.contains(feature))
376 self.requires_unsafe(expr.span, CallToFunctionWith(func_did));
380 ExprKind::Deref { arg } => {
381 if let ExprKind::StaticRef { def_id, .. } = self.thir[arg].kind {
382 if self.tcx.is_mutable_static(def_id) {
383 self.requires_unsafe(expr.span, UseOfMutableStatic);
384 } else if self.tcx.is_foreign_item(def_id) {
385 self.requires_unsafe(expr.span, UseOfExternStatic);
387 } else if self.thir[arg].ty.is_unsafe_ptr() {
388 self.requires_unsafe(expr.span, DerefOfRawPointer);
391 ExprKind::InlineAsm { .. } => {
392 self.requires_unsafe(expr.span, UseOfInlineAssembly);
394 ExprKind::Adt(box AdtExpr {
401 }) => match self.tcx.layout_scalar_valid_range(adt_def.did()) {
402 (Bound::Unbounded, Bound::Unbounded) => {}
403 _ => self.requires_unsafe(expr.span, InitializingTypeWith),
405 ExprKind::Closure(box ClosureExpr {
412 let closure_def = if let Some((did, const_param_id)) =
413 ty::WithOptConstParam::try_lookup(closure_id, self.tcx)
415 ty::WithOptConstParam { did, const_param_did: Some(const_param_id) }
417 ty::WithOptConstParam::unknown(closure_id)
419 let (closure_thir, expr) = self.tcx.thir_body(closure_def).unwrap_or_else(|_| {
420 (self.tcx.alloc_steal_thir(Thir::new()), ExprId::from_u32(0))
422 let closure_thir = &closure_thir.borrow();
423 let hir_context = self.tcx.hir().local_def_id_to_hir_id(closure_id);
424 let mut closure_visitor =
425 UnsafetyVisitor { thir: closure_thir, hir_context, ..*self };
426 closure_visitor.visit_expr(&closure_thir[expr]);
427 // Unsafe blocks can be used in closures, make sure to take it into account
428 self.safety_context = closure_visitor.safety_context;
430 ExprKind::Field { lhs, .. } => {
431 let lhs = &self.thir[lhs];
432 if let ty::Adt(adt_def, _) = lhs.ty.kind() && adt_def.is_union() {
433 if let Some((assigned_ty, assignment_span)) = self.assignment_info {
434 if assigned_ty.needs_drop(self.tcx, self.param_env) {
435 // This would be unsafe, but should be outright impossible since we reject such unions.
436 self.tcx.sess.delay_span_bug(assignment_span, format!("union fields that need dropping should be impossible: {assigned_ty}"));
439 self.requires_unsafe(expr.span, AccessToUnionField);
443 ExprKind::Assign { lhs, rhs } | ExprKind::AssignOp { lhs, rhs, .. } => {
444 let lhs = &self.thir[lhs];
445 // First, check whether we are mutating a layout constrained field
446 let mut visitor = LayoutConstrainedPlaceVisitor::new(self.thir, self.tcx);
447 visit::walk_expr(&mut visitor, lhs);
449 self.requires_unsafe(expr.span, MutationOfLayoutConstrainedField);
452 // Second, check for accesses to union fields
453 // don't have any special handling for AssignOp since it causes a read *and* write to lhs
454 if matches!(expr.kind, ExprKind::Assign { .. }) {
455 self.assignment_info = Some((lhs.ty, expr.span));
456 visit::walk_expr(self, lhs);
457 self.assignment_info = None;
458 visit::walk_expr(self, &self.thir()[rhs]);
459 return; // we have already visited everything by now
462 ExprKind::Borrow { borrow_kind, arg } => {
463 let mut visitor = LayoutConstrainedPlaceVisitor::new(self.thir, self.tcx);
464 visit::walk_expr(&mut visitor, expr);
467 BorrowKind::Shallow | BorrowKind::Shared | BorrowKind::Unique
470 .is_freeze(self.tcx.at(self.thir[arg].span), self.param_env) =>
472 self.requires_unsafe(expr.span, BorrowOfLayoutConstrainedField)
474 BorrowKind::Mut { .. } => {
475 self.requires_unsafe(expr.span, MutationOfLayoutConstrainedField)
477 BorrowKind::Shallow | BorrowKind::Shared | BorrowKind::Unique => {}
481 ExprKind::Let { expr: expr_id, .. } => {
482 let let_expr = &self.thir[expr_id];
483 if let ty::Adt(adt_def, _) = let_expr.ty.kind() && adt_def.is_union() {
484 self.requires_unsafe(expr.span, AccessToUnionField);
489 visit::walk_expr(self, expr);
493 #[derive(Clone, Copy)]
498 UnsafeBlock { span: Span, hir_id: hir::HirId, used: bool },
501 #[derive(Clone, Copy)]
503 /// The body is not unsafe.
505 /// The body is an unsafe function. The span points to
506 /// the signature of the function.
511 /// Returns whether the body is unsafe.
512 fn is_unsafe(&self) -> bool {
513 matches!(self, BodyUnsafety::Unsafe(_))
516 /// If the body is unsafe, returns the `Span` of its signature.
517 fn unsafe_fn_sig_span(self) -> Option<Span> {
519 BodyUnsafety::Unsafe(span) => Some(span),
520 BodyUnsafety::Safe => None,
525 #[derive(Clone, Copy, PartialEq)]
527 CallToUnsafeFunction(Option<DefId>),
529 InitializingTypeWith,
534 MutationOfLayoutConstrainedField,
535 BorrowOfLayoutConstrainedField,
536 CallToFunctionWith(DefId),
542 pub fn simple_description(&self) -> &'static str {
544 CallToUnsafeFunction(..) => "call to unsafe function",
545 UseOfInlineAssembly => "use of inline assembly",
546 InitializingTypeWith => "initializing type with `rustc_layout_scalar_valid_range` attr",
547 UseOfMutableStatic => "use of mutable static",
548 UseOfExternStatic => "use of extern static",
549 DerefOfRawPointer => "dereference of raw pointer",
550 AccessToUnionField => "access to union field",
551 MutationOfLayoutConstrainedField => "mutation of layout constrained field",
552 BorrowOfLayoutConstrainedField => {
553 "borrow of layout constrained field with interior mutability"
555 CallToFunctionWith(..) => "call to function with `#[target_feature]`",
559 pub fn description_and_note(&self, tcx: TyCtxt<'_>) -> (Cow<'static, str>, &'static str) {
561 CallToUnsafeFunction(did) => (
562 if let Some(did) = did {
563 Cow::from(format!("call to unsafe function `{}`", tcx.def_path_str(*did)))
565 Cow::Borrowed(self.simple_description())
567 "consult the function's documentation for information on how to avoid undefined \
570 UseOfInlineAssembly => (
571 Cow::Borrowed(self.simple_description()),
572 "inline assembly is entirely unchecked and can cause undefined behavior",
574 InitializingTypeWith => (
575 Cow::Borrowed(self.simple_description()),
576 "initializing a layout restricted type's field with a value outside the valid \
577 range is undefined behavior",
579 UseOfMutableStatic => (
580 Cow::Borrowed(self.simple_description()),
581 "mutable statics can be mutated by multiple threads: aliasing violations or data \
582 races will cause undefined behavior",
584 UseOfExternStatic => (
585 Cow::Borrowed(self.simple_description()),
586 "extern statics are not controlled by the Rust type system: invalid data, \
587 aliasing violations or data races will cause undefined behavior",
589 DerefOfRawPointer => (
590 Cow::Borrowed(self.simple_description()),
591 "raw pointers may be null, dangling or unaligned; they can violate aliasing rules \
592 and cause data races: all of these are undefined behavior",
594 AccessToUnionField => (
595 Cow::Borrowed(self.simple_description()),
596 "the field may not be properly initialized: using uninitialized data will cause \
599 MutationOfLayoutConstrainedField => (
600 Cow::Borrowed(self.simple_description()),
601 "mutating layout constrained fields cannot statically be checked for valid values",
603 BorrowOfLayoutConstrainedField => (
604 Cow::Borrowed(self.simple_description()),
605 "references to fields of layout constrained fields lose the constraints. Coupled \
606 with interior mutability, the field can be changed to invalid values",
608 CallToFunctionWith(did) => (
610 "call to function `{}` with `#[target_feature]`",
611 tcx.def_path_str(*did)
613 "can only be called if the required target features are available",
619 pub fn check_unsafety<'tcx>(tcx: TyCtxt<'tcx>, def: ty::WithOptConstParam<LocalDefId>) {
620 // THIR unsafeck is gated under `-Z thir-unsafeck`
621 if !tcx.sess.opts.unstable_opts.thir_unsafeck {
625 // Closures are handled by their owner, if it has a body
626 if tcx.is_closure(def.did.to_def_id()) {
628 let owner = hir.enclosing_body_owner(hir.local_def_id_to_hir_id(def.did));
629 tcx.ensure().thir_check_unsafety(owner);
633 let Ok((thir, expr)) = tcx.thir_body(def) else {
636 let thir = &thir.borrow();
637 // If `thir` is empty, a type error occurred, skip this body.
638 if thir.exprs.is_empty() {
642 let hir_id = tcx.hir().local_def_id_to_hir_id(def.did);
643 let body_unsafety = tcx.hir().fn_sig_by_hir_id(hir_id).map_or(BodyUnsafety::Safe, |fn_sig| {
644 if fn_sig.header.unsafety == hir::Unsafety::Unsafe {
645 BodyUnsafety::Unsafe(fn_sig.span)
650 let body_target_features = &tcx.body_codegen_attrs(def.did.to_def_id()).target_features;
652 if body_unsafety.is_unsafe() { SafetyContext::UnsafeFn } else { SafetyContext::Safe };
653 let mut visitor = UnsafetyVisitor {
659 body_target_features,
660 assignment_info: None,
661 in_union_destructure: false,
662 param_env: tcx.param_env(def.did),
665 visitor.visit_expr(&thir[expr]);
668 pub(crate) fn thir_check_unsafety<'tcx>(tcx: TyCtxt<'tcx>, def_id: LocalDefId) {
669 if let Some(def) = ty::WithOptConstParam::try_lookup(def_id, tcx) {
670 tcx.thir_check_unsafety_for_const_arg(def)
672 check_unsafety(tcx, ty::WithOptConstParam::unknown(def_id))
676 pub(crate) fn thir_check_unsafety_for_const_arg<'tcx>(
678 (did, param_did): (LocalDefId, DefId),
680 check_unsafety(tcx, ty::WithOptConstParam { did, const_param_did: Some(param_did) })