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