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,
92 format!("{} is unsafe and requires unsafe block (error E0133)", description,),
93 |lint| lint.span_label(span, kind.simple_description()).note(note),
96 SafetyContext::Safe => {
97 let (description, note) = kind.description_and_note(self.tcx);
98 let fn_sugg = if unsafe_op_in_unsafe_fn_allowed { " function or" } else { "" };
103 "{} is unsafe and requires unsafe{} block",
107 .span_label(span, kind.simple_description())
114 fn warn_unused_unsafe(
118 enclosing_unsafe: Option<(Span, &'static str)>,
120 let block_span = self.tcx.sess.source_map().guess_head_span(block_span);
121 let msg = "unnecessary `unsafe` block";
122 self.tcx.struct_span_lint_hir(UNUSED_UNSAFE, hir_id, block_span, msg, |lint| {
123 lint.span_label(block_span, msg);
124 if let Some((span, kind)) = enclosing_unsafe {
125 lint.span_label(span, format!("because it's nested under this `unsafe` {}", kind));
131 /// Whether the `unsafe_op_in_unsafe_fn` lint is `allow`ed at the current HIR node.
132 fn unsafe_op_in_unsafe_fn_allowed(&self) -> bool {
133 self.tcx.lint_level_at_node(UNSAFE_OP_IN_UNSAFE_FN, self.hir_context).0 == Level::Allow
137 // Searches for accesses to layout constrained fields.
138 struct LayoutConstrainedPlaceVisitor<'a, 'tcx> {
140 thir: &'a Thir<'tcx>,
144 impl<'a, 'tcx> LayoutConstrainedPlaceVisitor<'a, 'tcx> {
145 fn new(thir: &'a Thir<'tcx>, tcx: TyCtxt<'tcx>) -> Self {
146 Self { found: false, thir, tcx }
150 impl<'a, 'tcx> Visitor<'a, 'tcx> for LayoutConstrainedPlaceVisitor<'a, 'tcx> {
151 fn thir(&self) -> &'a Thir<'tcx> {
155 fn visit_expr(&mut self, expr: &Expr<'tcx>) {
157 ExprKind::Field { lhs, .. } => {
158 if let ty::Adt(adt_def, _) = self.thir[lhs].ty.kind() {
159 if (Bound::Unbounded, Bound::Unbounded)
160 != self.tcx.layout_scalar_valid_range(adt_def.did())
165 visit::walk_expr(self, expr);
168 // Keep walking through the expression as long as we stay in the same
169 // place, i.e. the expression is a place expression and not a dereference
170 // (since dereferencing something leads us to a different place).
171 ExprKind::Deref { .. } => {}
172 ref kind if ExprCategory::of(kind).map_or(true, |cat| cat == ExprCategory::Place) => {
173 visit::walk_expr(self, expr);
181 impl<'a, 'tcx> Visitor<'a, 'tcx> for UnsafetyVisitor<'a, 'tcx> {
182 fn thir(&self) -> &'a Thir<'tcx> {
186 fn visit_block(&mut self, block: &Block) {
187 match block.safety_mode {
188 // compiler-generated unsafe code should not count towards the usefulness of
189 // an outer unsafe block
190 BlockSafety::BuiltinUnsafe => {
191 self.in_safety_context(SafetyContext::BuiltinUnsafeBlock, |this| {
192 visit::walk_block(this, block)
195 BlockSafety::ExplicitUnsafe(hir_id) => {
196 self.in_safety_context(
197 SafetyContext::UnsafeBlock { span: block.span, hir_id, used: false },
198 |this| visit::walk_block(this, block),
201 BlockSafety::Safe => {
202 visit::walk_block(self, block);
207 fn visit_pat(&mut self, pat: &Pat<'tcx>) {
208 if self.in_union_destructure {
210 // binding to a variable allows getting stuff out of variable
211 PatKind::Binding { .. }
212 // match is conditional on having this value
213 | PatKind::Constant { .. }
214 | PatKind::Variant { .. }
215 | PatKind::Leaf { .. }
216 | PatKind::Deref { .. }
217 | PatKind::Range { .. }
218 | PatKind::Slice { .. }
219 | PatKind::Array { .. } => {
220 self.requires_unsafe(pat.span, AccessToUnionField);
221 return; // we can return here since this already requires unsafe
223 // wildcard doesn't take anything
225 // these just wrap other patterns
227 PatKind::AscribeUserType { .. } => {}
232 PatKind::Leaf { .. } => {
233 if let ty::Adt(adt_def, ..) = pat.ty.kind() {
234 if adt_def.is_union() {
235 let old_in_union_destructure =
236 std::mem::replace(&mut self.in_union_destructure, true);
237 visit::walk_pat(self, pat);
238 self.in_union_destructure = old_in_union_destructure;
239 } else if (Bound::Unbounded, Bound::Unbounded)
240 != self.tcx.layout_scalar_valid_range(adt_def.did())
242 let old_inside_adt = std::mem::replace(&mut self.inside_adt, true);
243 visit::walk_pat(self, pat);
244 self.inside_adt = old_inside_adt;
246 visit::walk_pat(self, pat);
249 visit::walk_pat(self, pat);
252 PatKind::Binding { mode: BindingMode::ByRef(borrow_kind), ty, .. } => {
254 let ty::Ref(_, ty, _) = ty.kind() else {
257 "BindingMode::ByRef in pattern, but found non-reference type {}",
262 BorrowKind::Shallow | BorrowKind::Shared | BorrowKind::Unique => {
263 if !ty.is_freeze(self.tcx, self.param_env) {
264 self.requires_unsafe(pat.span, BorrowOfLayoutConstrainedField);
267 BorrowKind::Mut { .. } => {
268 self.requires_unsafe(pat.span, MutationOfLayoutConstrainedField);
272 visit::walk_pat(self, pat);
274 PatKind::Deref { .. } => {
275 let old_inside_adt = std::mem::replace(&mut self.inside_adt, false);
276 visit::walk_pat(self, pat);
277 self.inside_adt = old_inside_adt;
280 visit::walk_pat(self, pat);
285 fn visit_expr(&mut self, expr: &Expr<'tcx>) {
286 // could we be in the LHS of an assignment to a field?
288 ExprKind::Field { .. }
289 | ExprKind::VarRef { .. }
290 | ExprKind::UpvarRef { .. }
291 | ExprKind::Scope { .. }
292 | ExprKind::Cast { .. } => {}
294 ExprKind::AddressOf { .. }
295 | ExprKind::Adt { .. }
296 | ExprKind::Array { .. }
297 | ExprKind::Binary { .. }
298 | ExprKind::Block { .. }
299 | ExprKind::Borrow { .. }
300 | ExprKind::Literal { .. }
301 | ExprKind::NamedConst { .. }
302 | ExprKind::NonHirLiteral { .. }
303 | ExprKind::ZstLiteral { .. }
304 | ExprKind::ConstParam { .. }
305 | ExprKind::ConstBlock { .. }
306 | ExprKind::Deref { .. }
307 | ExprKind::Index { .. }
308 | ExprKind::NeverToAny { .. }
309 | ExprKind::PlaceTypeAscription { .. }
310 | ExprKind::ValueTypeAscription { .. }
311 | ExprKind::Pointer { .. }
312 | ExprKind::Repeat { .. }
313 | ExprKind::StaticRef { .. }
314 | ExprKind::ThreadLocalRef { .. }
315 | ExprKind::Tuple { .. }
316 | ExprKind::Unary { .. }
317 | ExprKind::Call { .. }
318 | ExprKind::Assign { .. }
319 | ExprKind::AssignOp { .. }
320 | ExprKind::Break { .. }
321 | ExprKind::Closure { .. }
322 | ExprKind::Continue { .. }
323 | ExprKind::Return { .. }
324 | ExprKind::Yield { .. }
325 | ExprKind::Loop { .. }
326 | ExprKind::Let { .. }
327 | ExprKind::Match { .. }
328 | ExprKind::Box { .. }
329 | ExprKind::If { .. }
330 | ExprKind::InlineAsm { .. }
331 | ExprKind::LogicalOp { .. }
332 | ExprKind::Use { .. } => {
333 // We don't need to save the old value and restore it
334 // because all the place expressions can't have more
336 self.assignment_info = None;
340 ExprKind::Scope { value, lint_level: LintLevel::Explicit(hir_id), region_scope: _ } => {
341 let prev_id = self.hir_context;
342 self.hir_context = hir_id;
343 self.visit_expr(&self.thir[value]);
344 self.hir_context = prev_id;
345 return; // don't visit the whole expression
347 ExprKind::Call { fun, ty: _, args: _, from_hir_call: _, fn_span: _ } => {
348 if self.thir[fun].ty.fn_sig(self.tcx).unsafety() == hir::Unsafety::Unsafe {
349 let func_id = if let ty::FnDef(func_id, _) = self.thir[fun].ty.kind() {
354 self.requires_unsafe(expr.span, CallToUnsafeFunction(func_id));
355 } else if let &ty::FnDef(func_did, _) = self.thir[fun].ty.kind() {
356 // If the called function has target features the calling function hasn't,
357 // the call requires `unsafe`. Don't check this on wasm
358 // targets, though. For more information on wasm see the
359 // is_like_wasm check in hir_analysis/src/collect.rs
360 if !self.tcx.sess.target.options.is_like_wasm
363 .codegen_fn_attrs(func_did)
366 .all(|feature| self.body_target_features.contains(feature))
368 self.requires_unsafe(expr.span, CallToFunctionWith(func_did));
372 ExprKind::Deref { arg } => {
373 if let ExprKind::StaticRef { def_id, .. } = self.thir[arg].kind {
374 if self.tcx.is_mutable_static(def_id) {
375 self.requires_unsafe(expr.span, UseOfMutableStatic);
376 } else if self.tcx.is_foreign_item(def_id) {
377 self.requires_unsafe(expr.span, UseOfExternStatic);
379 } else if self.thir[arg].ty.is_unsafe_ptr() {
380 self.requires_unsafe(expr.span, DerefOfRawPointer);
383 ExprKind::InlineAsm { .. } => {
384 self.requires_unsafe(expr.span, UseOfInlineAssembly);
386 ExprKind::Adt(box AdtExpr {
393 }) => match self.tcx.layout_scalar_valid_range(adt_def.did()) {
394 (Bound::Unbounded, Bound::Unbounded) => {}
395 _ => self.requires_unsafe(expr.span, InitializingTypeWith),
397 ExprKind::Closure(box ClosureExpr {
404 let closure_def = if let Some((did, const_param_id)) =
405 ty::WithOptConstParam::try_lookup(closure_id, self.tcx)
407 ty::WithOptConstParam { did, const_param_did: Some(const_param_id) }
409 ty::WithOptConstParam::unknown(closure_id)
411 let (closure_thir, expr) = self.tcx.thir_body(closure_def).unwrap_or_else(|_| {
412 (self.tcx.alloc_steal_thir(Thir::new()), ExprId::from_u32(0))
414 let closure_thir = &closure_thir.borrow();
415 let hir_context = self.tcx.hir().local_def_id_to_hir_id(closure_id);
416 let mut closure_visitor =
417 UnsafetyVisitor { thir: closure_thir, hir_context, ..*self };
418 closure_visitor.visit_expr(&closure_thir[expr]);
419 // Unsafe blocks can be used in closures, make sure to take it into account
420 self.safety_context = closure_visitor.safety_context;
422 ExprKind::Field { lhs, .. } => {
423 let lhs = &self.thir[lhs];
424 if let ty::Adt(adt_def, _) = lhs.ty.kind() && adt_def.is_union() {
425 if let Some((assigned_ty, assignment_span)) = self.assignment_info {
426 if assigned_ty.needs_drop(self.tcx, self.param_env) {
427 // This would be unsafe, but should be outright impossible since we reject such unions.
428 self.tcx.sess.delay_span_bug(assignment_span, format!("union fields that need dropping should be impossible: {assigned_ty}"));
431 self.requires_unsafe(expr.span, AccessToUnionField);
435 ExprKind::Assign { lhs, rhs } | ExprKind::AssignOp { lhs, rhs, .. } => {
436 let lhs = &self.thir[lhs];
437 // First, check whether we are mutating a layout constrained field
438 let mut visitor = LayoutConstrainedPlaceVisitor::new(self.thir, self.tcx);
439 visit::walk_expr(&mut visitor, lhs);
441 self.requires_unsafe(expr.span, MutationOfLayoutConstrainedField);
444 // Second, check for accesses to union fields
445 // don't have any special handling for AssignOp since it causes a read *and* write to lhs
446 if matches!(expr.kind, ExprKind::Assign { .. }) {
447 self.assignment_info = Some((lhs.ty, expr.span));
448 visit::walk_expr(self, lhs);
449 self.assignment_info = None;
450 visit::walk_expr(self, &self.thir()[rhs]);
451 return; // we have already visited everything by now
454 ExprKind::Borrow { borrow_kind, arg } => {
455 let mut visitor = LayoutConstrainedPlaceVisitor::new(self.thir, self.tcx);
456 visit::walk_expr(&mut visitor, expr);
459 BorrowKind::Shallow | BorrowKind::Shared | BorrowKind::Unique
460 if !self.thir[arg].ty.is_freeze(self.tcx, self.param_env) =>
462 self.requires_unsafe(expr.span, BorrowOfLayoutConstrainedField)
464 BorrowKind::Mut { .. } => {
465 self.requires_unsafe(expr.span, MutationOfLayoutConstrainedField)
467 BorrowKind::Shallow | BorrowKind::Shared | BorrowKind::Unique => {}
471 ExprKind::Let { expr: expr_id, .. } => {
472 let let_expr = &self.thir[expr_id];
473 if let ty::Adt(adt_def, _) = let_expr.ty.kind() && adt_def.is_union() {
474 self.requires_unsafe(expr.span, AccessToUnionField);
479 visit::walk_expr(self, expr);
483 #[derive(Clone, Copy)]
488 UnsafeBlock { span: Span, hir_id: hir::HirId, used: bool },
491 #[derive(Clone, Copy)]
493 /// The body is not unsafe.
495 /// The body is an unsafe function. The span points to
496 /// the signature of the function.
501 /// Returns whether the body is unsafe.
502 fn is_unsafe(&self) -> bool {
503 matches!(self, BodyUnsafety::Unsafe(_))
506 /// If the body is unsafe, returns the `Span` of its signature.
507 fn unsafe_fn_sig_span(self) -> Option<Span> {
509 BodyUnsafety::Unsafe(span) => Some(span),
510 BodyUnsafety::Safe => None,
515 #[derive(Clone, Copy, PartialEq)]
517 CallToUnsafeFunction(Option<DefId>),
519 InitializingTypeWith,
524 MutationOfLayoutConstrainedField,
525 BorrowOfLayoutConstrainedField,
526 CallToFunctionWith(DefId),
532 pub fn simple_description(&self) -> &'static str {
534 CallToUnsafeFunction(..) => "call to unsafe function",
535 UseOfInlineAssembly => "use of inline assembly",
536 InitializingTypeWith => "initializing type with `rustc_layout_scalar_valid_range` attr",
537 UseOfMutableStatic => "use of mutable static",
538 UseOfExternStatic => "use of extern static",
539 DerefOfRawPointer => "dereference of raw pointer",
540 AccessToUnionField => "access to union field",
541 MutationOfLayoutConstrainedField => "mutation of layout constrained field",
542 BorrowOfLayoutConstrainedField => {
543 "borrow of layout constrained field with interior mutability"
545 CallToFunctionWith(..) => "call to function with `#[target_feature]`",
549 pub fn description_and_note(&self, tcx: TyCtxt<'_>) -> (Cow<'static, str>, &'static str) {
551 CallToUnsafeFunction(did) => (
552 if let Some(did) = did {
553 Cow::from(format!("call to unsafe function `{}`", tcx.def_path_str(*did)))
555 Cow::Borrowed(self.simple_description())
557 "consult the function's documentation for information on how to avoid undefined \
560 UseOfInlineAssembly => (
561 Cow::Borrowed(self.simple_description()),
562 "inline assembly is entirely unchecked and can cause undefined behavior",
564 InitializingTypeWith => (
565 Cow::Borrowed(self.simple_description()),
566 "initializing a layout restricted type's field with a value outside the valid \
567 range is undefined behavior",
569 UseOfMutableStatic => (
570 Cow::Borrowed(self.simple_description()),
571 "mutable statics can be mutated by multiple threads: aliasing violations or data \
572 races will cause undefined behavior",
574 UseOfExternStatic => (
575 Cow::Borrowed(self.simple_description()),
576 "extern statics are not controlled by the Rust type system: invalid data, \
577 aliasing violations or data races will cause undefined behavior",
579 DerefOfRawPointer => (
580 Cow::Borrowed(self.simple_description()),
581 "raw pointers may be null, dangling or unaligned; they can violate aliasing rules \
582 and cause data races: all of these are undefined behavior",
584 AccessToUnionField => (
585 Cow::Borrowed(self.simple_description()),
586 "the field may not be properly initialized: using uninitialized data will cause \
589 MutationOfLayoutConstrainedField => (
590 Cow::Borrowed(self.simple_description()),
591 "mutating layout constrained fields cannot statically be checked for valid values",
593 BorrowOfLayoutConstrainedField => (
594 Cow::Borrowed(self.simple_description()),
595 "references to fields of layout constrained fields lose the constraints. Coupled \
596 with interior mutability, the field can be changed to invalid values",
598 CallToFunctionWith(did) => (
600 "call to function `{}` with `#[target_feature]`",
601 tcx.def_path_str(*did)
603 "can only be called if the required target features are available",
609 pub fn check_unsafety<'tcx>(tcx: TyCtxt<'tcx>, def: ty::WithOptConstParam<LocalDefId>) {
610 // THIR unsafeck is gated under `-Z thir-unsafeck`
611 if !tcx.sess.opts.unstable_opts.thir_unsafeck {
615 // Closures are handled by their owner, if it has a body
616 if tcx.is_closure(def.did.to_def_id()) {
618 let owner = hir.enclosing_body_owner(hir.local_def_id_to_hir_id(def.did));
619 tcx.ensure().thir_check_unsafety(owner);
623 let Ok((thir, expr)) = tcx.thir_body(def) else {
626 let thir = &thir.borrow();
627 // If `thir` is empty, a type error occurred, skip this body.
628 if thir.exprs.is_empty() {
632 let hir_id = tcx.hir().local_def_id_to_hir_id(def.did);
633 let body_unsafety = tcx.hir().fn_sig_by_hir_id(hir_id).map_or(BodyUnsafety::Safe, |fn_sig| {
634 if fn_sig.header.unsafety == hir::Unsafety::Unsafe {
635 BodyUnsafety::Unsafe(fn_sig.span)
640 let body_target_features = &tcx.body_codegen_attrs(def.did.to_def_id()).target_features;
642 if body_unsafety.is_unsafe() { SafetyContext::UnsafeFn } else { SafetyContext::Safe };
643 let mut visitor = UnsafetyVisitor {
649 body_target_features,
650 assignment_info: None,
651 in_union_destructure: false,
652 param_env: tcx.param_env(def.did),
655 visitor.visit_expr(&thir[expr]);
658 pub(crate) fn thir_check_unsafety<'tcx>(tcx: TyCtxt<'tcx>, def_id: LocalDefId) {
659 if let Some(def) = ty::WithOptConstParam::try_lookup(def_id, tcx) {
660 tcx.thir_check_unsafety_for_const_arg(def)
662 check_unsafety(tcx, ty::WithOptConstParam::unknown(def_id))
666 pub(crate) fn thir_check_unsafety_for_const_arg<'tcx>(
668 (did, param_did): (LocalDefId, DefId),
670 check_unsafety(tcx, ty::WithOptConstParam { did, const_param_did: Some(param_did) })