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