]> git.lizzy.rs Git - rust.git/blob - compiler/rustc_mir_transform/src/check_unsafety.rs
Rollup merge of #104822 - spastorino:selctx-new-instead-of-with_query_mode, r=lcnr
[rust.git] / compiler / rustc_mir_transform / src / check_unsafety.rs
1 use rustc_data_structures::fx::FxHashSet;
2 use rustc_errors::struct_span_err;
3 use rustc_hir as hir;
4 use rustc_hir::def_id::{DefId, LocalDefId};
5 use rustc_hir::hir_id::HirId;
6 use rustc_hir::intravisit;
7 use rustc_hir::{BlockCheckMode, ExprKind, Node};
8 use rustc_middle::mir::visit::{MutatingUseContext, PlaceContext, Visitor};
9 use rustc_middle::mir::*;
10 use rustc_middle::ty::query::Providers;
11 use rustc_middle::ty::{self, TyCtxt};
12 use rustc_session::lint::builtin::{UNSAFE_OP_IN_UNSAFE_FN, UNUSED_UNSAFE};
13 use rustc_session::lint::Level;
14
15 use std::ops::Bound;
16
17 pub struct UnsafetyChecker<'a, 'tcx> {
18     body: &'a Body<'tcx>,
19     body_did: LocalDefId,
20     violations: Vec<UnsafetyViolation>,
21     source_info: SourceInfo,
22     tcx: TyCtxt<'tcx>,
23     param_env: ty::ParamEnv<'tcx>,
24
25     /// Used `unsafe` blocks in this function. This is used for the "unused_unsafe" lint.
26     used_unsafe_blocks: FxHashSet<HirId>,
27 }
28
29 impl<'a, 'tcx> UnsafetyChecker<'a, 'tcx> {
30     fn new(
31         body: &'a Body<'tcx>,
32         body_did: LocalDefId,
33         tcx: TyCtxt<'tcx>,
34         param_env: ty::ParamEnv<'tcx>,
35     ) -> Self {
36         Self {
37             body,
38             body_did,
39             violations: vec![],
40             source_info: SourceInfo::outermost(body.span),
41             tcx,
42             param_env,
43             used_unsafe_blocks: Default::default(),
44         }
45     }
46 }
47
48 impl<'tcx> Visitor<'tcx> for UnsafetyChecker<'_, 'tcx> {
49     fn visit_terminator(&mut self, terminator: &Terminator<'tcx>, location: Location) {
50         self.source_info = terminator.source_info;
51         match terminator.kind {
52             TerminatorKind::Goto { .. }
53             | TerminatorKind::SwitchInt { .. }
54             | TerminatorKind::Drop { .. }
55             | TerminatorKind::Yield { .. }
56             | TerminatorKind::Assert { .. }
57             | TerminatorKind::DropAndReplace { .. }
58             | TerminatorKind::GeneratorDrop
59             | TerminatorKind::Resume
60             | TerminatorKind::Abort
61             | TerminatorKind::Return
62             | TerminatorKind::Unreachable
63             | TerminatorKind::FalseEdge { .. }
64             | TerminatorKind::FalseUnwind { .. } => {
65                 // safe (at least as emitted during MIR construction)
66             }
67
68             TerminatorKind::Call { ref func, .. } => {
69                 let func_ty = func.ty(self.body, self.tcx);
70                 let func_id =
71                     if let ty::FnDef(func_id, _) = func_ty.kind() { Some(func_id) } else { None };
72                 let sig = func_ty.fn_sig(self.tcx);
73                 if let hir::Unsafety::Unsafe = sig.unsafety() {
74                     self.require_unsafe(
75                         UnsafetyViolationKind::General,
76                         UnsafetyViolationDetails::CallToUnsafeFunction,
77                     )
78                 }
79
80                 if let Some(func_id) = func_id {
81                     self.check_target_features(*func_id);
82                 }
83             }
84
85             TerminatorKind::InlineAsm { .. } => self.require_unsafe(
86                 UnsafetyViolationKind::General,
87                 UnsafetyViolationDetails::UseOfInlineAssembly,
88             ),
89         }
90         self.super_terminator(terminator, location);
91     }
92
93     fn visit_statement(&mut self, statement: &Statement<'tcx>, location: Location) {
94         self.source_info = statement.source_info;
95         match statement.kind {
96             StatementKind::Assign(..)
97             | StatementKind::FakeRead(..)
98             | StatementKind::SetDiscriminant { .. }
99             | StatementKind::Deinit(..)
100             | StatementKind::StorageLive(..)
101             | StatementKind::StorageDead(..)
102             | StatementKind::Retag { .. }
103             | StatementKind::AscribeUserType(..)
104             | StatementKind::Coverage(..)
105             | StatementKind::Intrinsic(..)
106             | StatementKind::Nop => {
107                 // safe (at least as emitted during MIR construction)
108             }
109         }
110         self.super_statement(statement, location);
111     }
112
113     fn visit_rvalue(&mut self, rvalue: &Rvalue<'tcx>, location: Location) {
114         match rvalue {
115             Rvalue::Aggregate(box ref aggregate, _) => match aggregate {
116                 &AggregateKind::Array(..) | &AggregateKind::Tuple => {}
117                 &AggregateKind::Adt(adt_did, ..) => {
118                     match self.tcx.layout_scalar_valid_range(adt_did) {
119                         (Bound::Unbounded, Bound::Unbounded) => {}
120                         _ => self.require_unsafe(
121                             UnsafetyViolationKind::General,
122                             UnsafetyViolationDetails::InitializingTypeWith,
123                         ),
124                     }
125                 }
126                 &AggregateKind::Closure(def_id, _) | &AggregateKind::Generator(def_id, _, _) => {
127                     let UnsafetyCheckResult { violations, used_unsafe_blocks, .. } =
128                         self.tcx.unsafety_check_result(def_id);
129                     self.register_violations(violations, used_unsafe_blocks.iter().copied());
130                 }
131             },
132             _ => {}
133         }
134         self.super_rvalue(rvalue, location);
135     }
136
137     fn visit_place(&mut self, place: &Place<'tcx>, context: PlaceContext, _location: Location) {
138         // On types with `scalar_valid_range`, prevent
139         // * `&mut x.field`
140         // * `x.field = y;`
141         // * `&x.field` if `field`'s type has interior mutability
142         // because either of these would allow modifying the layout constrained field and
143         // insert values that violate the layout constraints.
144         if context.is_mutating_use() || context.is_borrow() {
145             self.check_mut_borrowing_layout_constrained_field(*place, context.is_mutating_use());
146         }
147
148         // Some checks below need the extra meta info of the local declaration.
149         let decl = &self.body.local_decls[place.local];
150
151         // Check the base local: it might be an unsafe-to-access static. We only check derefs of the
152         // temporary holding the static pointer to avoid duplicate errors
153         // <https://github.com/rust-lang/rust/pull/78068#issuecomment-731753506>.
154         if decl.internal && place.projection.first() == Some(&ProjectionElem::Deref) {
155             // If the projection root is an artificial local that we introduced when
156             // desugaring `static`, give a more specific error message
157             // (avoid the general "raw pointer" clause below, that would only be confusing).
158             if let Some(box LocalInfo::StaticRef { def_id, .. }) = decl.local_info {
159                 if self.tcx.is_mutable_static(def_id) {
160                     self.require_unsafe(
161                         UnsafetyViolationKind::General,
162                         UnsafetyViolationDetails::UseOfMutableStatic,
163                     );
164                     return;
165                 } else if self.tcx.is_foreign_item(def_id) {
166                     self.require_unsafe(
167                         UnsafetyViolationKind::General,
168                         UnsafetyViolationDetails::UseOfExternStatic,
169                     );
170                     return;
171                 }
172             }
173         }
174
175         // Check for raw pointer `Deref`.
176         for (base, proj) in place.iter_projections() {
177             if proj == ProjectionElem::Deref {
178                 let base_ty = base.ty(self.body, self.tcx).ty;
179                 if base_ty.is_unsafe_ptr() {
180                     self.require_unsafe(
181                         UnsafetyViolationKind::General,
182                         UnsafetyViolationDetails::DerefOfRawPointer,
183                     )
184                 }
185             }
186         }
187
188         // Check for union fields. For this we traverse right-to-left, as the last `Deref` changes
189         // whether we *read* the union field or potentially *write* to it (if this place is being assigned to).
190         let mut saw_deref = false;
191         for (base, proj) in place.iter_projections().rev() {
192             if proj == ProjectionElem::Deref {
193                 saw_deref = true;
194                 continue;
195             }
196
197             let base_ty = base.ty(self.body, self.tcx).ty;
198             if base_ty.is_union() {
199                 // If we did not hit a `Deref` yet and the overall place use is an assignment, the
200                 // rules are different.
201                 let assign_to_field = !saw_deref
202                     && matches!(
203                         context,
204                         PlaceContext::MutatingUse(
205                             MutatingUseContext::Store
206                                 | MutatingUseContext::Drop
207                                 | MutatingUseContext::AsmOutput
208                         )
209                     );
210                 // If this is just an assignment, determine if the assigned type needs dropping.
211                 if assign_to_field {
212                     // We have to check the actual type of the assignment, as that determines if the
213                     // old value is being dropped.
214                     let assigned_ty = place.ty(&self.body.local_decls, self.tcx).ty;
215                     if assigned_ty.needs_drop(self.tcx, self.param_env) {
216                         // This would be unsafe, but should be outright impossible since we reject such unions.
217                         self.tcx.sess.delay_span_bug(
218                             self.source_info.span,
219                             format!("union fields that need dropping should be impossible: {assigned_ty}")
220                         );
221                     }
222                 } else {
223                     self.require_unsafe(
224                         UnsafetyViolationKind::General,
225                         UnsafetyViolationDetails::AccessToUnionField,
226                     )
227                 }
228             }
229         }
230     }
231 }
232
233 impl<'tcx> UnsafetyChecker<'_, 'tcx> {
234     fn require_unsafe(&mut self, kind: UnsafetyViolationKind, details: UnsafetyViolationDetails) {
235         // Violations can turn out to be `UnsafeFn` during analysis, but they should not start out as such.
236         assert_ne!(kind, UnsafetyViolationKind::UnsafeFn);
237
238         let source_info = self.source_info;
239         let lint_root = self.body.source_scopes[self.source_info.scope]
240             .local_data
241             .as_ref()
242             .assert_crate_local()
243             .lint_root;
244         self.register_violations(
245             [&UnsafetyViolation { source_info, lint_root, kind, details }],
246             [],
247         );
248     }
249
250     fn register_violations<'a>(
251         &mut self,
252         violations: impl IntoIterator<Item = &'a UnsafetyViolation>,
253         new_used_unsafe_blocks: impl IntoIterator<Item = HirId>,
254     ) {
255         let safety = self.body.source_scopes[self.source_info.scope]
256             .local_data
257             .as_ref()
258             .assert_crate_local()
259             .safety;
260         match safety {
261             // `unsafe` blocks are required in safe code
262             Safety::Safe => violations.into_iter().for_each(|&violation| {
263                 match violation.kind {
264                     UnsafetyViolationKind::General => {}
265                     UnsafetyViolationKind::UnsafeFn => {
266                         bug!("`UnsafetyViolationKind::UnsafeFn` in an `Safe` context")
267                     }
268                 }
269                 if !self.violations.contains(&violation) {
270                     self.violations.push(violation)
271                 }
272             }),
273             // With the RFC 2585, no longer allow `unsafe` operations in `unsafe fn`s
274             Safety::FnUnsafe => violations.into_iter().for_each(|&(mut violation)| {
275                 violation.kind = UnsafetyViolationKind::UnsafeFn;
276                 if !self.violations.contains(&violation) {
277                     self.violations.push(violation)
278                 }
279             }),
280             Safety::BuiltinUnsafe => {}
281             Safety::ExplicitUnsafe(hir_id) => violations.into_iter().for_each(|_violation| {
282                 self.used_unsafe_blocks.insert(hir_id);
283             }),
284         };
285
286         new_used_unsafe_blocks.into_iter().for_each(|hir_id| {
287             self.used_unsafe_blocks.insert(hir_id);
288         });
289     }
290     fn check_mut_borrowing_layout_constrained_field(
291         &mut self,
292         place: Place<'tcx>,
293         is_mut_use: bool,
294     ) {
295         for (place_base, elem) in place.iter_projections().rev() {
296             match elem {
297                 // Modifications behind a dereference don't affect the value of
298                 // the pointer.
299                 ProjectionElem::Deref => return,
300                 ProjectionElem::Field(..) => {
301                     let ty = place_base.ty(&self.body.local_decls, self.tcx).ty;
302                     if let ty::Adt(def, _) = ty.kind() {
303                         if self.tcx.layout_scalar_valid_range(def.did())
304                             != (Bound::Unbounded, Bound::Unbounded)
305                         {
306                             let details = if is_mut_use {
307                                 UnsafetyViolationDetails::MutationOfLayoutConstrainedField
308
309                             // Check `is_freeze` as late as possible to avoid cycle errors
310                             // with opaque types.
311                             } else if !place
312                                 .ty(self.body, self.tcx)
313                                 .ty
314                                 .is_freeze(self.tcx, self.param_env)
315                             {
316                                 UnsafetyViolationDetails::BorrowOfLayoutConstrainedField
317                             } else {
318                                 continue;
319                             };
320                             self.require_unsafe(UnsafetyViolationKind::General, details);
321                         }
322                     }
323                 }
324                 _ => {}
325             }
326         }
327     }
328
329     /// Checks whether calling `func_did` needs an `unsafe` context or not, i.e. whether
330     /// the called function has target features the calling function hasn't.
331     fn check_target_features(&mut self, func_did: DefId) {
332         // Unsafety isn't required on wasm targets. For more information see
333         // the corresponding check in typeck/src/collect.rs
334         if self.tcx.sess.target.options.is_like_wasm {
335             return;
336         }
337
338         let callee_features = &self.tcx.codegen_fn_attrs(func_did).target_features;
339         // The body might be a constant, so it doesn't have codegen attributes.
340         let self_features = &self.tcx.body_codegen_attrs(self.body_did.to_def_id()).target_features;
341
342         // Is `callee_features` a subset of `calling_features`?
343         if !callee_features.iter().all(|feature| self_features.contains(feature)) {
344             self.require_unsafe(
345                 UnsafetyViolationKind::General,
346                 UnsafetyViolationDetails::CallToFunctionWith,
347             )
348         }
349     }
350 }
351
352 pub(crate) fn provide(providers: &mut Providers) {
353     *providers = Providers {
354         unsafety_check_result: |tcx, def_id| {
355             if let Some(def) = ty::WithOptConstParam::try_lookup(def_id, tcx) {
356                 tcx.unsafety_check_result_for_const_arg(def)
357             } else {
358                 unsafety_check_result(tcx, ty::WithOptConstParam::unknown(def_id))
359             }
360         },
361         unsafety_check_result_for_const_arg: |tcx, (did, param_did)| {
362             unsafety_check_result(
363                 tcx,
364                 ty::WithOptConstParam { did, const_param_did: Some(param_did) },
365             )
366         },
367         ..*providers
368     };
369 }
370
371 /// Context information for [`UnusedUnsafeVisitor`] traversal,
372 /// saves (innermost) relevant context
373 #[derive(Copy, Clone, Debug)]
374 enum Context {
375     Safe,
376     /// in an `unsafe fn`
377     UnsafeFn(HirId),
378     /// in a *used* `unsafe` block
379     /// (i.e. a block without unused-unsafe warning)
380     UnsafeBlock(HirId),
381 }
382
383 struct UnusedUnsafeVisitor<'a, 'tcx> {
384     tcx: TyCtxt<'tcx>,
385     used_unsafe_blocks: &'a FxHashSet<HirId>,
386     context: Context,
387     unused_unsafes: &'a mut Vec<(HirId, UnusedUnsafe)>,
388 }
389
390 impl<'tcx> intravisit::Visitor<'tcx> for UnusedUnsafeVisitor<'_, 'tcx> {
391     fn visit_block(&mut self, block: &'tcx hir::Block<'tcx>) {
392         if let hir::BlockCheckMode::UnsafeBlock(hir::UnsafeSource::UserProvided) = block.rules {
393             let used = match self.tcx.lint_level_at_node(UNUSED_UNSAFE, block.hir_id) {
394                 (Level::Allow, _) => true,
395                 _ => self.used_unsafe_blocks.contains(&block.hir_id),
396             };
397             let unused_unsafe = match (self.context, used) {
398                 (_, false) => UnusedUnsafe::Unused,
399                 (Context::Safe, true) | (Context::UnsafeFn(_), true) => {
400                     let previous_context = self.context;
401                     self.context = Context::UnsafeBlock(block.hir_id);
402                     intravisit::walk_block(self, block);
403                     self.context = previous_context;
404                     return;
405                 }
406                 (Context::UnsafeBlock(hir_id), true) => UnusedUnsafe::InUnsafeBlock(hir_id),
407             };
408             self.unused_unsafes.push((block.hir_id, unused_unsafe));
409         }
410         intravisit::walk_block(self, block);
411     }
412
413     fn visit_fn(
414         &mut self,
415         fk: intravisit::FnKind<'tcx>,
416         _fd: &'tcx hir::FnDecl<'tcx>,
417         b: hir::BodyId,
418         _s: rustc_span::Span,
419         _id: HirId,
420     ) {
421         if matches!(fk, intravisit::FnKind::Closure) {
422             self.visit_body(self.tcx.hir().body(b))
423         }
424     }
425 }
426
427 fn check_unused_unsafe(
428     tcx: TyCtxt<'_>,
429     def_id: LocalDefId,
430     used_unsafe_blocks: &FxHashSet<HirId>,
431 ) -> Vec<(HirId, UnusedUnsafe)> {
432     let body_id = tcx.hir().maybe_body_owned_by(def_id);
433
434     let Some(body_id) = body_id else {
435         debug!("check_unused_unsafe({:?}) - no body found", def_id);
436         return vec![];
437     };
438
439     let body = tcx.hir().body(body_id);
440     let hir_id = tcx.hir().local_def_id_to_hir_id(def_id);
441     let context = match tcx.hir().fn_sig_by_hir_id(hir_id) {
442         Some(sig) if sig.header.unsafety == hir::Unsafety::Unsafe => Context::UnsafeFn(hir_id),
443         _ => Context::Safe,
444     };
445
446     debug!(
447         "check_unused_unsafe({:?}, context={:?}, body={:?}, used_unsafe_blocks={:?})",
448         def_id, body, context, used_unsafe_blocks
449     );
450
451     let mut unused_unsafes = vec![];
452
453     let mut visitor = UnusedUnsafeVisitor {
454         tcx,
455         used_unsafe_blocks,
456         context,
457         unused_unsafes: &mut unused_unsafes,
458     };
459     intravisit::Visitor::visit_body(&mut visitor, body);
460
461     unused_unsafes
462 }
463
464 fn unsafety_check_result<'tcx>(
465     tcx: TyCtxt<'tcx>,
466     def: ty::WithOptConstParam<LocalDefId>,
467 ) -> &'tcx UnsafetyCheckResult {
468     debug!("unsafety_violations({:?})", def);
469
470     // N.B., this borrow is valid because all the consumers of
471     // `mir_built` force this.
472     let body = &tcx.mir_built(def).borrow();
473
474     if body.should_skip() {
475         return tcx.arena.alloc(UnsafetyCheckResult {
476             violations: Vec::new(),
477             used_unsafe_blocks: FxHashSet::default(),
478             unused_unsafes: Some(Vec::new()),
479         });
480     }
481
482     let param_env = tcx.param_env(def.did);
483
484     let mut checker = UnsafetyChecker::new(body, def.did, tcx, param_env);
485     checker.visit_body(&body);
486
487     let unused_unsafes = (!tcx.is_closure(def.did.to_def_id()))
488         .then(|| check_unused_unsafe(tcx, def.did, &checker.used_unsafe_blocks));
489
490     tcx.arena.alloc(UnsafetyCheckResult {
491         violations: checker.violations,
492         used_unsafe_blocks: checker.used_unsafe_blocks,
493         unused_unsafes,
494     })
495 }
496
497 fn report_unused_unsafe(tcx: TyCtxt<'_>, kind: UnusedUnsafe, id: HirId) {
498     let span = tcx.sess.source_map().guess_head_span(tcx.hir().span(id));
499     let msg = "unnecessary `unsafe` block";
500     tcx.struct_span_lint_hir(UNUSED_UNSAFE, id, span, msg, |lint| {
501         lint.span_label(span, msg);
502         match kind {
503             UnusedUnsafe::Unused => {}
504             UnusedUnsafe::InUnsafeBlock(id) => {
505                 lint.span_label(
506                     tcx.sess.source_map().guess_head_span(tcx.hir().span(id)),
507                     "because it's nested under this `unsafe` block",
508                 );
509             }
510         }
511
512         lint
513     });
514 }
515
516 pub fn check_unsafety(tcx: TyCtxt<'_>, def_id: LocalDefId) {
517     debug!("check_unsafety({:?})", def_id);
518
519     // closures are handled by their parent fn.
520     if tcx.is_closure(def_id.to_def_id()) {
521         return;
522     }
523
524     let UnsafetyCheckResult { violations, unused_unsafes, .. } = tcx.unsafety_check_result(def_id);
525
526     for &UnsafetyViolation { source_info, lint_root, kind, details } in violations.iter() {
527         let (description, note) = details.description_and_note();
528
529         match kind {
530             UnsafetyViolationKind::General => {
531                 // once
532                 let unsafe_fn_msg = if unsafe_op_in_unsafe_fn_allowed(tcx, lint_root) {
533                     " function or"
534                 } else {
535                     ""
536                 };
537
538                 let mut err = struct_span_err!(
539                     tcx.sess,
540                     source_info.span,
541                     E0133,
542                     "{} is unsafe and requires unsafe{} block",
543                     description,
544                     unsafe_fn_msg,
545                 );
546                 err.span_label(source_info.span, description).note(note);
547                 let note_non_inherited = tcx.hir().parent_iter(lint_root).find(|(id, node)| {
548                     if let Node::Expr(block) = node
549                         && let ExprKind::Block(block, _) = block.kind
550                         && let BlockCheckMode::UnsafeBlock(_) = block.rules
551                     {
552                         true
553                     }
554                     else if let Some(sig) = tcx.hir().fn_sig_by_hir_id(*id)
555                         && sig.header.is_unsafe()
556                     {
557                         true
558                     } else {
559                         false
560                     }
561                 });
562                 if let Some((id, _)) = note_non_inherited {
563                     let span = tcx.hir().span(id);
564                     err.span_label(
565                         tcx.sess.source_map().guess_head_span(span),
566                         "items do not inherit unsafety from separate enclosing items",
567                     );
568                 }
569
570                 err.emit();
571             }
572             UnsafetyViolationKind::UnsafeFn => tcx.struct_span_lint_hir(
573                 UNSAFE_OP_IN_UNSAFE_FN,
574                 lint_root,
575                 source_info.span,
576                 format!("{} is unsafe and requires unsafe block (error E0133)", description,),
577                 |lint| lint.span_label(source_info.span, description).note(note),
578             ),
579         }
580     }
581
582     for &(block_id, kind) in unused_unsafes.as_ref().unwrap() {
583         report_unused_unsafe(tcx, kind, block_id);
584     }
585 }
586
587 fn unsafe_op_in_unsafe_fn_allowed(tcx: TyCtxt<'_>, id: HirId) -> bool {
588     tcx.lint_level_at_node(UNSAFE_OP_IN_UNSAFE_FN, id).0 == Level::Allow
589 }