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).0 == 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 = &inner_thir.steal();
207 let hir_context = self.tcx.local_def_id_to_hir_id(def);
208 let safety_context = mem::replace(&mut self.safety_context, SafetyContext::Safe);
209 let mut inner_visitor = UnsafetyVisitor {
210 tcx: self.tcx,
211 thir: inner_thir,
212 hir_context,
213 safety_context,
214 body_target_features: self.body_target_features,
215 assignment_info: self.assignment_info,
216 in_union_destructure: false,
217 typing_env: self.typing_env,
218 inside_adt: false,
219 warnings: self.warnings,
220 suggest_unsafe_block: self.suggest_unsafe_block,
221 };
222 for param in &inner_thir.params {
224 if let Some(param_pat) = param.pat.as_deref() {
225 inner_visitor.visit_pat(param_pat);
226 }
227 }
228 inner_visitor.visit_expr(&inner_thir[expr]);
230 self.safety_context = inner_visitor.safety_context;
232 }
233 }
234}
235
236struct LayoutConstrainedPlaceVisitor<'a, 'tcx> {
238 found: bool,
239 thir: &'a Thir<'tcx>,
240 tcx: TyCtxt<'tcx>,
241}
242
243impl<'a, 'tcx> LayoutConstrainedPlaceVisitor<'a, 'tcx> {
244 fn new(thir: &'a Thir<'tcx>, tcx: TyCtxt<'tcx>) -> Self {
245 Self { found: false, thir, tcx }
246 }
247}
248
249impl<'a, 'tcx> Visitor<'a, 'tcx> for LayoutConstrainedPlaceVisitor<'a, 'tcx> {
250 fn thir(&self) -> &'a Thir<'tcx> {
251 self.thir
252 }
253
254 fn visit_expr(&mut self, expr: &'a Expr<'tcx>) {
255 match expr.kind {
256 ExprKind::Field { lhs, .. } => {
257 if let ty::Adt(adt_def, _) = self.thir[lhs].ty.kind() {
258 if (Bound::Unbounded, Bound::Unbounded)
259 != self.tcx.layout_scalar_valid_range(adt_def.did())
260 {
261 self.found = true;
262 }
263 }
264 visit::walk_expr(self, expr);
265 }
266
267 ExprKind::Deref { .. } => {}
271 ref kind if ExprCategory::of(kind).is_none_or(|cat| cat == ExprCategory::Place) => {
272 visit::walk_expr(self, expr);
273 }
274
275 _ => {}
276 }
277 }
278}
279
280impl<'a, 'tcx> Visitor<'a, 'tcx> for UnsafetyVisitor<'a, 'tcx> {
281 fn thir(&self) -> &'a Thir<'tcx> {
282 self.thir
283 }
284
285 fn visit_block(&mut self, block: &'a Block) {
286 match block.safety_mode {
287 BlockSafety::BuiltinUnsafe => {
290 self.in_safety_context(SafetyContext::BuiltinUnsafeBlock, |this| {
291 visit::walk_block(this, block)
292 });
293 }
294 BlockSafety::ExplicitUnsafe(hir_id) => {
295 let used =
296 matches!(self.tcx.lint_level_at_node(UNUSED_UNSAFE, hir_id), (Level::Allow, _));
297 self.in_safety_context(
298 SafetyContext::UnsafeBlock {
299 span: block.span,
300 hir_id,
301 used,
302 nested_used_blocks: Vec::new(),
303 },
304 |this| visit::walk_block(this, block),
305 );
306 }
307 BlockSafety::Safe => {
308 visit::walk_block(self, block);
309 }
310 }
311 }
312
313 fn visit_pat(&mut self, pat: &'a Pat<'tcx>) {
314 if self.in_union_destructure {
315 match pat.kind {
316 PatKind::Binding { .. }
318 | PatKind::Constant { .. }
320 | PatKind::Variant { .. }
321 | PatKind::Leaf { .. }
322 | PatKind::Deref { .. }
323 | PatKind::DerefPattern { .. }
324 | PatKind::Range { .. }
325 | PatKind::Slice { .. }
326 | PatKind::Array { .. }
327 | PatKind::Never => {
329 self.requires_unsafe(pat.span, AccessToUnionField);
330 return; }
332 PatKind::Wild |
334 PatKind::Or { .. } |
336 PatKind::ExpandedConstant { .. } |
337 PatKind::AscribeUserType { .. } |
338 PatKind::Error(_) => {}
339 }
340 };
341
342 match &pat.kind {
343 PatKind::Leaf { subpatterns, .. } => {
344 if let ty::Adt(adt_def, ..) = pat.ty.kind() {
345 for pat in subpatterns {
346 if adt_def.non_enum_variant().fields[pat.field].safety.is_unsafe() {
347 self.requires_unsafe(pat.pattern.span, UseOfUnsafeField);
348 }
349 }
350 if adt_def.is_union() {
351 let old_in_union_destructure =
352 std::mem::replace(&mut self.in_union_destructure, true);
353 visit::walk_pat(self, pat);
354 self.in_union_destructure = old_in_union_destructure;
355 } else if (Bound::Unbounded, Bound::Unbounded)
356 != self.tcx.layout_scalar_valid_range(adt_def.did())
357 {
358 let old_inside_adt = std::mem::replace(&mut self.inside_adt, true);
359 visit::walk_pat(self, pat);
360 self.inside_adt = old_inside_adt;
361 } else {
362 visit::walk_pat(self, pat);
363 }
364 } else {
365 visit::walk_pat(self, pat);
366 }
367 }
368 PatKind::Variant { adt_def, args: _, variant_index, subpatterns } => {
369 for pat in subpatterns {
370 let field = &pat.field;
371 if adt_def.variant(*variant_index).fields[*field].safety.is_unsafe() {
372 self.requires_unsafe(pat.pattern.span, UseOfUnsafeField);
373 }
374 }
375 visit::walk_pat(self, pat);
376 }
377 PatKind::Binding { mode: BindingMode(ByRef::Yes(rm), _), ty, .. } => {
378 if self.inside_adt {
379 let ty::Ref(_, ty, _) = ty.kind() else {
380 span_bug!(
381 pat.span,
382 "ByRef::Yes in pattern, but found non-reference type {}",
383 ty
384 );
385 };
386 match rm {
387 Mutability::Not => {
388 if !ty.is_freeze(self.tcx, self.typing_env) {
389 self.requires_unsafe(pat.span, BorrowOfLayoutConstrainedField);
390 }
391 }
392 Mutability::Mut { .. } => {
393 self.requires_unsafe(pat.span, MutationOfLayoutConstrainedField);
394 }
395 }
396 }
397 visit::walk_pat(self, pat);
398 }
399 PatKind::Deref { .. } | PatKind::DerefPattern { .. } => {
400 let old_inside_adt = std::mem::replace(&mut self.inside_adt, false);
401 visit::walk_pat(self, pat);
402 self.inside_adt = old_inside_adt;
403 }
404 PatKind::ExpandedConstant { def_id, is_inline, .. } => {
405 if let Some(def) = def_id.as_local()
406 && *is_inline
407 {
408 self.visit_inner_body(def);
409 }
410 visit::walk_pat(self, pat);
411 }
412 _ => {
413 visit::walk_pat(self, pat);
414 }
415 }
416 }
417
418 fn visit_expr(&mut self, expr: &'a Expr<'tcx>) {
419 match expr.kind {
421 ExprKind::Field { .. }
422 | ExprKind::VarRef { .. }
423 | ExprKind::UpvarRef { .. }
424 | ExprKind::Scope { .. }
425 | ExprKind::Cast { .. } => {}
426
427 ExprKind::RawBorrow { .. }
428 | ExprKind::Adt { .. }
429 | ExprKind::Array { .. }
430 | ExprKind::Binary { .. }
431 | ExprKind::Block { .. }
432 | ExprKind::Borrow { .. }
433 | ExprKind::Literal { .. }
434 | ExprKind::NamedConst { .. }
435 | ExprKind::NonHirLiteral { .. }
436 | ExprKind::ZstLiteral { .. }
437 | ExprKind::ConstParam { .. }
438 | ExprKind::ConstBlock { .. }
439 | ExprKind::Deref { .. }
440 | ExprKind::Index { .. }
441 | ExprKind::NeverToAny { .. }
442 | ExprKind::PlaceTypeAscription { .. }
443 | ExprKind::ValueTypeAscription { .. }
444 | ExprKind::PlaceUnwrapUnsafeBinder { .. }
445 | ExprKind::ValueUnwrapUnsafeBinder { .. }
446 | ExprKind::WrapUnsafeBinder { .. }
447 | ExprKind::PointerCoercion { .. }
448 | ExprKind::Repeat { .. }
449 | ExprKind::StaticRef { .. }
450 | ExprKind::ThreadLocalRef { .. }
451 | ExprKind::Tuple { .. }
452 | ExprKind::Unary { .. }
453 | ExprKind::Call { .. }
454 | ExprKind::ByUse { .. }
455 | ExprKind::Assign { .. }
456 | ExprKind::AssignOp { .. }
457 | ExprKind::Break { .. }
458 | ExprKind::Closure { .. }
459 | ExprKind::Continue { .. }
460 | ExprKind::Return { .. }
461 | ExprKind::Become { .. }
462 | ExprKind::Yield { .. }
463 | ExprKind::Loop { .. }
464 | ExprKind::Let { .. }
465 | ExprKind::Match { .. }
466 | ExprKind::Box { .. }
467 | ExprKind::If { .. }
468 | ExprKind::InlineAsm { .. }
469 | ExprKind::OffsetOf { .. }
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.implied
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 ExprKind::Deref { arg } => {
548 if let ExprKind::StaticRef { def_id, .. } | ExprKind::ThreadLocalRef(def_id) =
549 self.thir[arg].kind
550 {
551 if self.tcx.is_mutable_static(def_id) {
552 self.requires_unsafe(expr.span, UseOfMutableStatic);
553 } else if self.tcx.is_foreign_item(def_id) {
554 match self.tcx.def_kind(def_id) {
555 DefKind::Static { safety: hir::Safety::Safe, .. } => {}
556 _ => self.requires_unsafe(expr.span, UseOfExternStatic),
557 }
558 }
559 } else if self.thir[arg].ty.is_raw_ptr() {
560 self.requires_unsafe(expr.span, DerefOfRawPointer);
561 }
562 }
563 ExprKind::InlineAsm(box InlineAsmExpr {
564 asm_macro: AsmMacro::Asm | AsmMacro::NakedAsm,
565 ref operands,
566 template: _,
567 options: _,
568 line_spans: _,
569 }) => {
570 self.requires_unsafe(expr.span, UseOfInlineAssembly);
571
572 for op in &**operands {
575 use rustc_middle::thir::InlineAsmOperand::*;
576 match op {
577 In { expr, reg: _ }
578 | Out { expr: Some(expr), reg: _, late: _ }
579 | InOut { expr, reg: _, late: _ } => self.visit_expr(&self.thir()[*expr]),
580 SplitInOut { in_expr, out_expr, reg: _, late: _ } => {
581 self.visit_expr(&self.thir()[*in_expr]);
582 if let Some(out_expr) = out_expr {
583 self.visit_expr(&self.thir()[*out_expr]);
584 }
585 }
586 Out { expr: None, reg: _, late: _ }
587 | Const { value: _, span: _ }
588 | SymFn { value: _ }
589 | SymStatic { def_id: _ } => {}
590 Label { block } => {
591 self.in_safety_context(SafetyContext::Safe, |this| {
596 visit::walk_block(this, &this.thir()[*block])
597 });
598 }
599 }
600 }
601 return;
602 }
603 ExprKind::Adt(box AdtExpr {
604 adt_def,
605 variant_index,
606 args: _,
607 user_ty: _,
608 fields: _,
609 base: _,
610 }) => {
611 if adt_def.variant(variant_index).has_unsafe_fields() {
612 self.requires_unsafe(expr.span, InitializingTypeWithUnsafeField)
613 }
614 match self.tcx.layout_scalar_valid_range(adt_def.did()) {
615 (Bound::Unbounded, Bound::Unbounded) => {}
616 _ => self.requires_unsafe(expr.span, InitializingTypeWith),
617 }
618 }
619 ExprKind::Closure(box ClosureExpr {
620 closure_id,
621 args: _,
622 upvars: _,
623 movability: _,
624 fake_reads: _,
625 }) => {
626 self.visit_inner_body(closure_id);
627 }
628 ExprKind::ConstBlock { did, args: _ } => {
629 let def_id = did.expect_local();
630 self.visit_inner_body(def_id);
631 }
632 ExprKind::Field { lhs, variant_index, name } => {
633 let lhs = &self.thir[lhs];
634 if let ty::Adt(adt_def, _) = lhs.ty.kind() {
635 if adt_def.variant(variant_index).fields[name].safety.is_unsafe() {
636 self.requires_unsafe(expr.span, UseOfUnsafeField);
637 } else if adt_def.is_union() {
638 if let Some(assigned_ty) = self.assignment_info {
639 if assigned_ty.needs_drop(self.tcx, self.typing_env) {
640 assert!(
643 self.tcx.dcx().has_errors().is_some(),
644 "union fields that need dropping should be impossible: {assigned_ty}"
645 );
646 }
647 } else {
648 self.requires_unsafe(expr.span, AccessToUnionField);
649 }
650 }
651 }
652 }
653 ExprKind::Assign { lhs, rhs } | ExprKind::AssignOp { lhs, rhs, .. } => {
654 let lhs = &self.thir[lhs];
655 let mut visitor = LayoutConstrainedPlaceVisitor::new(self.thir, self.tcx);
657 visit::walk_expr(&mut visitor, lhs);
658 if visitor.found {
659 self.requires_unsafe(expr.span, MutationOfLayoutConstrainedField);
660 }
661
662 if matches!(expr.kind, ExprKind::Assign { .. }) {
666 self.assignment_info = Some(lhs.ty);
667 visit::walk_expr(self, lhs);
668 self.assignment_info = None;
669 visit::walk_expr(self, &self.thir()[rhs]);
670 return; }
672 }
673 ExprKind::Borrow { borrow_kind, arg } => {
674 let mut visitor = LayoutConstrainedPlaceVisitor::new(self.thir, self.tcx);
675 visit::walk_expr(&mut visitor, expr);
676 if visitor.found {
677 match borrow_kind {
678 BorrowKind::Fake(_) | BorrowKind::Shared
679 if !self.thir[arg].ty.is_freeze(self.tcx, self.typing_env) =>
680 {
681 self.requires_unsafe(expr.span, BorrowOfLayoutConstrainedField)
682 }
683 BorrowKind::Mut { .. } => {
684 self.requires_unsafe(expr.span, MutationOfLayoutConstrainedField)
685 }
686 BorrowKind::Fake(_) | BorrowKind::Shared => {}
687 }
688 }
689 }
690 ExprKind::PlaceUnwrapUnsafeBinder { .. }
691 | ExprKind::ValueUnwrapUnsafeBinder { .. }
692 | ExprKind::WrapUnsafeBinder { .. } => {
693 self.requires_unsafe(expr.span, UnsafeBinderCast);
694 }
695 _ => {}
696 }
697 visit::walk_expr(self, expr);
698 }
699}
700
701#[derive(Clone)]
702enum SafetyContext {
703 Safe,
704 BuiltinUnsafeBlock,
705 UnsafeFn,
706 UnsafeBlock { span: Span, hir_id: HirId, used: bool, nested_used_blocks: Vec<NestedUsedBlock> },
707}
708
709#[derive(Clone, Copy)]
710struct NestedUsedBlock {
711 hir_id: HirId,
712 span: Span,
713}
714
715struct UnusedUnsafeWarning {
716 hir_id: HirId,
717 block_span: Span,
718 enclosing_unsafe: Option<UnusedUnsafeEnclosing>,
719}
720
721#[derive(Clone, PartialEq)]
722enum UnsafeOpKind {
723 CallToUnsafeFunction(Option<DefId>),
724 UseOfInlineAssembly,
725 InitializingTypeWith,
726 InitializingTypeWithUnsafeField,
727 UseOfMutableStatic,
728 UseOfExternStatic,
729 UseOfUnsafeField,
730 DerefOfRawPointer,
731 AccessToUnionField,
732 MutationOfLayoutConstrainedField,
733 BorrowOfLayoutConstrainedField,
734 CallToFunctionWith {
735 function: DefId,
736 missing: Vec<Symbol>,
739 build_enabled: Vec<Symbol>,
742 },
743 UnsafeBinderCast,
744}
745
746use UnsafeOpKind::*;
747
748impl UnsafeOpKind {
749 fn emit_unsafe_op_in_unsafe_fn_lint(
750 &self,
751 tcx: TyCtxt<'_>,
752 hir_id: HirId,
753 span: Span,
754 suggest_unsafe_block: bool,
755 ) {
756 if tcx.hir_opt_delegation_sig_id(hir_id.owner.def_id).is_some() {
757 return;
760 }
761 let parent_id = tcx.hir_get_parent_item(hir_id);
762 let parent_owner = tcx.hir_owner_node(parent_id);
763 let should_suggest = parent_owner.fn_sig().is_some_and(|sig| {
764 matches!(sig.header.safety, hir::HeaderSafety::Normal(hir::Safety::Unsafe))
766 });
767 let unsafe_not_inherited_note = if should_suggest {
768 suggest_unsafe_block.then(|| {
769 let body_span = tcx.hir_body(parent_owner.body_id().unwrap()).value.span;
770 UnsafeNotInheritedLintNote {
771 signature_span: tcx.def_span(parent_id.def_id),
772 body_span,
773 }
774 })
775 } else {
776 None
777 };
778 match self {
781 CallToUnsafeFunction(Some(did)) => tcx.emit_node_span_lint(
782 UNSAFE_OP_IN_UNSAFE_FN,
783 hir_id,
784 span,
785 UnsafeOpInUnsafeFnCallToUnsafeFunctionRequiresUnsafe {
786 span,
787 function: with_no_trimmed_paths!(tcx.def_path_str(*did)),
788 unsafe_not_inherited_note,
789 },
790 ),
791 CallToUnsafeFunction(None) => tcx.emit_node_span_lint(
792 UNSAFE_OP_IN_UNSAFE_FN,
793 hir_id,
794 span,
795 UnsafeOpInUnsafeFnCallToUnsafeFunctionRequiresUnsafeNameless {
796 span,
797 unsafe_not_inherited_note,
798 },
799 ),
800 UseOfInlineAssembly => tcx.emit_node_span_lint(
801 UNSAFE_OP_IN_UNSAFE_FN,
802 hir_id,
803 span,
804 UnsafeOpInUnsafeFnUseOfInlineAssemblyRequiresUnsafe {
805 span,
806 unsafe_not_inherited_note,
807 },
808 ),
809 InitializingTypeWith => tcx.emit_node_span_lint(
810 UNSAFE_OP_IN_UNSAFE_FN,
811 hir_id,
812 span,
813 UnsafeOpInUnsafeFnInitializingTypeWithRequiresUnsafe {
814 span,
815 unsafe_not_inherited_note,
816 },
817 ),
818 InitializingTypeWithUnsafeField => tcx.emit_node_span_lint(
819 UNSAFE_OP_IN_UNSAFE_FN,
820 hir_id,
821 span,
822 UnsafeOpInUnsafeFnInitializingTypeWithUnsafeFieldRequiresUnsafe {
823 span,
824 unsafe_not_inherited_note,
825 },
826 ),
827 UseOfMutableStatic => tcx.emit_node_span_lint(
828 UNSAFE_OP_IN_UNSAFE_FN,
829 hir_id,
830 span,
831 UnsafeOpInUnsafeFnUseOfMutableStaticRequiresUnsafe {
832 span,
833 unsafe_not_inherited_note,
834 },
835 ),
836 UseOfExternStatic => tcx.emit_node_span_lint(
837 UNSAFE_OP_IN_UNSAFE_FN,
838 hir_id,
839 span,
840 UnsafeOpInUnsafeFnUseOfExternStaticRequiresUnsafe {
841 span,
842 unsafe_not_inherited_note,
843 },
844 ),
845 UseOfUnsafeField => tcx.emit_node_span_lint(
846 UNSAFE_OP_IN_UNSAFE_FN,
847 hir_id,
848 span,
849 UnsafeOpInUnsafeFnUseOfUnsafeFieldRequiresUnsafe {
850 span,
851 unsafe_not_inherited_note,
852 },
853 ),
854 DerefOfRawPointer => tcx.emit_node_span_lint(
855 UNSAFE_OP_IN_UNSAFE_FN,
856 hir_id,
857 span,
858 UnsafeOpInUnsafeFnDerefOfRawPointerRequiresUnsafe {
859 span,
860 unsafe_not_inherited_note,
861 },
862 ),
863 AccessToUnionField => tcx.emit_node_span_lint(
864 UNSAFE_OP_IN_UNSAFE_FN,
865 hir_id,
866 span,
867 UnsafeOpInUnsafeFnAccessToUnionFieldRequiresUnsafe {
868 span,
869 unsafe_not_inherited_note,
870 },
871 ),
872 MutationOfLayoutConstrainedField => tcx.emit_node_span_lint(
873 UNSAFE_OP_IN_UNSAFE_FN,
874 hir_id,
875 span,
876 UnsafeOpInUnsafeFnMutationOfLayoutConstrainedFieldRequiresUnsafe {
877 span,
878 unsafe_not_inherited_note,
879 },
880 ),
881 BorrowOfLayoutConstrainedField => tcx.emit_node_span_lint(
882 UNSAFE_OP_IN_UNSAFE_FN,
883 hir_id,
884 span,
885 UnsafeOpInUnsafeFnBorrowOfLayoutConstrainedFieldRequiresUnsafe {
886 span,
887 unsafe_not_inherited_note,
888 },
889 ),
890 CallToFunctionWith { function, missing, build_enabled } => tcx.emit_node_span_lint(
891 UNSAFE_OP_IN_UNSAFE_FN,
892 hir_id,
893 span,
894 UnsafeOpInUnsafeFnCallToFunctionWithRequiresUnsafe {
895 span,
896 function: with_no_trimmed_paths!(tcx.def_path_str(*function)),
897 missing_target_features: DiagArgValue::StrListSepByAnd(
898 missing.iter().map(|feature| Cow::from(feature.to_string())).collect(),
899 ),
900 missing_target_features_count: missing.len(),
901 note: !build_enabled.is_empty(),
902 build_target_features: DiagArgValue::StrListSepByAnd(
903 build_enabled
904 .iter()
905 .map(|feature| Cow::from(feature.to_string()))
906 .collect(),
907 ),
908 build_target_features_count: build_enabled.len(),
909 unsafe_not_inherited_note,
910 },
911 ),
912 UnsafeBinderCast => tcx.emit_node_span_lint(
913 UNSAFE_OP_IN_UNSAFE_FN,
914 hir_id,
915 span,
916 UnsafeOpInUnsafeFnUnsafeBinderCastRequiresUnsafe {
917 span,
918 unsafe_not_inherited_note,
919 },
920 ),
921 }
922 }
923
924 fn emit_requires_unsafe_err(
925 &self,
926 tcx: TyCtxt<'_>,
927 span: Span,
928 hir_context: HirId,
929 unsafe_op_in_unsafe_fn_allowed: bool,
930 ) {
931 let note_non_inherited = tcx.hir_parent_iter(hir_context).find(|(id, node)| {
932 if let hir::Node::Expr(block) = node
933 && let hir::ExprKind::Block(block, _) = block.kind
934 && let hir::BlockCheckMode::UnsafeBlock(_) = block.rules
935 {
936 true
937 } else if let Some(sig) = tcx.hir_fn_sig_by_hir_id(*id)
938 && matches!(sig.header.safety, hir::HeaderSafety::Normal(hir::Safety::Unsafe))
939 {
940 true
941 } else {
942 false
943 }
944 });
945 let unsafe_not_inherited_note = if let Some((id, _)) = note_non_inherited {
946 let span = tcx.hir().span(id);
947 let span = tcx.sess.source_map().guess_head_span(span);
948 Some(UnsafeNotInheritedNote { span })
949 } else {
950 None
951 };
952
953 let dcx = tcx.dcx();
954 match self {
955 CallToUnsafeFunction(Some(did)) if unsafe_op_in_unsafe_fn_allowed => {
956 dcx.emit_err(CallToUnsafeFunctionRequiresUnsafeUnsafeOpInUnsafeFnAllowed {
957 span,
958 unsafe_not_inherited_note,
959 function: tcx.def_path_str(*did),
960 });
961 }
962 CallToUnsafeFunction(Some(did)) => {
963 dcx.emit_err(CallToUnsafeFunctionRequiresUnsafe {
964 span,
965 unsafe_not_inherited_note,
966 function: tcx.def_path_str(*did),
967 });
968 }
969 CallToUnsafeFunction(None) if unsafe_op_in_unsafe_fn_allowed => {
970 dcx.emit_err(CallToUnsafeFunctionRequiresUnsafeNamelessUnsafeOpInUnsafeFnAllowed {
971 span,
972 unsafe_not_inherited_note,
973 });
974 }
975 CallToUnsafeFunction(None) => {
976 dcx.emit_err(CallToUnsafeFunctionRequiresUnsafeNameless {
977 span,
978 unsafe_not_inherited_note,
979 });
980 }
981 UseOfInlineAssembly if unsafe_op_in_unsafe_fn_allowed => {
982 dcx.emit_err(UseOfInlineAssemblyRequiresUnsafeUnsafeOpInUnsafeFnAllowed {
983 span,
984 unsafe_not_inherited_note,
985 });
986 }
987 UseOfInlineAssembly => {
988 dcx.emit_err(UseOfInlineAssemblyRequiresUnsafe { span, unsafe_not_inherited_note });
989 }
990 InitializingTypeWith if unsafe_op_in_unsafe_fn_allowed => {
991 dcx.emit_err(InitializingTypeWithRequiresUnsafeUnsafeOpInUnsafeFnAllowed {
992 span,
993 unsafe_not_inherited_note,
994 });
995 }
996 InitializingTypeWith => {
997 dcx.emit_err(InitializingTypeWithRequiresUnsafe {
998 span,
999 unsafe_not_inherited_note,
1000 });
1001 }
1002 InitializingTypeWithUnsafeField if unsafe_op_in_unsafe_fn_allowed => {
1003 dcx.emit_err(
1004 InitializingTypeWithUnsafeFieldRequiresUnsafeUnsafeOpInUnsafeFnAllowed {
1005 span,
1006 unsafe_not_inherited_note,
1007 },
1008 );
1009 }
1010 InitializingTypeWithUnsafeField => {
1011 dcx.emit_err(InitializingTypeWithUnsafeFieldRequiresUnsafe {
1012 span,
1013 unsafe_not_inherited_note,
1014 });
1015 }
1016 UseOfMutableStatic if unsafe_op_in_unsafe_fn_allowed => {
1017 dcx.emit_err(UseOfMutableStaticRequiresUnsafeUnsafeOpInUnsafeFnAllowed {
1018 span,
1019 unsafe_not_inherited_note,
1020 });
1021 }
1022 UseOfMutableStatic => {
1023 dcx.emit_err(UseOfMutableStaticRequiresUnsafe { span, unsafe_not_inherited_note });
1024 }
1025 UseOfExternStatic if unsafe_op_in_unsafe_fn_allowed => {
1026 dcx.emit_err(UseOfExternStaticRequiresUnsafeUnsafeOpInUnsafeFnAllowed {
1027 span,
1028 unsafe_not_inherited_note,
1029 });
1030 }
1031 UseOfExternStatic => {
1032 dcx.emit_err(UseOfExternStaticRequiresUnsafe { span, unsafe_not_inherited_note });
1033 }
1034 UseOfUnsafeField if unsafe_op_in_unsafe_fn_allowed => {
1035 dcx.emit_err(UseOfUnsafeFieldRequiresUnsafeUnsafeOpInUnsafeFnAllowed {
1036 span,
1037 unsafe_not_inherited_note,
1038 });
1039 }
1040 UseOfUnsafeField => {
1041 dcx.emit_err(UseOfUnsafeFieldRequiresUnsafe { span, unsafe_not_inherited_note });
1042 }
1043 DerefOfRawPointer if unsafe_op_in_unsafe_fn_allowed => {
1044 dcx.emit_err(DerefOfRawPointerRequiresUnsafeUnsafeOpInUnsafeFnAllowed {
1045 span,
1046 unsafe_not_inherited_note,
1047 });
1048 }
1049 DerefOfRawPointer => {
1050 dcx.emit_err(DerefOfRawPointerRequiresUnsafe { span, unsafe_not_inherited_note });
1051 }
1052 AccessToUnionField if unsafe_op_in_unsafe_fn_allowed => {
1053 dcx.emit_err(AccessToUnionFieldRequiresUnsafeUnsafeOpInUnsafeFnAllowed {
1054 span,
1055 unsafe_not_inherited_note,
1056 });
1057 }
1058 AccessToUnionField => {
1059 dcx.emit_err(AccessToUnionFieldRequiresUnsafe { span, unsafe_not_inherited_note });
1060 }
1061 MutationOfLayoutConstrainedField if unsafe_op_in_unsafe_fn_allowed => {
1062 dcx.emit_err(
1063 MutationOfLayoutConstrainedFieldRequiresUnsafeUnsafeOpInUnsafeFnAllowed {
1064 span,
1065 unsafe_not_inherited_note,
1066 },
1067 );
1068 }
1069 MutationOfLayoutConstrainedField => {
1070 dcx.emit_err(MutationOfLayoutConstrainedFieldRequiresUnsafe {
1071 span,
1072 unsafe_not_inherited_note,
1073 });
1074 }
1075 BorrowOfLayoutConstrainedField if unsafe_op_in_unsafe_fn_allowed => {
1076 dcx.emit_err(
1077 BorrowOfLayoutConstrainedFieldRequiresUnsafeUnsafeOpInUnsafeFnAllowed {
1078 span,
1079 unsafe_not_inherited_note,
1080 },
1081 );
1082 }
1083 BorrowOfLayoutConstrainedField => {
1084 dcx.emit_err(BorrowOfLayoutConstrainedFieldRequiresUnsafe {
1085 span,
1086 unsafe_not_inherited_note,
1087 });
1088 }
1089 CallToFunctionWith { function, missing, build_enabled }
1090 if unsafe_op_in_unsafe_fn_allowed =>
1091 {
1092 dcx.emit_err(CallToFunctionWithRequiresUnsafeUnsafeOpInUnsafeFnAllowed {
1093 span,
1094 missing_target_features: DiagArgValue::StrListSepByAnd(
1095 missing.iter().map(|feature| Cow::from(feature.to_string())).collect(),
1096 ),
1097 missing_target_features_count: missing.len(),
1098 note: !build_enabled.is_empty(),
1099 build_target_features: DiagArgValue::StrListSepByAnd(
1100 build_enabled
1101 .iter()
1102 .map(|feature| Cow::from(feature.to_string()))
1103 .collect(),
1104 ),
1105 build_target_features_count: build_enabled.len(),
1106 unsafe_not_inherited_note,
1107 function: tcx.def_path_str(*function),
1108 });
1109 }
1110 CallToFunctionWith { function, missing, build_enabled } => {
1111 dcx.emit_err(CallToFunctionWithRequiresUnsafe {
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 UnsafeBinderCast if unsafe_op_in_unsafe_fn_allowed => {
1130 dcx.emit_err(UnsafeBinderCastRequiresUnsafeUnsafeOpInUnsafeFnAllowed {
1131 span,
1132 unsafe_not_inherited_note,
1133 });
1134 }
1135 UnsafeBinderCast => {
1136 dcx.emit_err(UnsafeBinderCastRequiresUnsafe { span, unsafe_not_inherited_note });
1137 }
1138 }
1139 }
1140}
1141
1142pub(crate) fn check_unsafety(tcx: TyCtxt<'_>, def: LocalDefId) {
1143 if tcx.is_typeck_child(def.to_def_id()) || tcx.has_attr(def, sym::custom_mir) {
1146 return;
1147 }
1148
1149 let Ok((thir, expr)) = tcx.thir_body(def) else { return };
1150 tcx.ensure_done().mir_built(def);
1152 let thir = &thir.steal();
1153
1154 let hir_id = tcx.local_def_id_to_hir_id(def);
1155 let safety_context = tcx.hir_fn_sig_by_hir_id(hir_id).map_or(SafetyContext::Safe, |fn_sig| {
1156 match fn_sig.header.safety {
1157 hir::HeaderSafety::SafeTargetFeatures => SafetyContext::Safe,
1161 hir::HeaderSafety::Normal(safety) => match safety {
1162 hir::Safety::Unsafe => SafetyContext::UnsafeFn,
1163 hir::Safety::Safe => SafetyContext::Safe,
1164 },
1165 }
1166 });
1167 let body_target_features = &tcx.body_codegen_attrs(def.to_def_id()).target_features;
1168 let mut warnings = Vec::new();
1169 let mut visitor = UnsafetyVisitor {
1170 tcx,
1171 thir,
1172 safety_context,
1173 hir_context: hir_id,
1174 body_target_features,
1175 assignment_info: None,
1176 in_union_destructure: false,
1177 typing_env: ty::TypingEnv::non_body_analysis(tcx, def),
1179 inside_adt: false,
1180 warnings: &mut warnings,
1181 suggest_unsafe_block: true,
1182 };
1183 for param in &thir.params {
1185 if let Some(param_pat) = param.pat.as_deref() {
1186 visitor.visit_pat(param_pat);
1187 }
1188 }
1189 visitor.visit_expr(&thir[expr]);
1191
1192 warnings.sort_by_key(|w| w.block_span);
1193 for UnusedUnsafeWarning { hir_id, block_span, enclosing_unsafe } in warnings {
1194 let block_span = tcx.sess.source_map().guess_head_span(block_span);
1195 tcx.emit_node_span_lint(
1196 UNUSED_UNSAFE,
1197 hir_id,
1198 block_span,
1199 UnusedUnsafe { span: block_span, enclosing: enclosing_unsafe },
1200 );
1201 }
1202}