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