1use std::borrow::Cow;
2use std::mem;
3use std::ops::Bound;
4
5use rustc_ast::AsmMacro;
6use rustc_data_structures::stack::ensure_sufficient_stack;
7use rustc_errors::DiagArgValue;
8use rustc_hir::def::DefKind;
9use rustc_hir::{self as hir, BindingMode, ByRef, HirId, Mutability};
10use rustc_middle::middle::codegen_fn_attrs::TargetFeature;
11use rustc_middle::mir::BorrowKind;
12use rustc_middle::span_bug;
13use rustc_middle::thir::visit::Visitor;
14use rustc_middle::thir::*;
15use rustc_middle::ty::print::with_no_trimmed_paths;
16use rustc_middle::ty::{self, Ty, TyCtxt};
17use rustc_session::lint::Level;
18use rustc_session::lint::builtin::{DEPRECATED_SAFE_2024, UNSAFE_OP_IN_UNSAFE_FN, UNUSED_UNSAFE};
19use rustc_span::def_id::{DefId, LocalDefId};
20use rustc_span::{Span, Symbol, sym};
21
22use crate::builder::ExprCategory;
23use crate::errors::*;
24
25struct UnsafetyVisitor<'a, 'tcx> {
26 tcx: TyCtxt<'tcx>,
27 thir: &'a Thir<'tcx>,
28 hir_context: HirId,
31 safety_context: SafetyContext,
34 body_target_features: &'tcx [TargetFeature],
37 assignment_info: Option<Ty<'tcx>>,
40 in_union_destructure: bool,
41 typing_env: ty::TypingEnv<'tcx>,
42 inside_adt: bool,
43 warnings: &'a mut Vec<UnusedUnsafeWarning>,
44
45 suggest_unsafe_block: bool,
48}
49
50impl<'tcx> UnsafetyVisitor<'_, 'tcx> {
51 fn in_safety_context(&mut self, safety_context: SafetyContext, f: impl FnOnce(&mut Self)) {
52 let prev_context = mem::replace(&mut self.safety_context, safety_context);
53
54 f(self);
55
56 let safety_context = mem::replace(&mut self.safety_context, prev_context);
57 if let SafetyContext::UnsafeBlock { used, span, hir_id, nested_used_blocks } =
58 safety_context
59 {
60 if !used {
61 self.warn_unused_unsafe(hir_id, span, None);
62
63 if let SafetyContext::UnsafeBlock {
64 nested_used_blocks: ref mut prev_nested_used_blocks,
65 ..
66 } = self.safety_context
67 {
68 prev_nested_used_blocks.extend(nested_used_blocks);
69 }
70 } else {
71 for block in nested_used_blocks {
72 self.warn_unused_unsafe(
73 block.hir_id,
74 block.span,
75 Some(UnusedUnsafeEnclosing::Block {
76 span: self.tcx.sess.source_map().guess_head_span(span),
77 }),
78 );
79 }
80
81 match self.safety_context {
82 SafetyContext::UnsafeBlock {
83 nested_used_blocks: ref mut prev_nested_used_blocks,
84 ..
85 } => {
86 prev_nested_used_blocks.push(NestedUsedBlock { hir_id, span });
87 }
88 _ => (),
89 }
90 }
91 }
92 }
93
94 fn emit_deprecated_safe_fn_call(&self, span: Span, kind: &UnsafeOpKind) -> bool {
95 match kind {
96 &UnsafeOpKind::CallToUnsafeFunction(Some(id))
99 if !span.at_least_rust_2024()
100 && let Some(attr) = self.tcx.get_attr(id, sym::rustc_deprecated_safe_2024) =>
101 {
102 let suggestion = attr
103 .meta_item_list()
104 .unwrap_or_default()
105 .into_iter()
106 .find(|item| item.has_name(sym::audit_that))
107 .map(|item| {
108 item.value_str().expect(
109 "`#[rustc_deprecated_safe_2024(audit_that)]` must have a string value",
110 )
111 });
112
113 let sm = self.tcx.sess.source_map();
114 let guarantee = suggestion
115 .as_ref()
116 .map(|suggestion| format!("that {}", suggestion))
117 .unwrap_or_else(|| String::from("its unsafe preconditions"));
118 let suggestion = suggestion
119 .and_then(|suggestion| {
120 sm.indentation_before(span).map(|indent| {
121 format!("{}// TODO: Audit that {}.\n", indent, suggestion) })
123 })
124 .unwrap_or_default();
125
126 self.tcx.emit_node_span_lint(
127 DEPRECATED_SAFE_2024,
128 self.hir_context,
129 span,
130 CallToDeprecatedSafeFnRequiresUnsafe {
131 span,
132 function: with_no_trimmed_paths!(self.tcx.def_path_str(id)),
133 guarantee,
134 sub: CallToDeprecatedSafeFnRequiresUnsafeSub {
135 start_of_line_suggestion: suggestion,
136 start_of_line: sm.span_extend_to_line(span).shrink_to_lo(),
137 left: span.shrink_to_lo(),
138 right: span.shrink_to_hi(),
139 },
140 },
141 );
142 true
143 }
144 _ => false,
145 }
146 }
147
148 fn requires_unsafe(&mut self, span: Span, kind: UnsafeOpKind) {
149 let unsafe_op_in_unsafe_fn_allowed = self.unsafe_op_in_unsafe_fn_allowed();
150 match self.safety_context {
151 SafetyContext::BuiltinUnsafeBlock => {}
152 SafetyContext::UnsafeBlock { ref mut used, .. } => {
153 *used = true;
158 }
159 SafetyContext::UnsafeFn if unsafe_op_in_unsafe_fn_allowed => {}
160 SafetyContext::UnsafeFn => {
161 let deprecated_safe_fn = self.emit_deprecated_safe_fn_call(span, &kind);
162 if !deprecated_safe_fn {
163 kind.emit_unsafe_op_in_unsafe_fn_lint(
165 self.tcx,
166 self.hir_context,
167 span,
168 self.suggest_unsafe_block,
169 );
170 self.suggest_unsafe_block = false;
171 }
172 }
173 SafetyContext::Safe => {
174 let deprecated_safe_fn = self.emit_deprecated_safe_fn_call(span, &kind);
175 if !deprecated_safe_fn {
176 kind.emit_requires_unsafe_err(
177 self.tcx,
178 span,
179 self.hir_context,
180 unsafe_op_in_unsafe_fn_allowed,
181 );
182 }
183 }
184 }
185 }
186
187 fn warn_unused_unsafe(
188 &mut self,
189 hir_id: HirId,
190 block_span: Span,
191 enclosing_unsafe: Option<UnusedUnsafeEnclosing>,
192 ) {
193 self.warnings.push(UnusedUnsafeWarning { hir_id, block_span, enclosing_unsafe });
194 }
195
196 fn unsafe_op_in_unsafe_fn_allowed(&self) -> bool {
198 self.tcx.lint_level_at_node(UNSAFE_OP_IN_UNSAFE_FN, self.hir_context).level == Level::Allow
199 }
200
201 fn visit_inner_body(&mut self, def: LocalDefId) {
203 if let Ok((inner_thir, expr)) = self.tcx.thir_body(def) {
204 self.tcx.ensure_done().mir_built(def);
206 let inner_thir = if self.tcx.sess.opts.unstable_opts.no_steal_thir {
207 &inner_thir.borrow()
208 } else {
209 &inner_thir.steal()
211 };
212 let hir_context = self.tcx.local_def_id_to_hir_id(def);
213 let safety_context = mem::replace(&mut self.safety_context, SafetyContext::Safe);
214 let mut inner_visitor = UnsafetyVisitor {
215 tcx: self.tcx,
216 thir: inner_thir,
217 hir_context,
218 safety_context,
219 body_target_features: self.body_target_features,
220 assignment_info: self.assignment_info,
221 in_union_destructure: false,
222 typing_env: self.typing_env,
223 inside_adt: false,
224 warnings: self.warnings,
225 suggest_unsafe_block: self.suggest_unsafe_block,
226 };
227 for param in &inner_thir.params {
229 if let Some(param_pat) = param.pat.as_deref() {
230 inner_visitor.visit_pat(param_pat);
231 }
232 }
233 inner_visitor.visit_expr(&inner_thir[expr]);
235 self.safety_context = inner_visitor.safety_context;
237 }
238 }
239}
240
241struct LayoutConstrainedPlaceVisitor<'a, 'tcx> {
243 found: bool,
244 thir: &'a Thir<'tcx>,
245 tcx: TyCtxt<'tcx>,
246}
247
248impl<'a, 'tcx> LayoutConstrainedPlaceVisitor<'a, 'tcx> {
249 fn new(thir: &'a Thir<'tcx>, tcx: TyCtxt<'tcx>) -> Self {
250 Self { found: false, thir, tcx }
251 }
252}
253
254impl<'a, 'tcx> Visitor<'a, 'tcx> for LayoutConstrainedPlaceVisitor<'a, 'tcx> {
255 fn thir(&self) -> &'a Thir<'tcx> {
256 self.thir
257 }
258
259 fn visit_expr(&mut self, expr: &'a Expr<'tcx>) {
260 match expr.kind {
261 ExprKind::Field { lhs, .. } => {
262 if let ty::Adt(adt_def, _) = self.thir[lhs].ty.kind() {
263 if (Bound::Unbounded, Bound::Unbounded)
264 != self.tcx.layout_scalar_valid_range(adt_def.did())
265 {
266 self.found = true;
267 }
268 }
269 visit::walk_expr(self, expr);
270 }
271
272 ExprKind::Deref { .. } => {}
276 ref kind if ExprCategory::of(kind).is_none_or(|cat| cat == ExprCategory::Place) => {
277 visit::walk_expr(self, expr);
278 }
279
280 _ => {}
281 }
282 }
283}
284
285impl<'a, 'tcx> Visitor<'a, 'tcx> for UnsafetyVisitor<'a, 'tcx> {
286 fn thir(&self) -> &'a Thir<'tcx> {
287 self.thir
288 }
289
290 fn visit_block(&mut self, block: &'a Block) {
291 match block.safety_mode {
292 BlockSafety::BuiltinUnsafe => {
295 self.in_safety_context(SafetyContext::BuiltinUnsafeBlock, |this| {
296 visit::walk_block(this, block)
297 });
298 }
299 BlockSafety::ExplicitUnsafe(hir_id) => {
300 let used = matches!(
301 self.tcx.lint_level_at_node(UNUSED_UNSAFE, hir_id).level,
302 Level::Allow
303 );
304 self.in_safety_context(
305 SafetyContext::UnsafeBlock {
306 span: block.span,
307 hir_id,
308 used,
309 nested_used_blocks: Vec::new(),
310 },
311 |this| visit::walk_block(this, block),
312 );
313 }
314 BlockSafety::Safe => {
315 visit::walk_block(self, block);
316 }
317 }
318 }
319
320 fn visit_pat(&mut self, pat: &'a Pat<'tcx>) {
321 if self.in_union_destructure {
322 match pat.kind {
323 PatKind::Missing => unreachable!(),
324 PatKind::Binding { .. }
326 | PatKind::Constant { .. }
328 | PatKind::Variant { .. }
329 | PatKind::Leaf { .. }
330 | PatKind::Deref { .. }
331 | PatKind::DerefPattern { .. }
332 | PatKind::Range { .. }
333 | PatKind::Slice { .. }
334 | PatKind::Array { .. }
335 | PatKind::Never => {
337 self.requires_unsafe(pat.span, AccessToUnionField);
338 return; }
340 PatKind::Wild |
342 PatKind::Or { .. } |
344 PatKind::ExpandedConstant { .. } |
345 PatKind::AscribeUserType { .. } |
346 PatKind::Error(_) => {}
347 }
348 };
349
350 match &pat.kind {
351 PatKind::Leaf { subpatterns, .. } => {
352 if let ty::Adt(adt_def, ..) = pat.ty.kind() {
353 for pat in subpatterns {
354 if adt_def.non_enum_variant().fields[pat.field].safety.is_unsafe() {
355 self.requires_unsafe(pat.pattern.span, UseOfUnsafeField);
356 }
357 }
358 if adt_def.is_union() {
359 let old_in_union_destructure =
360 std::mem::replace(&mut self.in_union_destructure, true);
361 visit::walk_pat(self, pat);
362 self.in_union_destructure = old_in_union_destructure;
363 } else if (Bound::Unbounded, Bound::Unbounded)
364 != self.tcx.layout_scalar_valid_range(adt_def.did())
365 {
366 let old_inside_adt = std::mem::replace(&mut self.inside_adt, true);
367 visit::walk_pat(self, pat);
368 self.inside_adt = old_inside_adt;
369 } else {
370 visit::walk_pat(self, pat);
371 }
372 } else {
373 visit::walk_pat(self, pat);
374 }
375 }
376 PatKind::Variant { adt_def, args: _, variant_index, subpatterns } => {
377 for pat in subpatterns {
378 let field = &pat.field;
379 if adt_def.variant(*variant_index).fields[*field].safety.is_unsafe() {
380 self.requires_unsafe(pat.pattern.span, UseOfUnsafeField);
381 }
382 }
383 visit::walk_pat(self, pat);
384 }
385 PatKind::Binding { mode: BindingMode(ByRef::Yes(rm), _), ty, .. } => {
386 if self.inside_adt {
387 let ty::Ref(_, ty, _) = ty.kind() else {
388 span_bug!(
389 pat.span,
390 "ByRef::Yes in pattern, but found non-reference type {}",
391 ty
392 );
393 };
394 match rm {
395 Mutability::Not => {
396 if !ty.is_freeze(self.tcx, self.typing_env) {
397 self.requires_unsafe(pat.span, BorrowOfLayoutConstrainedField);
398 }
399 }
400 Mutability::Mut { .. } => {
401 self.requires_unsafe(pat.span, MutationOfLayoutConstrainedField);
402 }
403 }
404 }
405 visit::walk_pat(self, pat);
406 }
407 PatKind::Deref { .. } | PatKind::DerefPattern { .. } => {
408 let old_inside_adt = std::mem::replace(&mut self.inside_adt, false);
409 visit::walk_pat(self, pat);
410 self.inside_adt = old_inside_adt;
411 }
412 PatKind::ExpandedConstant { def_id, .. } => {
413 if let Some(def) = def_id.as_local()
414 && matches!(self.tcx.def_kind(def_id), DefKind::InlineConst)
415 {
416 self.visit_inner_body(def);
417 }
418 visit::walk_pat(self, pat);
419 }
420 _ => {
421 visit::walk_pat(self, pat);
422 }
423 }
424 }
425
426 fn visit_expr(&mut self, expr: &'a Expr<'tcx>) {
427 match expr.kind {
429 ExprKind::Field { .. }
430 | ExprKind::VarRef { .. }
431 | ExprKind::UpvarRef { .. }
432 | ExprKind::Scope { .. }
433 | ExprKind::Cast { .. } => {}
434
435 ExprKind::RawBorrow { .. }
436 | ExprKind::Adt { .. }
437 | ExprKind::Array { .. }
438 | ExprKind::Binary { .. }
439 | ExprKind::Block { .. }
440 | ExprKind::Borrow { .. }
441 | ExprKind::Literal { .. }
442 | ExprKind::NamedConst { .. }
443 | ExprKind::NonHirLiteral { .. }
444 | ExprKind::ZstLiteral { .. }
445 | ExprKind::ConstParam { .. }
446 | ExprKind::ConstBlock { .. }
447 | ExprKind::Deref { .. }
448 | ExprKind::Index { .. }
449 | ExprKind::NeverToAny { .. }
450 | ExprKind::PlaceTypeAscription { .. }
451 | ExprKind::ValueTypeAscription { .. }
452 | ExprKind::PlaceUnwrapUnsafeBinder { .. }
453 | ExprKind::ValueUnwrapUnsafeBinder { .. }
454 | ExprKind::WrapUnsafeBinder { .. }
455 | ExprKind::PointerCoercion { .. }
456 | ExprKind::Repeat { .. }
457 | ExprKind::StaticRef { .. }
458 | ExprKind::ThreadLocalRef { .. }
459 | ExprKind::Tuple { .. }
460 | ExprKind::Unary { .. }
461 | ExprKind::Call { .. }
462 | ExprKind::ByUse { .. }
463 | ExprKind::Assign { .. }
464 | ExprKind::AssignOp { .. }
465 | ExprKind::Break { .. }
466 | ExprKind::Closure { .. }
467 | ExprKind::Continue { .. }
468 | ExprKind::Return { .. }
469 | ExprKind::Become { .. }
470 | ExprKind::Yield { .. }
471 | ExprKind::Loop { .. }
472 | ExprKind::Let { .. }
473 | ExprKind::Match { .. }
474 | ExprKind::Box { .. }
475 | ExprKind::If { .. }
476 | ExprKind::InlineAsm { .. }
477 | ExprKind::OffsetOf { .. }
478 | ExprKind::LogicalOp { .. }
479 | ExprKind::Use { .. } => {
480 self.assignment_info = None;
484 }
485 };
486 match expr.kind {
487 ExprKind::Scope { value, lint_level: LintLevel::Explicit(hir_id), region_scope: _ } => {
488 let prev_id = self.hir_context;
489 self.hir_context = hir_id;
490 ensure_sufficient_stack(|| {
491 self.visit_expr(&self.thir[value]);
492 });
493 self.hir_context = prev_id;
494 return; }
496 ExprKind::Call { fun, ty: _, args: _, from_hir_call: _, fn_span: _ } => {
497 let fn_ty = self.thir[fun].ty;
498 let sig = fn_ty.fn_sig(self.tcx);
499 let (callee_features, safe_target_features): (&[_], _) = match fn_ty.kind() {
500 ty::FnDef(func_id, ..) => {
501 let cg_attrs = self.tcx.codegen_fn_attrs(func_id);
502 (&cg_attrs.target_features, cg_attrs.safe_target_features)
503 }
504 _ => (&[], false),
505 };
506 if sig.safety().is_unsafe() && !safe_target_features {
507 let func_id = if let ty::FnDef(func_id, _) = fn_ty.kind() {
508 Some(*func_id)
509 } else {
510 None
511 };
512 self.requires_unsafe(expr.span, CallToUnsafeFunction(func_id));
513 } else if let &ty::FnDef(func_did, _) = fn_ty.kind() {
514 if !self
515 .tcx
516 .is_target_feature_call_safe(callee_features, self.body_target_features)
517 {
518 let missing: Vec<_> = callee_features
519 .iter()
520 .copied()
521 .filter(|feature| {
522 !feature.implied
523 && !self
524 .body_target_features
525 .iter()
526 .any(|body_feature| body_feature.name == feature.name)
527 })
528 .map(|feature| feature.name)
529 .collect();
530 let build_enabled = self
531 .tcx
532 .sess
533 .target_features
534 .iter()
535 .copied()
536 .filter(|feature| missing.contains(feature))
537 .collect();
538 self.requires_unsafe(
539 expr.span,
540 CallToFunctionWith { function: func_did, missing, build_enabled },
541 );
542 }
543 }
544 }
545 ExprKind::RawBorrow { arg, .. } => {
546 if let ExprKind::Scope { value: arg, .. } = self.thir[arg].kind
547 && let ExprKind::Deref { arg } = self.thir[arg].kind
548 {
549 visit::walk_expr(self, &self.thir[arg]);
552 return;
553 }
554 }
555 ExprKind::Deref { arg } => {
556 if let ExprKind::StaticRef { def_id, .. } | ExprKind::ThreadLocalRef(def_id) =
557 self.thir[arg].kind
558 {
559 if self.tcx.is_mutable_static(def_id) {
560 self.requires_unsafe(expr.span, UseOfMutableStatic);
561 } else if self.tcx.is_foreign_item(def_id) {
562 match self.tcx.def_kind(def_id) {
563 DefKind::Static { safety: hir::Safety::Safe, .. } => {}
564 _ => self.requires_unsafe(expr.span, UseOfExternStatic),
565 }
566 }
567 } else if self.thir[arg].ty.is_raw_ptr() {
568 self.requires_unsafe(expr.span, DerefOfRawPointer);
569 }
570 }
571 ExprKind::InlineAsm(box InlineAsmExpr {
572 asm_macro: asm_macro @ (AsmMacro::Asm | AsmMacro::NakedAsm),
573 ref operands,
574 template: _,
575 options: _,
576 line_spans: _,
577 }) => {
578 if let AsmMacro::Asm = asm_macro {
581 self.requires_unsafe(expr.span, UseOfInlineAssembly);
582 }
583
584 for op in &**operands {
587 use rustc_middle::thir::InlineAsmOperand::*;
588 match op {
589 In { expr, reg: _ }
590 | Out { expr: Some(expr), reg: _, late: _ }
591 | InOut { expr, reg: _, late: _ } => self.visit_expr(&self.thir()[*expr]),
592 SplitInOut { in_expr, out_expr, reg: _, late: _ } => {
593 self.visit_expr(&self.thir()[*in_expr]);
594 if let Some(out_expr) = out_expr {
595 self.visit_expr(&self.thir()[*out_expr]);
596 }
597 }
598 Out { expr: None, reg: _, late: _ }
599 | Const { value: _, span: _ }
600 | SymFn { value: _ }
601 | SymStatic { def_id: _ } => {}
602 Label { block } => {
603 self.in_safety_context(SafetyContext::Safe, |this| {
608 visit::walk_block(this, &this.thir()[*block])
609 });
610 }
611 }
612 }
613 return;
614 }
615 ExprKind::Adt(box AdtExpr {
616 adt_def,
617 variant_index,
618 args: _,
619 user_ty: _,
620 fields: _,
621 base: _,
622 }) => {
623 if adt_def.variant(variant_index).has_unsafe_fields() {
624 self.requires_unsafe(expr.span, InitializingTypeWithUnsafeField)
625 }
626 match self.tcx.layout_scalar_valid_range(adt_def.did()) {
627 (Bound::Unbounded, Bound::Unbounded) => {}
628 _ => self.requires_unsafe(expr.span, InitializingTypeWith),
629 }
630 }
631 ExprKind::Closure(box ClosureExpr {
632 closure_id,
633 args: _,
634 upvars: _,
635 movability: _,
636 fake_reads: _,
637 }) => {
638 self.visit_inner_body(closure_id);
639 }
640 ExprKind::ConstBlock { did, args: _ } => {
641 let def_id = did.expect_local();
642 self.visit_inner_body(def_id);
643 }
644 ExprKind::Field { lhs, variant_index, name } => {
645 let lhs = &self.thir[lhs];
646 if let ty::Adt(adt_def, _) = lhs.ty.kind() {
647 if adt_def.variant(variant_index).fields[name].safety.is_unsafe() {
648 self.requires_unsafe(expr.span, UseOfUnsafeField);
649 } else if adt_def.is_union() {
650 if let Some(assigned_ty) = self.assignment_info {
651 if assigned_ty.needs_drop(self.tcx, self.typing_env) {
652 assert!(
655 self.tcx.dcx().has_errors().is_some(),
656 "union fields that need dropping should be impossible: {assigned_ty}"
657 );
658 }
659 } else {
660 self.requires_unsafe(expr.span, AccessToUnionField);
661 }
662 }
663 }
664 }
665 ExprKind::Assign { lhs, rhs } | ExprKind::AssignOp { lhs, rhs, .. } => {
666 let lhs = &self.thir[lhs];
667 let mut visitor = LayoutConstrainedPlaceVisitor::new(self.thir, self.tcx);
669 visit::walk_expr(&mut visitor, lhs);
670 if visitor.found {
671 self.requires_unsafe(expr.span, MutationOfLayoutConstrainedField);
672 }
673
674 if matches!(expr.kind, ExprKind::Assign { .. }) {
678 self.assignment_info = Some(lhs.ty);
679 visit::walk_expr(self, lhs);
680 self.assignment_info = None;
681 visit::walk_expr(self, &self.thir()[rhs]);
682 return; }
684 }
685 ExprKind::Borrow { borrow_kind, arg } => {
686 let mut visitor = LayoutConstrainedPlaceVisitor::new(self.thir, self.tcx);
687 visit::walk_expr(&mut visitor, expr);
688 if visitor.found {
689 match borrow_kind {
690 BorrowKind::Fake(_) | BorrowKind::Shared
691 if !self.thir[arg].ty.is_freeze(self.tcx, self.typing_env) =>
692 {
693 self.requires_unsafe(expr.span, BorrowOfLayoutConstrainedField)
694 }
695 BorrowKind::Mut { .. } => {
696 self.requires_unsafe(expr.span, MutationOfLayoutConstrainedField)
697 }
698 BorrowKind::Fake(_) | BorrowKind::Shared => {}
699 }
700 }
701 }
702 ExprKind::PlaceUnwrapUnsafeBinder { .. }
703 | ExprKind::ValueUnwrapUnsafeBinder { .. }
704 | ExprKind::WrapUnsafeBinder { .. } => {
705 self.requires_unsafe(expr.span, UnsafeBinderCast);
706 }
707 _ => {}
708 }
709 visit::walk_expr(self, expr);
710 }
711}
712
713#[derive(Clone)]
714enum SafetyContext {
715 Safe,
716 BuiltinUnsafeBlock,
717 UnsafeFn,
718 UnsafeBlock { span: Span, hir_id: HirId, used: bool, nested_used_blocks: Vec<NestedUsedBlock> },
719}
720
721#[derive(Clone, Copy)]
722struct NestedUsedBlock {
723 hir_id: HirId,
724 span: Span,
725}
726
727struct UnusedUnsafeWarning {
728 hir_id: HirId,
729 block_span: Span,
730 enclosing_unsafe: Option<UnusedUnsafeEnclosing>,
731}
732
733#[derive(Clone, PartialEq)]
734enum UnsafeOpKind {
735 CallToUnsafeFunction(Option<DefId>),
736 UseOfInlineAssembly,
737 InitializingTypeWith,
738 InitializingTypeWithUnsafeField,
739 UseOfMutableStatic,
740 UseOfExternStatic,
741 UseOfUnsafeField,
742 DerefOfRawPointer,
743 AccessToUnionField,
744 MutationOfLayoutConstrainedField,
745 BorrowOfLayoutConstrainedField,
746 CallToFunctionWith {
747 function: DefId,
748 missing: Vec<Symbol>,
751 build_enabled: Vec<Symbol>,
754 },
755 UnsafeBinderCast,
756}
757
758use UnsafeOpKind::*;
759
760impl UnsafeOpKind {
761 fn emit_unsafe_op_in_unsafe_fn_lint(
762 &self,
763 tcx: TyCtxt<'_>,
764 hir_id: HirId,
765 span: Span,
766 suggest_unsafe_block: bool,
767 ) {
768 if tcx.hir_opt_delegation_sig_id(hir_id.owner.def_id).is_some() {
769 return;
772 }
773 let parent_id = tcx.hir_get_parent_item(hir_id);
774 let parent_owner = tcx.hir_owner_node(parent_id);
775 let should_suggest = parent_owner.fn_sig().is_some_and(|sig| {
776 matches!(sig.header.safety, hir::HeaderSafety::Normal(hir::Safety::Unsafe))
778 });
779 let unsafe_not_inherited_note = if should_suggest {
780 suggest_unsafe_block.then(|| {
781 let body_span = tcx.hir_body(parent_owner.body_id().unwrap()).value.span;
782 UnsafeNotInheritedLintNote {
783 signature_span: tcx.def_span(parent_id.def_id),
784 body_span,
785 }
786 })
787 } else {
788 None
789 };
790 match self {
793 CallToUnsafeFunction(Some(did)) => tcx.emit_node_span_lint(
794 UNSAFE_OP_IN_UNSAFE_FN,
795 hir_id,
796 span,
797 UnsafeOpInUnsafeFnCallToUnsafeFunctionRequiresUnsafe {
798 span,
799 function: with_no_trimmed_paths!(tcx.def_path_str(*did)),
800 unsafe_not_inherited_note,
801 },
802 ),
803 CallToUnsafeFunction(None) => tcx.emit_node_span_lint(
804 UNSAFE_OP_IN_UNSAFE_FN,
805 hir_id,
806 span,
807 UnsafeOpInUnsafeFnCallToUnsafeFunctionRequiresUnsafeNameless {
808 span,
809 unsafe_not_inherited_note,
810 },
811 ),
812 UseOfInlineAssembly => tcx.emit_node_span_lint(
813 UNSAFE_OP_IN_UNSAFE_FN,
814 hir_id,
815 span,
816 UnsafeOpInUnsafeFnUseOfInlineAssemblyRequiresUnsafe {
817 span,
818 unsafe_not_inherited_note,
819 },
820 ),
821 InitializingTypeWith => tcx.emit_node_span_lint(
822 UNSAFE_OP_IN_UNSAFE_FN,
823 hir_id,
824 span,
825 UnsafeOpInUnsafeFnInitializingTypeWithRequiresUnsafe {
826 span,
827 unsafe_not_inherited_note,
828 },
829 ),
830 InitializingTypeWithUnsafeField => tcx.emit_node_span_lint(
831 UNSAFE_OP_IN_UNSAFE_FN,
832 hir_id,
833 span,
834 UnsafeOpInUnsafeFnInitializingTypeWithUnsafeFieldRequiresUnsafe {
835 span,
836 unsafe_not_inherited_note,
837 },
838 ),
839 UseOfMutableStatic => tcx.emit_node_span_lint(
840 UNSAFE_OP_IN_UNSAFE_FN,
841 hir_id,
842 span,
843 UnsafeOpInUnsafeFnUseOfMutableStaticRequiresUnsafe {
844 span,
845 unsafe_not_inherited_note,
846 },
847 ),
848 UseOfExternStatic => tcx.emit_node_span_lint(
849 UNSAFE_OP_IN_UNSAFE_FN,
850 hir_id,
851 span,
852 UnsafeOpInUnsafeFnUseOfExternStaticRequiresUnsafe {
853 span,
854 unsafe_not_inherited_note,
855 },
856 ),
857 UseOfUnsafeField => tcx.emit_node_span_lint(
858 UNSAFE_OP_IN_UNSAFE_FN,
859 hir_id,
860 span,
861 UnsafeOpInUnsafeFnUseOfUnsafeFieldRequiresUnsafe {
862 span,
863 unsafe_not_inherited_note,
864 },
865 ),
866 DerefOfRawPointer => tcx.emit_node_span_lint(
867 UNSAFE_OP_IN_UNSAFE_FN,
868 hir_id,
869 span,
870 UnsafeOpInUnsafeFnDerefOfRawPointerRequiresUnsafe {
871 span,
872 unsafe_not_inherited_note,
873 },
874 ),
875 AccessToUnionField => tcx.emit_node_span_lint(
876 UNSAFE_OP_IN_UNSAFE_FN,
877 hir_id,
878 span,
879 UnsafeOpInUnsafeFnAccessToUnionFieldRequiresUnsafe {
880 span,
881 unsafe_not_inherited_note,
882 },
883 ),
884 MutationOfLayoutConstrainedField => tcx.emit_node_span_lint(
885 UNSAFE_OP_IN_UNSAFE_FN,
886 hir_id,
887 span,
888 UnsafeOpInUnsafeFnMutationOfLayoutConstrainedFieldRequiresUnsafe {
889 span,
890 unsafe_not_inherited_note,
891 },
892 ),
893 BorrowOfLayoutConstrainedField => tcx.emit_node_span_lint(
894 UNSAFE_OP_IN_UNSAFE_FN,
895 hir_id,
896 span,
897 UnsafeOpInUnsafeFnBorrowOfLayoutConstrainedFieldRequiresUnsafe {
898 span,
899 unsafe_not_inherited_note,
900 },
901 ),
902 CallToFunctionWith { function, missing, build_enabled } => tcx.emit_node_span_lint(
903 UNSAFE_OP_IN_UNSAFE_FN,
904 hir_id,
905 span,
906 UnsafeOpInUnsafeFnCallToFunctionWithRequiresUnsafe {
907 span,
908 function: with_no_trimmed_paths!(tcx.def_path_str(*function)),
909 missing_target_features: DiagArgValue::StrListSepByAnd(
910 missing.iter().map(|feature| Cow::from(feature.to_string())).collect(),
911 ),
912 missing_target_features_count: missing.len(),
913 note: !build_enabled.is_empty(),
914 build_target_features: DiagArgValue::StrListSepByAnd(
915 build_enabled
916 .iter()
917 .map(|feature| Cow::from(feature.to_string()))
918 .collect(),
919 ),
920 build_target_features_count: build_enabled.len(),
921 unsafe_not_inherited_note,
922 },
923 ),
924 UnsafeBinderCast => tcx.emit_node_span_lint(
925 UNSAFE_OP_IN_UNSAFE_FN,
926 hir_id,
927 span,
928 UnsafeOpInUnsafeFnUnsafeBinderCastRequiresUnsafe {
929 span,
930 unsafe_not_inherited_note,
931 },
932 ),
933 }
934 }
935
936 fn emit_requires_unsafe_err(
937 &self,
938 tcx: TyCtxt<'_>,
939 span: Span,
940 hir_context: HirId,
941 unsafe_op_in_unsafe_fn_allowed: bool,
942 ) {
943 let note_non_inherited = tcx.hir_parent_iter(hir_context).find(|(id, node)| {
944 if let hir::Node::Expr(block) = node
945 && let hir::ExprKind::Block(block, _) = block.kind
946 && let hir::BlockCheckMode::UnsafeBlock(_) = block.rules
947 {
948 true
949 } else if let Some(sig) = tcx.hir_fn_sig_by_hir_id(*id)
950 && matches!(sig.header.safety, hir::HeaderSafety::Normal(hir::Safety::Unsafe))
951 {
952 true
953 } else {
954 false
955 }
956 });
957 let unsafe_not_inherited_note = if let Some((id, _)) = note_non_inherited {
958 let span = tcx.hir_span(id);
959 let span = tcx.sess.source_map().guess_head_span(span);
960 Some(UnsafeNotInheritedNote { span })
961 } else {
962 None
963 };
964
965 let dcx = tcx.dcx();
966 match self {
967 CallToUnsafeFunction(Some(did)) if unsafe_op_in_unsafe_fn_allowed => {
968 dcx.emit_err(CallToUnsafeFunctionRequiresUnsafeUnsafeOpInUnsafeFnAllowed {
969 span,
970 unsafe_not_inherited_note,
971 function: tcx.def_path_str(*did),
972 });
973 }
974 CallToUnsafeFunction(Some(did)) => {
975 dcx.emit_err(CallToUnsafeFunctionRequiresUnsafe {
976 span,
977 unsafe_not_inherited_note,
978 function: tcx.def_path_str(*did),
979 });
980 }
981 CallToUnsafeFunction(None) if unsafe_op_in_unsafe_fn_allowed => {
982 dcx.emit_err(CallToUnsafeFunctionRequiresUnsafeNamelessUnsafeOpInUnsafeFnAllowed {
983 span,
984 unsafe_not_inherited_note,
985 });
986 }
987 CallToUnsafeFunction(None) => {
988 dcx.emit_err(CallToUnsafeFunctionRequiresUnsafeNameless {
989 span,
990 unsafe_not_inherited_note,
991 });
992 }
993 UseOfInlineAssembly if unsafe_op_in_unsafe_fn_allowed => {
994 dcx.emit_err(UseOfInlineAssemblyRequiresUnsafeUnsafeOpInUnsafeFnAllowed {
995 span,
996 unsafe_not_inherited_note,
997 });
998 }
999 UseOfInlineAssembly => {
1000 dcx.emit_err(UseOfInlineAssemblyRequiresUnsafe { span, unsafe_not_inherited_note });
1001 }
1002 InitializingTypeWith if unsafe_op_in_unsafe_fn_allowed => {
1003 dcx.emit_err(InitializingTypeWithRequiresUnsafeUnsafeOpInUnsafeFnAllowed {
1004 span,
1005 unsafe_not_inherited_note,
1006 });
1007 }
1008 InitializingTypeWith => {
1009 dcx.emit_err(InitializingTypeWithRequiresUnsafe {
1010 span,
1011 unsafe_not_inherited_note,
1012 });
1013 }
1014 InitializingTypeWithUnsafeField if unsafe_op_in_unsafe_fn_allowed => {
1015 dcx.emit_err(
1016 InitializingTypeWithUnsafeFieldRequiresUnsafeUnsafeOpInUnsafeFnAllowed {
1017 span,
1018 unsafe_not_inherited_note,
1019 },
1020 );
1021 }
1022 InitializingTypeWithUnsafeField => {
1023 dcx.emit_err(InitializingTypeWithUnsafeFieldRequiresUnsafe {
1024 span,
1025 unsafe_not_inherited_note,
1026 });
1027 }
1028 UseOfMutableStatic if unsafe_op_in_unsafe_fn_allowed => {
1029 dcx.emit_err(UseOfMutableStaticRequiresUnsafeUnsafeOpInUnsafeFnAllowed {
1030 span,
1031 unsafe_not_inherited_note,
1032 });
1033 }
1034 UseOfMutableStatic => {
1035 dcx.emit_err(UseOfMutableStaticRequiresUnsafe { span, unsafe_not_inherited_note });
1036 }
1037 UseOfExternStatic if unsafe_op_in_unsafe_fn_allowed => {
1038 dcx.emit_err(UseOfExternStaticRequiresUnsafeUnsafeOpInUnsafeFnAllowed {
1039 span,
1040 unsafe_not_inherited_note,
1041 });
1042 }
1043 UseOfExternStatic => {
1044 dcx.emit_err(UseOfExternStaticRequiresUnsafe { span, unsafe_not_inherited_note });
1045 }
1046 UseOfUnsafeField if unsafe_op_in_unsafe_fn_allowed => {
1047 dcx.emit_err(UseOfUnsafeFieldRequiresUnsafeUnsafeOpInUnsafeFnAllowed {
1048 span,
1049 unsafe_not_inherited_note,
1050 });
1051 }
1052 UseOfUnsafeField => {
1053 dcx.emit_err(UseOfUnsafeFieldRequiresUnsafe { span, unsafe_not_inherited_note });
1054 }
1055 DerefOfRawPointer if unsafe_op_in_unsafe_fn_allowed => {
1056 dcx.emit_err(DerefOfRawPointerRequiresUnsafeUnsafeOpInUnsafeFnAllowed {
1057 span,
1058 unsafe_not_inherited_note,
1059 });
1060 }
1061 DerefOfRawPointer => {
1062 dcx.emit_err(DerefOfRawPointerRequiresUnsafe { span, unsafe_not_inherited_note });
1063 }
1064 AccessToUnionField if unsafe_op_in_unsafe_fn_allowed => {
1065 dcx.emit_err(AccessToUnionFieldRequiresUnsafeUnsafeOpInUnsafeFnAllowed {
1066 span,
1067 unsafe_not_inherited_note,
1068 });
1069 }
1070 AccessToUnionField => {
1071 dcx.emit_err(AccessToUnionFieldRequiresUnsafe { span, unsafe_not_inherited_note });
1072 }
1073 MutationOfLayoutConstrainedField if unsafe_op_in_unsafe_fn_allowed => {
1074 dcx.emit_err(
1075 MutationOfLayoutConstrainedFieldRequiresUnsafeUnsafeOpInUnsafeFnAllowed {
1076 span,
1077 unsafe_not_inherited_note,
1078 },
1079 );
1080 }
1081 MutationOfLayoutConstrainedField => {
1082 dcx.emit_err(MutationOfLayoutConstrainedFieldRequiresUnsafe {
1083 span,
1084 unsafe_not_inherited_note,
1085 });
1086 }
1087 BorrowOfLayoutConstrainedField if unsafe_op_in_unsafe_fn_allowed => {
1088 dcx.emit_err(
1089 BorrowOfLayoutConstrainedFieldRequiresUnsafeUnsafeOpInUnsafeFnAllowed {
1090 span,
1091 unsafe_not_inherited_note,
1092 },
1093 );
1094 }
1095 BorrowOfLayoutConstrainedField => {
1096 dcx.emit_err(BorrowOfLayoutConstrainedFieldRequiresUnsafe {
1097 span,
1098 unsafe_not_inherited_note,
1099 });
1100 }
1101 CallToFunctionWith { function, missing, build_enabled }
1102 if unsafe_op_in_unsafe_fn_allowed =>
1103 {
1104 dcx.emit_err(CallToFunctionWithRequiresUnsafeUnsafeOpInUnsafeFnAllowed {
1105 span,
1106 missing_target_features: DiagArgValue::StrListSepByAnd(
1107 missing.iter().map(|feature| Cow::from(feature.to_string())).collect(),
1108 ),
1109 missing_target_features_count: missing.len(),
1110 note: !build_enabled.is_empty(),
1111 build_target_features: DiagArgValue::StrListSepByAnd(
1112 build_enabled
1113 .iter()
1114 .map(|feature| Cow::from(feature.to_string()))
1115 .collect(),
1116 ),
1117 build_target_features_count: build_enabled.len(),
1118 unsafe_not_inherited_note,
1119 function: tcx.def_path_str(*function),
1120 });
1121 }
1122 CallToFunctionWith { function, missing, build_enabled } => {
1123 dcx.emit_err(CallToFunctionWithRequiresUnsafe {
1124 span,
1125 missing_target_features: DiagArgValue::StrListSepByAnd(
1126 missing.iter().map(|feature| Cow::from(feature.to_string())).collect(),
1127 ),
1128 missing_target_features_count: missing.len(),
1129 note: !build_enabled.is_empty(),
1130 build_target_features: DiagArgValue::StrListSepByAnd(
1131 build_enabled
1132 .iter()
1133 .map(|feature| Cow::from(feature.to_string()))
1134 .collect(),
1135 ),
1136 build_target_features_count: build_enabled.len(),
1137 unsafe_not_inherited_note,
1138 function: tcx.def_path_str(*function),
1139 });
1140 }
1141 UnsafeBinderCast if unsafe_op_in_unsafe_fn_allowed => {
1142 dcx.emit_err(UnsafeBinderCastRequiresUnsafeUnsafeOpInUnsafeFnAllowed {
1143 span,
1144 unsafe_not_inherited_note,
1145 });
1146 }
1147 UnsafeBinderCast => {
1148 dcx.emit_err(UnsafeBinderCastRequiresUnsafe { span, unsafe_not_inherited_note });
1149 }
1150 }
1151 }
1152}
1153
1154pub(crate) fn check_unsafety(tcx: TyCtxt<'_>, def: LocalDefId) {
1155 assert!(!tcx.is_typeck_child(def.to_def_id()));
1157 if tcx.has_attr(def, sym::custom_mir) {
1159 return;
1160 }
1161
1162 let Ok((thir, expr)) = tcx.thir_body(def) else { return };
1163 tcx.ensure_done().mir_built(def);
1165 let thir = if tcx.sess.opts.unstable_opts.no_steal_thir {
1166 &thir.borrow()
1167 } else {
1168 &thir.steal()
1170 };
1171
1172 let hir_id = tcx.local_def_id_to_hir_id(def);
1173 let safety_context = tcx.hir_fn_sig_by_hir_id(hir_id).map_or(SafetyContext::Safe, |fn_sig| {
1174 match fn_sig.header.safety {
1175 hir::HeaderSafety::SafeTargetFeatures => SafetyContext::Safe,
1179 hir::HeaderSafety::Normal(safety) => match safety {
1180 hir::Safety::Unsafe => SafetyContext::UnsafeFn,
1181 hir::Safety::Safe => SafetyContext::Safe,
1182 },
1183 }
1184 });
1185 let body_target_features = &tcx.body_codegen_attrs(def.to_def_id()).target_features;
1186 let mut warnings = Vec::new();
1187 let mut visitor = UnsafetyVisitor {
1188 tcx,
1189 thir,
1190 safety_context,
1191 hir_context: hir_id,
1192 body_target_features,
1193 assignment_info: None,
1194 in_union_destructure: false,
1195 typing_env: ty::TypingEnv::non_body_analysis(tcx, def),
1197 inside_adt: false,
1198 warnings: &mut warnings,
1199 suggest_unsafe_block: true,
1200 };
1201 for param in &thir.params {
1203 if let Some(param_pat) = param.pat.as_deref() {
1204 visitor.visit_pat(param_pat);
1205 }
1206 }
1207 visitor.visit_expr(&thir[expr]);
1209
1210 warnings.sort_by_key(|w| w.block_span);
1211 for UnusedUnsafeWarning { hir_id, block_span, enclosing_unsafe } in warnings {
1212 let block_span = tcx.sess.source_map().guess_head_span(block_span);
1213 tcx.emit_node_span_lint(
1214 UNUSED_UNSAFE,
1215 hir_id,
1216 block_span,
1217 UnusedUnsafe { span: block_span, enclosing: enclosing_unsafe },
1218 );
1219 }
1220}