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;
17 struct UnsafetyVisitor<'a, 'tcx> {
20 /// The `HirId` of the current scope, which would be the `HirId`
21 /// of the current HIR node, modulo adjustments. Used for lint levels.
22 hir_context: hir::HirId,
23 /// The current "safety context". This notably tracks whether we are in an
24 /// `unsafe` block, and whether it has been used.
25 safety_context: SafetyContext,
26 body_unsafety: BodyUnsafety,
27 /// The `#[target_feature]` attributes of the body. Used for checking
28 /// calls to functions with `#[target_feature]` (RFC 2396).
29 body_target_features: &'tcx Vec<Symbol>,
30 /// When inside the LHS of an assignment to a field, this is the type
31 /// of the LHS and the span of the assignment expression.
32 assignment_info: Option<(Ty<'tcx>, Span)>,
33 in_union_destructure: bool,
34 param_env: ParamEnv<'tcx>,
38 impl<'tcx> UnsafetyVisitor<'_, 'tcx> {
39 fn in_safety_context(&mut self, safety_context: SafetyContext, f: impl FnOnce(&mut Self)) {
41 SafetyContext::UnsafeBlock { span: enclosing_span, .. },
42 SafetyContext::UnsafeBlock { span: block_span, hir_id, .. },
43 ) = (self.safety_context, safety_context)
45 self.warn_unused_unsafe(
48 Some((self.tcx.sess.source_map().guess_head_span(enclosing_span), "block")),
52 let prev_context = self.safety_context;
53 self.safety_context = safety_context;
57 if let SafetyContext::UnsafeBlock { used: false, span, hir_id } = self.safety_context {
58 self.warn_unused_unsafe(
61 if self.unsafe_op_in_unsafe_fn_allowed() {
62 self.body_unsafety.unsafe_fn_sig_span().map(|span| (span, "fn"))
68 self.safety_context = prev_context;
72 fn requires_unsafe(&mut self, span: Span, kind: UnsafeOpKind) {
73 let (description, note) = kind.description_and_note();
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 if !self.body_unsafety.is_unsafe() || !unsafe_op_in_unsafe_fn_allowed {
79 // Mark this block as useful
83 SafetyContext::UnsafeFn if unsafe_op_in_unsafe_fn_allowed => {}
84 SafetyContext::UnsafeFn => {
85 // unsafe_op_in_unsafe_fn is disallowed
86 self.tcx.struct_span_lint_hir(
87 UNSAFE_OP_IN_UNSAFE_FN,
92 "{} is unsafe and requires unsafe block (error E0133)",
95 .span_label(span, description)
101 SafetyContext::Safe => {
102 let fn_sugg = if unsafe_op_in_unsafe_fn_allowed { " function or" } else { "" };
107 "{} is unsafe and requires unsafe{} block",
111 .span_label(span, description)
118 fn warn_unused_unsafe(
122 enclosing_unsafe: Option<(Span, &'static str)>,
124 let block_span = self.tcx.sess.source_map().guess_head_span(block_span);
125 self.tcx.struct_span_lint_hir(UNUSED_UNSAFE, hir_id, block_span, |lint| {
126 let msg = "unnecessary `unsafe` block";
127 let mut db = lint.build(msg);
128 db.span_label(block_span, msg);
129 if let Some((span, kind)) = enclosing_unsafe {
130 db.span_label(span, format!("because it's nested under this `unsafe` {}", kind));
136 /// Whether the `unsafe_op_in_unsafe_fn` lint is `allow`ed at the current HIR node.
137 fn unsafe_op_in_unsafe_fn_allowed(&self) -> bool {
138 self.tcx.lint_level_at_node(UNSAFE_OP_IN_UNSAFE_FN, self.hir_context).0 == Level::Allow
142 // Searches for accesses to layout constrained fields.
143 struct LayoutConstrainedPlaceVisitor<'a, 'tcx> {
145 thir: &'a Thir<'tcx>,
149 impl<'a, 'tcx> LayoutConstrainedPlaceVisitor<'a, 'tcx> {
150 fn new(thir: &'a Thir<'tcx>, tcx: TyCtxt<'tcx>) -> Self {
151 Self { found: false, thir, tcx }
155 impl<'a, 'tcx> Visitor<'a, 'tcx> for LayoutConstrainedPlaceVisitor<'a, 'tcx> {
156 fn thir(&self) -> &'a Thir<'tcx> {
160 fn visit_expr(&mut self, expr: &Expr<'tcx>) {
162 ExprKind::Field { lhs, .. } => {
163 if let ty::Adt(adt_def, _) = self.thir[lhs].ty.kind() {
164 if (Bound::Unbounded, Bound::Unbounded)
165 != self.tcx.layout_scalar_valid_range(adt_def.did)
170 visit::walk_expr(self, expr);
173 // Keep walking through the expression as long as we stay in the same
174 // place, i.e. the expression is a place expression and not a dereference
175 // (since dereferencing something leads us to a different place).
176 ExprKind::Deref { .. } => {}
177 ref kind if ExprCategory::of(kind).map_or(true, |cat| cat == ExprCategory::Place) => {
178 visit::walk_expr(self, expr);
186 impl<'a, 'tcx> Visitor<'a, 'tcx> for UnsafetyVisitor<'a, 'tcx> {
187 fn thir(&self) -> &'a Thir<'tcx> {
191 fn visit_block(&mut self, block: &Block) {
192 match block.safety_mode {
193 // compiler-generated unsafe code should not count towards the usefulness of
194 // an outer unsafe block
195 BlockSafety::BuiltinUnsafe => {
196 self.in_safety_context(SafetyContext::BuiltinUnsafeBlock, |this| {
197 visit::walk_block(this, block)
200 BlockSafety::ExplicitUnsafe(hir_id) => {
201 self.in_safety_context(
202 SafetyContext::UnsafeBlock { span: block.span, hir_id, used: false },
203 |this| visit::walk_block(this, block),
206 BlockSafety::Safe => {
207 visit::walk_block(self, block);
212 fn visit_pat(&mut self, pat: &Pat<'tcx>) {
213 if self.in_union_destructure {
215 // binding to a variable allows getting stuff out of variable
216 PatKind::Binding { .. }
217 // match is conditional on having this value
218 | PatKind::Constant { .. }
219 | PatKind::Variant { .. }
220 | PatKind::Leaf { .. }
221 | PatKind::Deref { .. }
222 | PatKind::Range { .. }
223 | PatKind::Slice { .. }
224 | PatKind::Array { .. } => {
225 self.requires_unsafe(pat.span, AccessToUnionField);
226 return; // we can return here since this already requires unsafe
228 // wildcard doesn't take anything
230 // these just wrap other patterns
232 PatKind::AscribeUserType { .. } => {}
237 PatKind::Leaf { .. } => {
238 if let ty::Adt(adt_def, ..) = pat.ty.kind() {
239 if adt_def.is_union() {
240 let old_in_union_destructure =
241 std::mem::replace(&mut self.in_union_destructure, true);
242 visit::walk_pat(self, pat);
243 self.in_union_destructure = old_in_union_destructure;
244 } else if (Bound::Unbounded, Bound::Unbounded)
245 != self.tcx.layout_scalar_valid_range(adt_def.did)
247 let old_inside_adt = std::mem::replace(&mut self.inside_adt, true);
248 visit::walk_pat(self, pat);
249 self.inside_adt = old_inside_adt;
251 visit::walk_pat(self, pat);
254 visit::walk_pat(self, pat);
257 PatKind::Binding { mode: BindingMode::ByRef(borrow_kind), ty, .. } => {
259 let ty::Ref(_, ty, _) = ty.kind() else {
262 "BindingMode::ByRef in pattern, but found non-reference type {}",
267 BorrowKind::Shallow | BorrowKind::Shared | BorrowKind::Unique => {
268 if !ty.is_freeze(self.tcx.at(pat.span), self.param_env) {
269 self.requires_unsafe(pat.span, BorrowOfLayoutConstrainedField);
272 BorrowKind::Mut { .. } => {
273 self.requires_unsafe(pat.span, MutationOfLayoutConstrainedField);
277 visit::walk_pat(self, pat);
279 PatKind::Deref { .. } => {
280 let old_inside_adt = std::mem::replace(&mut self.inside_adt, false);
281 visit::walk_pat(self, pat);
282 self.inside_adt = old_inside_adt;
285 visit::walk_pat(self, pat);
290 fn visit_expr(&mut self, expr: &Expr<'tcx>) {
291 // could we be in the LHS of an assignment to a field?
293 ExprKind::Field { .. }
294 | ExprKind::VarRef { .. }
295 | ExprKind::UpvarRef { .. }
296 | ExprKind::Scope { .. }
297 | ExprKind::Cast { .. } => {}
299 ExprKind::AddressOf { .. }
300 | ExprKind::Adt { .. }
301 | ExprKind::Array { .. }
302 | ExprKind::Binary { .. }
303 | ExprKind::Block { .. }
304 | ExprKind::Borrow { .. }
305 | ExprKind::Literal { .. }
306 | ExprKind::ConstBlock { .. }
307 | ExprKind::Deref { .. }
308 | ExprKind::Index { .. }
309 | ExprKind::NeverToAny { .. }
310 | ExprKind::PlaceTypeAscription { .. }
311 | ExprKind::ValueTypeAscription { .. }
312 | ExprKind::Pointer { .. }
313 | ExprKind::Repeat { .. }
314 | ExprKind::StaticRef { .. }
315 | ExprKind::ThreadLocalRef { .. }
316 | ExprKind::Tuple { .. }
317 | ExprKind::Unary { .. }
318 | ExprKind::Call { .. }
319 | ExprKind::Assign { .. }
320 | ExprKind::AssignOp { .. }
321 | ExprKind::Break { .. }
322 | ExprKind::Closure { .. }
323 | ExprKind::Continue { .. }
324 | ExprKind::Return { .. }
325 | ExprKind::Yield { .. }
326 | ExprKind::Loop { .. }
327 | ExprKind::Let { .. }
328 | ExprKind::Match { .. }
329 | ExprKind::Box { .. }
330 | ExprKind::If { .. }
331 | ExprKind::InlineAsm { .. }
332 | ExprKind::LogicalOp { .. }
333 | ExprKind::Use { .. } => {
334 // We don't need to save the old value and restore it
335 // because all the place expressions can't have more
337 self.assignment_info = None;
341 ExprKind::Scope { value, lint_level: LintLevel::Explicit(hir_id), region_scope: _ } => {
342 let prev_id = self.hir_context;
343 self.hir_context = hir_id;
344 self.visit_expr(&self.thir[value]);
345 self.hir_context = prev_id;
346 return; // don't visit the whole expression
348 ExprKind::Call { fun, ty: _, args: _, from_hir_call: _, fn_span: _ } => {
349 if self.thir[fun].ty.fn_sig(self.tcx).unsafety() == hir::Unsafety::Unsafe {
350 self.requires_unsafe(expr.span, CallToUnsafeFunction);
351 } else if let &ty::FnDef(func_did, _) = self.thir[fun].ty.kind() {
352 // If the called function has target features the calling function hasn't,
353 // the call requires `unsafe`. Don't check this on wasm
354 // targets, though. For more information on wasm see the
355 // is_like_wasm check in typeck/src/collect.rs
356 if !self.tcx.sess.target.options.is_like_wasm
359 .codegen_fn_attrs(func_did)
362 .all(|feature| self.body_target_features.contains(feature))
364 self.requires_unsafe(expr.span, CallToFunctionWith);
368 ExprKind::Deref { arg } => {
369 if let ExprKind::StaticRef { def_id, .. } = self.thir[arg].kind {
370 if self.tcx.is_mutable_static(def_id) {
371 self.requires_unsafe(expr.span, UseOfMutableStatic);
372 } else if self.tcx.is_foreign_item(def_id) {
373 self.requires_unsafe(expr.span, UseOfExternStatic);
375 } else if self.thir[arg].ty.is_unsafe_ptr() {
376 self.requires_unsafe(expr.span, DerefOfRawPointer);
379 ExprKind::InlineAsm { .. } => {
380 self.requires_unsafe(expr.span, UseOfInlineAssembly);
382 ExprKind::Adt(box Adt {
389 }) => match self.tcx.layout_scalar_valid_range(adt_def.did) {
390 (Bound::Unbounded, Bound::Unbounded) => {}
391 _ => self.requires_unsafe(expr.span, InitializingTypeWith),
400 let closure_id = closure_id.expect_local();
401 let closure_def = if let Some((did, const_param_id)) =
402 ty::WithOptConstParam::try_lookup(closure_id, self.tcx)
404 ty::WithOptConstParam { did, const_param_did: Some(const_param_id) }
406 ty::WithOptConstParam::unknown(closure_id)
408 let (closure_thir, expr) = self.tcx.thir_body(closure_def);
409 let closure_thir = &closure_thir.borrow();
410 let hir_context = self.tcx.hir().local_def_id_to_hir_id(closure_id);
411 let mut closure_visitor =
412 UnsafetyVisitor { thir: closure_thir, hir_context, ..*self };
413 closure_visitor.visit_expr(&closure_thir[expr]);
414 // Unsafe blocks can be used in closures, make sure to take it into account
415 self.safety_context = closure_visitor.safety_context;
417 ExprKind::Field { lhs, .. } => {
418 let lhs = &self.thir[lhs];
419 if let ty::Adt(adt_def, _) = lhs.ty.kind() {
420 if adt_def.is_union() {
421 if let Some((assigned_ty, assignment_span)) = self.assignment_info {
422 // To avoid semver hazard, we only consider `Copy` and `ManuallyDrop` non-dropping.
425 .map_or(false, |adt| adt.is_manually_drop())
427 .is_copy_modulo_regions(self.tcx.at(expr.span), self.param_env))
429 self.requires_unsafe(assignment_span, AssignToDroppingUnionField);
431 // write to non-drop union field, safe
434 self.requires_unsafe(expr.span, AccessToUnionField);
439 ExprKind::Assign { lhs, rhs } | ExprKind::AssignOp { lhs, rhs, .. } => {
440 let lhs = &self.thir[lhs];
441 // First, check whether we are mutating a layout constrained field
442 let mut visitor = LayoutConstrainedPlaceVisitor::new(self.thir, self.tcx);
443 visit::walk_expr(&mut visitor, lhs);
445 self.requires_unsafe(expr.span, MutationOfLayoutConstrainedField);
448 // Second, check for accesses to union fields
449 // don't have any special handling for AssignOp since it causes a read *and* write to lhs
450 if matches!(expr.kind, ExprKind::Assign { .. }) {
451 self.assignment_info = Some((lhs.ty, expr.span));
452 visit::walk_expr(self, lhs);
453 self.assignment_info = None;
454 visit::walk_expr(self, &self.thir()[rhs]);
455 return; // we have already visited everything by now
458 ExprKind::Borrow { borrow_kind, arg } => {
459 let mut visitor = LayoutConstrainedPlaceVisitor::new(self.thir, self.tcx);
460 visit::walk_expr(&mut visitor, expr);
463 BorrowKind::Shallow | BorrowKind::Shared | BorrowKind::Unique
466 .is_freeze(self.tcx.at(self.thir[arg].span), self.param_env) =>
468 self.requires_unsafe(expr.span, BorrowOfLayoutConstrainedField)
470 BorrowKind::Mut { .. } => {
471 self.requires_unsafe(expr.span, MutationOfLayoutConstrainedField)
473 BorrowKind::Shallow | BorrowKind::Shared | BorrowKind::Unique => {}
477 ExprKind::Let { expr: expr_id, .. } => {
478 let let_expr = &self.thir[expr_id];
479 if let ty::Adt(adt_def, _) = let_expr.ty.kind() {
480 if adt_def.is_union() {
481 self.requires_unsafe(expr.span, AccessToUnionField);
487 visit::walk_expr(self, expr);
491 #[derive(Clone, Copy)]
496 UnsafeBlock { span: Span, hir_id: hir::HirId, used: bool },
499 #[derive(Clone, Copy)]
501 /// The body is not unsafe.
503 /// The body is an unsafe function. The span points to
504 /// the signature of the function.
509 /// Returns whether the body is unsafe.
510 fn is_unsafe(&self) -> bool {
511 matches!(self, BodyUnsafety::Unsafe(_))
514 /// If the body is unsafe, returns the `Span` of its signature.
515 fn unsafe_fn_sig_span(self) -> Option<Span> {
517 BodyUnsafety::Unsafe(span) => Some(span),
518 BodyUnsafety::Safe => None,
523 #[derive(Clone, Copy, PartialEq)]
525 CallToUnsafeFunction,
527 InitializingTypeWith,
531 AssignToDroppingUnionField,
533 MutationOfLayoutConstrainedField,
534 BorrowOfLayoutConstrainedField,
541 pub fn description_and_note(&self) -> (&'static str, &'static str) {
543 CallToUnsafeFunction => (
544 "call to unsafe function",
545 "consult the function's documentation for information on how to avoid undefined \
548 UseOfInlineAssembly => (
549 "use of inline assembly",
550 "inline assembly is entirely unchecked and can cause undefined behavior",
552 InitializingTypeWith => (
553 "initializing type with `rustc_layout_scalar_valid_range` attr",
554 "initializing a layout restricted type's field with a value outside the valid \
555 range is undefined behavior",
557 UseOfMutableStatic => (
558 "use of mutable static",
559 "mutable statics can be mutated by multiple threads: aliasing violations or data \
560 races will cause undefined behavior",
562 UseOfExternStatic => (
563 "use of extern static",
564 "extern statics are not controlled by the Rust type system: invalid data, \
565 aliasing violations or data races will cause undefined behavior",
567 DerefOfRawPointer => (
568 "dereference of raw pointer",
569 "raw pointers may be null, dangling or unaligned; they can violate aliasing rules \
570 and cause data races: all of these are undefined behavior",
572 AssignToDroppingUnionField => (
573 "assignment to union field that might need dropping",
574 "the previous content of the field will be dropped, which causes undefined \
575 behavior if the field was not properly initialized",
577 AccessToUnionField => (
578 "access to union field",
579 "the field may not be properly initialized: using uninitialized data will cause \
582 MutationOfLayoutConstrainedField => (
583 "mutation of layout constrained field",
584 "mutating layout constrained fields cannot statically be checked for valid values",
586 BorrowOfLayoutConstrainedField => (
587 "borrow of layout constrained field with interior mutability",
588 "references to fields of layout constrained fields lose the constraints. Coupled \
589 with interior mutability, the field can be changed to invalid values",
591 CallToFunctionWith => (
592 "call to function with `#[target_feature]`",
593 "can only be called if the required target features are available",
599 pub fn check_unsafety<'tcx>(tcx: TyCtxt<'tcx>, def: ty::WithOptConstParam<LocalDefId>) {
600 // THIR unsafeck is gated under `-Z thir-unsafeck`
601 if !tcx.sess.opts.debugging_opts.thir_unsafeck {
605 // Closures are handled by their owner, if it has a body
606 if tcx.is_closure(def.did.to_def_id()) {
608 let owner = hir.enclosing_body_owner(hir.local_def_id_to_hir_id(def.did));
609 tcx.ensure().thir_check_unsafety(hir.local_def_id(owner));
613 let (thir, expr) = tcx.thir_body(def);
614 let thir = &thir.borrow();
615 // If `thir` is empty, a type error occured, skip this body.
616 if thir.exprs.is_empty() {
620 let hir_id = tcx.hir().local_def_id_to_hir_id(def.did);
621 let body_unsafety = tcx.hir().fn_sig_by_hir_id(hir_id).map_or(BodyUnsafety::Safe, |fn_sig| {
622 if fn_sig.header.unsafety == hir::Unsafety::Unsafe {
623 BodyUnsafety::Unsafe(fn_sig.span)
628 let body_target_features = &tcx.codegen_fn_attrs(def.did).target_features;
630 if body_unsafety.is_unsafe() { SafetyContext::UnsafeFn } else { SafetyContext::Safe };
631 let mut visitor = UnsafetyVisitor {
637 body_target_features,
638 assignment_info: None,
639 in_union_destructure: false,
640 param_env: tcx.param_env(def.did),
643 visitor.visit_expr(&thir[expr]);
646 crate fn thir_check_unsafety<'tcx>(tcx: TyCtxt<'tcx>, def_id: LocalDefId) {
647 if let Some(def) = ty::WithOptConstParam::try_lookup(def_id, tcx) {
648 tcx.thir_check_unsafety_for_const_arg(def)
650 check_unsafety(tcx, ty::WithOptConstParam::unknown(def_id))
654 crate fn thir_check_unsafety_for_const_arg<'tcx>(
656 (did, param_did): (LocalDefId, DefId),
658 check_unsafety(tcx, ty::WithOptConstParam { did, const_param_did: Some(param_did) })