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::ExpandedConstant { .. } |
346 PatKind::AscribeUserType { .. } |
347 PatKind::Error(_) => {}
348 }
349 };
350
351 match &pat.kind {
352 PatKind::Leaf { subpatterns, .. } => {
353 if let ty::Adt(adt_def, ..) = pat.ty.kind() {
354 for pat in subpatterns {
355 if adt_def.non_enum_variant().fields[pat.field].safety.is_unsafe() {
356 self.requires_unsafe(pat.pattern.span, UseOfUnsafeField);
357 }
358 }
359 if adt_def.is_union() {
360 let old_in_union_destructure =
361 std::mem::replace(&mut self.in_union_destructure, true);
362 visit::walk_pat(self, pat);
363 self.in_union_destructure = old_in_union_destructure;
364 } else if (Bound::Unbounded, Bound::Unbounded)
365 != self.tcx.layout_scalar_valid_range(adt_def.did())
366 {
367 let old_inside_adt = std::mem::replace(&mut self.inside_adt, true);
368 visit::walk_pat(self, pat);
369 self.inside_adt = old_inside_adt;
370 } else {
371 visit::walk_pat(self, pat);
372 }
373 } else {
374 visit::walk_pat(self, pat);
375 }
376 }
377 PatKind::Variant { adt_def, args: _, variant_index, subpatterns } => {
378 for pat in subpatterns {
379 let field = &pat.field;
380 if adt_def.variant(*variant_index).fields[*field].safety.is_unsafe() {
381 self.requires_unsafe(pat.pattern.span, UseOfUnsafeField);
382 }
383 }
384 visit::walk_pat(self, pat);
385 }
386 PatKind::Binding { mode: BindingMode(ByRef::Yes(_, rm), _), ty, .. } => {
387 if self.inside_adt {
388 let ty::Ref(_, ty, _) = ty.kind() else {
389 span_bug!(
390 pat.span,
391 "ByRef::Yes in pattern, but found non-reference type {}",
392 ty
393 );
394 };
395 match rm {
396 Mutability::Not => {
397 if !ty.is_freeze(self.tcx, self.typing_env) {
398 self.requires_unsafe(pat.span, BorrowOfLayoutConstrainedField);
399 }
400 }
401 Mutability::Mut { .. } => {
402 self.requires_unsafe(pat.span, MutationOfLayoutConstrainedField);
403 }
404 }
405 }
406 visit::walk_pat(self, pat);
407 }
408 PatKind::Deref { .. } | PatKind::DerefPattern { .. } => {
409 let old_inside_adt = std::mem::replace(&mut self.inside_adt, false);
410 visit::walk_pat(self, pat);
411 self.inside_adt = old_inside_adt;
412 }
413 PatKind::ExpandedConstant { def_id, .. } => {
414 if let Some(def) = def_id.as_local()
415 && matches!(self.tcx.def_kind(def_id), DefKind::InlineConst)
416 {
417 self.visit_inner_body(def);
418 }
419 visit::walk_pat(self, pat);
420 }
421 _ => {
422 visit::walk_pat(self, pat);
423 }
424 }
425 }
426
427 fn visit_expr(&mut self, expr: &'a Expr<'tcx>) {
428 match expr.kind {
430 ExprKind::Field { .. }
431 | ExprKind::VarRef { .. }
432 | ExprKind::UpvarRef { .. }
433 | ExprKind::Scope { .. }
434 | ExprKind::Cast { .. } => {}
435
436 ExprKind::RawBorrow { .. }
437 | ExprKind::Adt { .. }
438 | ExprKind::Array { .. }
439 | ExprKind::Binary { .. }
440 | ExprKind::Block { .. }
441 | ExprKind::Borrow { .. }
442 | ExprKind::Literal { .. }
443 | ExprKind::NamedConst { .. }
444 | ExprKind::NonHirLiteral { .. }
445 | ExprKind::ZstLiteral { .. }
446 | ExprKind::ConstParam { .. }
447 | ExprKind::ConstBlock { .. }
448 | ExprKind::Deref { .. }
449 | ExprKind::Index { .. }
450 | ExprKind::NeverToAny { .. }
451 | ExprKind::PlaceTypeAscription { .. }
452 | ExprKind::ValueTypeAscription { .. }
453 | ExprKind::PlaceUnwrapUnsafeBinder { .. }
454 | ExprKind::ValueUnwrapUnsafeBinder { .. }
455 | ExprKind::WrapUnsafeBinder { .. }
456 | ExprKind::PointerCoercion { .. }
457 | ExprKind::Repeat { .. }
458 | ExprKind::StaticRef { .. }
459 | ExprKind::ThreadLocalRef { .. }
460 | ExprKind::Tuple { .. }
461 | ExprKind::Unary { .. }
462 | ExprKind::Call { .. }
463 | ExprKind::ByUse { .. }
464 | ExprKind::Assign { .. }
465 | ExprKind::AssignOp { .. }
466 | ExprKind::Break { .. }
467 | ExprKind::Closure { .. }
468 | ExprKind::Continue { .. }
469 | ExprKind::ConstContinue { .. }
470 | ExprKind::Return { .. }
471 | ExprKind::Become { .. }
472 | ExprKind::Yield { .. }
473 | ExprKind::Loop { .. }
474 | ExprKind::LoopMatch { .. }
475 | ExprKind::Let { .. }
476 | ExprKind::Match { .. }
477 | ExprKind::Box { .. }
478 | ExprKind::If { .. }
479 | ExprKind::InlineAsm { .. }
480 | ExprKind::LogicalOp { .. }
481 | ExprKind::Use { .. } => {
482 self.assignment_info = None;
486 }
487 };
488 match expr.kind {
489 ExprKind::Scope { value, lint_level: LintLevel::Explicit(hir_id), region_scope: _ } => {
490 let prev_id = self.hir_context;
491 self.hir_context = hir_id;
492 ensure_sufficient_stack(|| {
493 self.visit_expr(&self.thir[value]);
494 });
495 self.hir_context = prev_id;
496 return; }
498 ExprKind::Call { fun, ty: _, args: _, from_hir_call: _, fn_span: _ } => {
499 let fn_ty = self.thir[fun].ty;
500 let sig = fn_ty.fn_sig(self.tcx);
501 let (callee_features, safe_target_features): (&[_], _) = match fn_ty.kind() {
502 ty::FnDef(func_id, ..) => {
503 let cg_attrs = self.tcx.codegen_fn_attrs(func_id);
504 (&cg_attrs.target_features, cg_attrs.safe_target_features)
505 }
506 _ => (&[], false),
507 };
508 if sig.safety().is_unsafe() && !safe_target_features {
509 let func_id = if let ty::FnDef(func_id, _) = fn_ty.kind() {
510 Some(*func_id)
511 } else {
512 None
513 };
514 self.requires_unsafe(expr.span, CallToUnsafeFunction(func_id));
515 } else if let &ty::FnDef(func_did, _) = fn_ty.kind() {
516 if !self
517 .tcx
518 .is_target_feature_call_safe(callee_features, self.body_target_features)
519 {
520 let missing: Vec<_> = callee_features
521 .iter()
522 .copied()
523 .filter(|feature| {
524 feature.kind == TargetFeatureKind::Enabled
525 && !self
526 .body_target_features
527 .iter()
528 .any(|body_feature| body_feature.name == feature.name)
529 })
530 .map(|feature| feature.name)
531 .collect();
532 let build_enabled = self
533 .tcx
534 .sess
535 .target_features
536 .iter()
537 .copied()
538 .filter(|feature| missing.contains(feature))
539 .collect();
540 self.requires_unsafe(
541 expr.span,
542 CallToFunctionWith { function: func_did, missing, build_enabled },
543 );
544 }
545 }
546 }
547 ExprKind::RawBorrow { arg, .. } => {
548 if let ExprKind::Scope { value: arg, .. } = self.thir[arg].kind
549 && let ExprKind::Deref { arg } = self.thir[arg].kind
550 {
551 visit::walk_expr(self, &self.thir[arg]);
554 return;
555 }
556
557 let mut peeled = arg;
561 while let ExprKind::Scope { value: arg, .. } = self.thir[peeled].kind
562 && let ExprKind::Field { lhs, name: _, variant_index: _ } = self.thir[arg].kind
563 && let ty::Adt(def, _) = &self.thir[lhs].ty.kind()
564 && def.is_union()
565 {
566 peeled = lhs;
567 }
568 visit::walk_expr(self, &self.thir[peeled]);
569 return;
571 }
572 ExprKind::Deref { arg } => {
573 if let ExprKind::StaticRef { def_id, .. } | ExprKind::ThreadLocalRef(def_id) =
574 self.thir[arg].kind
575 {
576 if self.tcx.is_mutable_static(def_id) {
577 self.requires_unsafe(expr.span, UseOfMutableStatic);
578 } else if self.tcx.is_foreign_item(def_id) {
579 match self.tcx.def_kind(def_id) {
580 DefKind::Static { safety: hir::Safety::Safe, .. } => {}
581 _ => self.requires_unsafe(expr.span, UseOfExternStatic),
582 }
583 }
584 } else if self.thir[arg].ty.is_raw_ptr() {
585 self.requires_unsafe(expr.span, DerefOfRawPointer);
586 }
587 }
588 ExprKind::InlineAsm(box InlineAsmExpr {
589 asm_macro: asm_macro @ (AsmMacro::Asm | AsmMacro::NakedAsm),
590 ref operands,
591 template: _,
592 options: _,
593 line_spans: _,
594 }) => {
595 if let AsmMacro::Asm = asm_macro {
598 self.requires_unsafe(expr.span, UseOfInlineAssembly);
599 }
600
601 for op in &**operands {
604 use rustc_middle::thir::InlineAsmOperand::*;
605 match op {
606 In { expr, reg: _ }
607 | Out { expr: Some(expr), reg: _, late: _ }
608 | InOut { expr, reg: _, late: _ } => self.visit_expr(&self.thir()[*expr]),
609 SplitInOut { in_expr, out_expr, reg: _, late: _ } => {
610 self.visit_expr(&self.thir()[*in_expr]);
611 if let Some(out_expr) = out_expr {
612 self.visit_expr(&self.thir()[*out_expr]);
613 }
614 }
615 Out { expr: None, reg: _, late: _ }
616 | Const { value: _, span: _ }
617 | SymFn { value: _ }
618 | SymStatic { def_id: _ } => {}
619 Label { block } => {
620 self.in_safety_context(SafetyContext::Safe, |this| {
625 visit::walk_block(this, &this.thir()[*block])
626 });
627 }
628 }
629 }
630 return;
631 }
632 ExprKind::Adt(box AdtExpr {
633 adt_def,
634 variant_index,
635 args: _,
636 user_ty: _,
637 fields: _,
638 base: _,
639 }) => {
640 if adt_def.variant(variant_index).has_unsafe_fields() {
641 self.requires_unsafe(expr.span, InitializingTypeWithUnsafeField)
642 }
643 match self.tcx.layout_scalar_valid_range(adt_def.did()) {
644 (Bound::Unbounded, Bound::Unbounded) => {}
645 _ => self.requires_unsafe(expr.span, InitializingTypeWith),
646 }
647 }
648 ExprKind::Closure(box ClosureExpr {
649 closure_id,
650 args: _,
651 upvars: _,
652 movability: _,
653 fake_reads: _,
654 }) => {
655 self.visit_inner_body(closure_id);
656 }
657 ExprKind::ConstBlock { did, args: _ } => {
658 let def_id = did.expect_local();
659 self.visit_inner_body(def_id);
660 }
661 ExprKind::Field { lhs, variant_index, name } => {
662 let lhs = &self.thir[lhs];
663 if let ty::Adt(adt_def, _) = lhs.ty.kind() {
664 if adt_def.variant(variant_index).fields[name].safety.is_unsafe() {
665 self.requires_unsafe(expr.span, UseOfUnsafeField);
666 } else if adt_def.is_union() {
667 if let Some(assigned_ty) = self.assignment_info {
668 if assigned_ty.needs_drop(self.tcx, self.typing_env) {
669 assert!(
672 self.tcx.dcx().has_errors().is_some(),
673 "union fields that need dropping should be impossible: {assigned_ty}"
674 );
675 }
676 } else {
677 self.requires_unsafe(expr.span, AccessToUnionField);
678 }
679 }
680 }
681 }
682 ExprKind::Assign { lhs, rhs } | ExprKind::AssignOp { lhs, rhs, .. } => {
683 let lhs = &self.thir[lhs];
684 let mut visitor = LayoutConstrainedPlaceVisitor::new(self.thir, self.tcx);
686 visit::walk_expr(&mut visitor, lhs);
687 if visitor.found {
688 self.requires_unsafe(expr.span, MutationOfLayoutConstrainedField);
689 }
690
691 if matches!(expr.kind, ExprKind::Assign { .. }) {
695 self.assignment_info = Some(lhs.ty);
696 visit::walk_expr(self, lhs);
697 self.assignment_info = None;
698 visit::walk_expr(self, &self.thir()[rhs]);
699 return; }
701 }
702 ExprKind::Borrow { borrow_kind, arg } => {
703 let mut visitor = LayoutConstrainedPlaceVisitor::new(self.thir, self.tcx);
704 visit::walk_expr(&mut visitor, expr);
705 if visitor.found {
706 match borrow_kind {
707 BorrowKind::Fake(_) | BorrowKind::Shared
708 if !self.thir[arg].ty.is_freeze(self.tcx, self.typing_env) =>
709 {
710 self.requires_unsafe(expr.span, BorrowOfLayoutConstrainedField)
711 }
712 BorrowKind::Mut { .. } => {
713 self.requires_unsafe(expr.span, MutationOfLayoutConstrainedField)
714 }
715 BorrowKind::Fake(_) | BorrowKind::Shared => {}
716 }
717 }
718 }
719 ExprKind::PlaceUnwrapUnsafeBinder { .. }
720 | ExprKind::ValueUnwrapUnsafeBinder { .. }
721 | ExprKind::WrapUnsafeBinder { .. } => {
722 self.requires_unsafe(expr.span, UnsafeBinderCast);
723 }
724 _ => {}
725 }
726 visit::walk_expr(self, expr);
727 }
728}
729
730#[derive(Clone)]
731enum SafetyContext {
732 Safe,
733 BuiltinUnsafeBlock,
734 UnsafeFn,
735 UnsafeBlock { span: Span, hir_id: HirId, used: bool, nested_used_blocks: Vec<NestedUsedBlock> },
736}
737
738#[derive(Clone, Copy)]
739struct NestedUsedBlock {
740 hir_id: HirId,
741 span: Span,
742}
743
744struct UnusedUnsafeWarning {
745 hir_id: HirId,
746 block_span: Span,
747 enclosing_unsafe: Option<UnusedUnsafeEnclosing>,
748}
749
750#[derive(Clone, PartialEq)]
751enum UnsafeOpKind {
752 CallToUnsafeFunction(Option<DefId>),
753 UseOfInlineAssembly,
754 InitializingTypeWith,
755 InitializingTypeWithUnsafeField,
756 UseOfMutableStatic,
757 UseOfExternStatic,
758 UseOfUnsafeField,
759 DerefOfRawPointer,
760 AccessToUnionField,
761 MutationOfLayoutConstrainedField,
762 BorrowOfLayoutConstrainedField,
763 CallToFunctionWith {
764 function: DefId,
765 missing: Vec<Symbol>,
768 build_enabled: Vec<Symbol>,
771 },
772 UnsafeBinderCast,
773}
774
775use UnsafeOpKind::*;
776
777impl UnsafeOpKind {
778 fn emit_unsafe_op_in_unsafe_fn_lint(
779 &self,
780 tcx: TyCtxt<'_>,
781 hir_id: HirId,
782 span: Span,
783 suggest_unsafe_block: bool,
784 ) {
785 if tcx.hir_opt_delegation_sig_id(hir_id.owner.def_id).is_some() {
786 return;
789 }
790 let parent_id = tcx.hir_get_parent_item(hir_id);
791 let parent_owner = tcx.hir_owner_node(parent_id);
792 let should_suggest = parent_owner.fn_sig().is_some_and(|sig| {
793 matches!(sig.header.safety, hir::HeaderSafety::Normal(hir::Safety::Unsafe))
795 });
796 let unsafe_not_inherited_note = if should_suggest {
797 suggest_unsafe_block.then(|| {
798 let body_span = tcx.hir_body(parent_owner.body_id().unwrap()).value.span;
799 UnsafeNotInheritedLintNote {
800 signature_span: tcx.def_span(parent_id.def_id),
801 body_span,
802 }
803 })
804 } else {
805 None
806 };
807 match self {
810 CallToUnsafeFunction(Some(did)) => tcx.emit_node_span_lint(
811 UNSAFE_OP_IN_UNSAFE_FN,
812 hir_id,
813 span,
814 UnsafeOpInUnsafeFnCallToUnsafeFunctionRequiresUnsafe {
815 span,
816 function: with_no_trimmed_paths!(tcx.def_path_str(*did)),
817 unsafe_not_inherited_note,
818 },
819 ),
820 CallToUnsafeFunction(None) => tcx.emit_node_span_lint(
821 UNSAFE_OP_IN_UNSAFE_FN,
822 hir_id,
823 span,
824 UnsafeOpInUnsafeFnCallToUnsafeFunctionRequiresUnsafeNameless {
825 span,
826 unsafe_not_inherited_note,
827 },
828 ),
829 UseOfInlineAssembly => tcx.emit_node_span_lint(
830 UNSAFE_OP_IN_UNSAFE_FN,
831 hir_id,
832 span,
833 UnsafeOpInUnsafeFnUseOfInlineAssemblyRequiresUnsafe {
834 span,
835 unsafe_not_inherited_note,
836 },
837 ),
838 InitializingTypeWith => tcx.emit_node_span_lint(
839 UNSAFE_OP_IN_UNSAFE_FN,
840 hir_id,
841 span,
842 UnsafeOpInUnsafeFnInitializingTypeWithRequiresUnsafe {
843 span,
844 unsafe_not_inherited_note,
845 },
846 ),
847 InitializingTypeWithUnsafeField => tcx.emit_node_span_lint(
848 UNSAFE_OP_IN_UNSAFE_FN,
849 hir_id,
850 span,
851 UnsafeOpInUnsafeFnInitializingTypeWithUnsafeFieldRequiresUnsafe {
852 span,
853 unsafe_not_inherited_note,
854 },
855 ),
856 UseOfMutableStatic => tcx.emit_node_span_lint(
857 UNSAFE_OP_IN_UNSAFE_FN,
858 hir_id,
859 span,
860 UnsafeOpInUnsafeFnUseOfMutableStaticRequiresUnsafe {
861 span,
862 unsafe_not_inherited_note,
863 },
864 ),
865 UseOfExternStatic => tcx.emit_node_span_lint(
866 UNSAFE_OP_IN_UNSAFE_FN,
867 hir_id,
868 span,
869 UnsafeOpInUnsafeFnUseOfExternStaticRequiresUnsafe {
870 span,
871 unsafe_not_inherited_note,
872 },
873 ),
874 UseOfUnsafeField => tcx.emit_node_span_lint(
875 UNSAFE_OP_IN_UNSAFE_FN,
876 hir_id,
877 span,
878 UnsafeOpInUnsafeFnUseOfUnsafeFieldRequiresUnsafe {
879 span,
880 unsafe_not_inherited_note,
881 },
882 ),
883 DerefOfRawPointer => tcx.emit_node_span_lint(
884 UNSAFE_OP_IN_UNSAFE_FN,
885 hir_id,
886 span,
887 UnsafeOpInUnsafeFnDerefOfRawPointerRequiresUnsafe {
888 span,
889 unsafe_not_inherited_note,
890 },
891 ),
892 AccessToUnionField => tcx.emit_node_span_lint(
893 UNSAFE_OP_IN_UNSAFE_FN,
894 hir_id,
895 span,
896 UnsafeOpInUnsafeFnAccessToUnionFieldRequiresUnsafe {
897 span,
898 unsafe_not_inherited_note,
899 },
900 ),
901 MutationOfLayoutConstrainedField => tcx.emit_node_span_lint(
902 UNSAFE_OP_IN_UNSAFE_FN,
903 hir_id,
904 span,
905 UnsafeOpInUnsafeFnMutationOfLayoutConstrainedFieldRequiresUnsafe {
906 span,
907 unsafe_not_inherited_note,
908 },
909 ),
910 BorrowOfLayoutConstrainedField => tcx.emit_node_span_lint(
911 UNSAFE_OP_IN_UNSAFE_FN,
912 hir_id,
913 span,
914 UnsafeOpInUnsafeFnBorrowOfLayoutConstrainedFieldRequiresUnsafe {
915 span,
916 unsafe_not_inherited_note,
917 },
918 ),
919 CallToFunctionWith { function, missing, build_enabled } => tcx.emit_node_span_lint(
920 UNSAFE_OP_IN_UNSAFE_FN,
921 hir_id,
922 span,
923 UnsafeOpInUnsafeFnCallToFunctionWithRequiresUnsafe {
924 span,
925 function: with_no_trimmed_paths!(tcx.def_path_str(*function)),
926 missing_target_features: DiagArgValue::StrListSepByAnd(
927 missing.iter().map(|feature| Cow::from(feature.to_string())).collect(),
928 ),
929 missing_target_features_count: missing.len(),
930 note: !build_enabled.is_empty(),
931 build_target_features: DiagArgValue::StrListSepByAnd(
932 build_enabled
933 .iter()
934 .map(|feature| Cow::from(feature.to_string()))
935 .collect(),
936 ),
937 build_target_features_count: build_enabled.len(),
938 unsafe_not_inherited_note,
939 },
940 ),
941 UnsafeBinderCast => tcx.emit_node_span_lint(
942 UNSAFE_OP_IN_UNSAFE_FN,
943 hir_id,
944 span,
945 UnsafeOpInUnsafeFnUnsafeBinderCastRequiresUnsafe {
946 span,
947 unsafe_not_inherited_note,
948 },
949 ),
950 }
951 }
952
953 fn emit_requires_unsafe_err(
954 &self,
955 tcx: TyCtxt<'_>,
956 span: Span,
957 hir_context: HirId,
958 unsafe_op_in_unsafe_fn_allowed: bool,
959 ) {
960 let note_non_inherited = tcx.hir_parent_iter(hir_context).find(|(id, node)| {
961 if let hir::Node::Expr(block) = node
962 && let hir::ExprKind::Block(block, _) = block.kind
963 && let hir::BlockCheckMode::UnsafeBlock(_) = block.rules
964 {
965 true
966 } else if let Some(sig) = tcx.hir_fn_sig_by_hir_id(*id)
967 && matches!(sig.header.safety, hir::HeaderSafety::Normal(hir::Safety::Unsafe))
968 {
969 true
970 } else {
971 false
972 }
973 });
974 let unsafe_not_inherited_note = if let Some((id, _)) = note_non_inherited {
975 let span = tcx.hir_span(id);
976 let span = tcx.sess.source_map().guess_head_span(span);
977 Some(UnsafeNotInheritedNote { span })
978 } else {
979 None
980 };
981
982 let dcx = tcx.dcx();
983 match self {
984 CallToUnsafeFunction(Some(did)) if unsafe_op_in_unsafe_fn_allowed => {
985 dcx.emit_err(CallToUnsafeFunctionRequiresUnsafeUnsafeOpInUnsafeFnAllowed {
986 span,
987 unsafe_not_inherited_note,
988 function: tcx.def_path_str(*did),
989 });
990 }
991 CallToUnsafeFunction(Some(did)) => {
992 dcx.emit_err(CallToUnsafeFunctionRequiresUnsafe {
993 span,
994 unsafe_not_inherited_note,
995 function: tcx.def_path_str(*did),
996 });
997 }
998 CallToUnsafeFunction(None) if unsafe_op_in_unsafe_fn_allowed => {
999 dcx.emit_err(CallToUnsafeFunctionRequiresUnsafeNamelessUnsafeOpInUnsafeFnAllowed {
1000 span,
1001 unsafe_not_inherited_note,
1002 });
1003 }
1004 CallToUnsafeFunction(None) => {
1005 dcx.emit_err(CallToUnsafeFunctionRequiresUnsafeNameless {
1006 span,
1007 unsafe_not_inherited_note,
1008 });
1009 }
1010 UseOfInlineAssembly if unsafe_op_in_unsafe_fn_allowed => {
1011 dcx.emit_err(UseOfInlineAssemblyRequiresUnsafeUnsafeOpInUnsafeFnAllowed {
1012 span,
1013 unsafe_not_inherited_note,
1014 });
1015 }
1016 UseOfInlineAssembly => {
1017 dcx.emit_err(UseOfInlineAssemblyRequiresUnsafe { span, unsafe_not_inherited_note });
1018 }
1019 InitializingTypeWith if unsafe_op_in_unsafe_fn_allowed => {
1020 dcx.emit_err(InitializingTypeWithRequiresUnsafeUnsafeOpInUnsafeFnAllowed {
1021 span,
1022 unsafe_not_inherited_note,
1023 });
1024 }
1025 InitializingTypeWith => {
1026 dcx.emit_err(InitializingTypeWithRequiresUnsafe {
1027 span,
1028 unsafe_not_inherited_note,
1029 });
1030 }
1031 InitializingTypeWithUnsafeField if unsafe_op_in_unsafe_fn_allowed => {
1032 dcx.emit_err(
1033 InitializingTypeWithUnsafeFieldRequiresUnsafeUnsafeOpInUnsafeFnAllowed {
1034 span,
1035 unsafe_not_inherited_note,
1036 },
1037 );
1038 }
1039 InitializingTypeWithUnsafeField => {
1040 dcx.emit_err(InitializingTypeWithUnsafeFieldRequiresUnsafe {
1041 span,
1042 unsafe_not_inherited_note,
1043 });
1044 }
1045 UseOfMutableStatic if unsafe_op_in_unsafe_fn_allowed => {
1046 dcx.emit_err(UseOfMutableStaticRequiresUnsafeUnsafeOpInUnsafeFnAllowed {
1047 span,
1048 unsafe_not_inherited_note,
1049 });
1050 }
1051 UseOfMutableStatic => {
1052 dcx.emit_err(UseOfMutableStaticRequiresUnsafe { span, unsafe_not_inherited_note });
1053 }
1054 UseOfExternStatic if unsafe_op_in_unsafe_fn_allowed => {
1055 dcx.emit_err(UseOfExternStaticRequiresUnsafeUnsafeOpInUnsafeFnAllowed {
1056 span,
1057 unsafe_not_inherited_note,
1058 });
1059 }
1060 UseOfExternStatic => {
1061 dcx.emit_err(UseOfExternStaticRequiresUnsafe { span, unsafe_not_inherited_note });
1062 }
1063 UseOfUnsafeField if unsafe_op_in_unsafe_fn_allowed => {
1064 dcx.emit_err(UseOfUnsafeFieldRequiresUnsafeUnsafeOpInUnsafeFnAllowed {
1065 span,
1066 unsafe_not_inherited_note,
1067 });
1068 }
1069 UseOfUnsafeField => {
1070 dcx.emit_err(UseOfUnsafeFieldRequiresUnsafe { span, unsafe_not_inherited_note });
1071 }
1072 DerefOfRawPointer if unsafe_op_in_unsafe_fn_allowed => {
1073 dcx.emit_err(DerefOfRawPointerRequiresUnsafeUnsafeOpInUnsafeFnAllowed {
1074 span,
1075 unsafe_not_inherited_note,
1076 });
1077 }
1078 DerefOfRawPointer => {
1079 dcx.emit_err(DerefOfRawPointerRequiresUnsafe { span, unsafe_not_inherited_note });
1080 }
1081 AccessToUnionField if unsafe_op_in_unsafe_fn_allowed => {
1082 dcx.emit_err(AccessToUnionFieldRequiresUnsafeUnsafeOpInUnsafeFnAllowed {
1083 span,
1084 unsafe_not_inherited_note,
1085 });
1086 }
1087 AccessToUnionField => {
1088 dcx.emit_err(AccessToUnionFieldRequiresUnsafe { span, unsafe_not_inherited_note });
1089 }
1090 MutationOfLayoutConstrainedField if unsafe_op_in_unsafe_fn_allowed => {
1091 dcx.emit_err(
1092 MutationOfLayoutConstrainedFieldRequiresUnsafeUnsafeOpInUnsafeFnAllowed {
1093 span,
1094 unsafe_not_inherited_note,
1095 },
1096 );
1097 }
1098 MutationOfLayoutConstrainedField => {
1099 dcx.emit_err(MutationOfLayoutConstrainedFieldRequiresUnsafe {
1100 span,
1101 unsafe_not_inherited_note,
1102 });
1103 }
1104 BorrowOfLayoutConstrainedField if unsafe_op_in_unsafe_fn_allowed => {
1105 dcx.emit_err(
1106 BorrowOfLayoutConstrainedFieldRequiresUnsafeUnsafeOpInUnsafeFnAllowed {
1107 span,
1108 unsafe_not_inherited_note,
1109 },
1110 );
1111 }
1112 BorrowOfLayoutConstrainedField => {
1113 dcx.emit_err(BorrowOfLayoutConstrainedFieldRequiresUnsafe {
1114 span,
1115 unsafe_not_inherited_note,
1116 });
1117 }
1118 CallToFunctionWith { function, missing, build_enabled }
1119 if unsafe_op_in_unsafe_fn_allowed =>
1120 {
1121 dcx.emit_err(CallToFunctionWithRequiresUnsafeUnsafeOpInUnsafeFnAllowed {
1122 span,
1123 missing_target_features: DiagArgValue::StrListSepByAnd(
1124 missing.iter().map(|feature| Cow::from(feature.to_string())).collect(),
1125 ),
1126 missing_target_features_count: missing.len(),
1127 note: !build_enabled.is_empty(),
1128 build_target_features: DiagArgValue::StrListSepByAnd(
1129 build_enabled
1130 .iter()
1131 .map(|feature| Cow::from(feature.to_string()))
1132 .collect(),
1133 ),
1134 build_target_features_count: build_enabled.len(),
1135 unsafe_not_inherited_note,
1136 function: tcx.def_path_str(*function),
1137 });
1138 }
1139 CallToFunctionWith { function, missing, build_enabled } => {
1140 dcx.emit_err(CallToFunctionWithRequiresUnsafe {
1141 span,
1142 missing_target_features: DiagArgValue::StrListSepByAnd(
1143 missing.iter().map(|feature| Cow::from(feature.to_string())).collect(),
1144 ),
1145 missing_target_features_count: missing.len(),
1146 note: !build_enabled.is_empty(),
1147 build_target_features: DiagArgValue::StrListSepByAnd(
1148 build_enabled
1149 .iter()
1150 .map(|feature| Cow::from(feature.to_string()))
1151 .collect(),
1152 ),
1153 build_target_features_count: build_enabled.len(),
1154 unsafe_not_inherited_note,
1155 function: tcx.def_path_str(*function),
1156 });
1157 }
1158 UnsafeBinderCast if unsafe_op_in_unsafe_fn_allowed => {
1159 dcx.emit_err(UnsafeBinderCastRequiresUnsafeUnsafeOpInUnsafeFnAllowed {
1160 span,
1161 unsafe_not_inherited_note,
1162 });
1163 }
1164 UnsafeBinderCast => {
1165 dcx.emit_err(UnsafeBinderCastRequiresUnsafe { span, unsafe_not_inherited_note });
1166 }
1167 }
1168 }
1169}
1170
1171pub(crate) fn check_unsafety(tcx: TyCtxt<'_>, def: LocalDefId) {
1172 assert!(!tcx.is_typeck_child(def.to_def_id()));
1174 if find_attr!(tcx.get_all_attrs(def), AttributeKind::CustomMir(..) => ()).is_some() {
1176 return;
1177 }
1178
1179 let Ok((thir, expr)) = tcx.thir_body(def) else { return };
1180 tcx.ensure_done().mir_built(def);
1182 let thir = if tcx.sess.opts.unstable_opts.no_steal_thir {
1183 &thir.borrow()
1184 } else {
1185 &thir.steal()
1187 };
1188
1189 let hir_id = tcx.local_def_id_to_hir_id(def);
1190 let safety_context = tcx.hir_fn_sig_by_hir_id(hir_id).map_or(SafetyContext::Safe, |fn_sig| {
1191 match fn_sig.header.safety {
1192 hir::HeaderSafety::SafeTargetFeatures => SafetyContext::Safe,
1196 hir::HeaderSafety::Normal(safety) => match safety {
1197 hir::Safety::Unsafe => SafetyContext::UnsafeFn,
1198 hir::Safety::Safe => SafetyContext::Safe,
1199 },
1200 }
1201 });
1202 let body_target_features = &tcx.body_codegen_attrs(def.to_def_id()).target_features;
1203 let mut warnings = Vec::new();
1204 let mut visitor = UnsafetyVisitor {
1205 tcx,
1206 thir,
1207 safety_context,
1208 hir_context: hir_id,
1209 body_target_features,
1210 assignment_info: None,
1211 in_union_destructure: false,
1212 typing_env: ty::TypingEnv::non_body_analysis(tcx, def),
1214 inside_adt: false,
1215 warnings: &mut warnings,
1216 suggest_unsafe_block: true,
1217 };
1218 for param in &thir.params {
1220 if let Some(param_pat) = param.pat.as_deref() {
1221 visitor.visit_pat(param_pat);
1222 }
1223 }
1224 visitor.visit_expr(&thir[expr]);
1226
1227 warnings.sort_by_key(|w| w.block_span);
1228 for UnusedUnsafeWarning { hir_id, block_span, enclosing_unsafe } in warnings {
1229 let block_span = tcx.sess.source_map().guess_head_span(block_span);
1230 tcx.emit_node_span_lint(
1231 UNUSED_UNSAFE,
1232 hir_id,
1233 block_span,
1234 UnusedUnsafe { span: block_span, enclosing: enclosing_unsafe },
1235 );
1236 }
1237}