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