]> git.lizzy.rs Git - rust.git/blob - compiler/rustc_mir_transform/src/check_unsafety.rs
Rollup merge of #93436 - dcsommer:master, r=Mark-Simulacrum
[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::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     /// Mark an `unsafe` block as used, so we don't lint it.
25     used_unsafe: FxHashSet<hir::HirId>,
26     inherited_blocks: Vec<(hir::HirId, bool)>,
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: Default::default(),
44             inherited_blocks: vec![],
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 sig = func_ty.fn_sig(self.tcx);
72                 if let hir::Unsafety::Unsafe = sig.unsafety() {
73                     self.require_unsafe(
74                         UnsafetyViolationKind::General,
75                         UnsafetyViolationDetails::CallToUnsafeFunction,
76                     )
77                 }
78
79                 if let ty::FnDef(func_id, _) = func_ty.kind() {
80                     self.check_target_features(*func_id);
81                 }
82             }
83
84             TerminatorKind::InlineAsm { .. } => self.require_unsafe(
85                 UnsafetyViolationKind::General,
86                 UnsafetyViolationDetails::UseOfInlineAssembly,
87             ),
88         }
89         self.super_terminator(terminator, location);
90     }
91
92     fn visit_statement(&mut self, statement: &Statement<'tcx>, location: Location) {
93         self.source_info = statement.source_info;
94         match statement.kind {
95             StatementKind::Assign(..)
96             | StatementKind::FakeRead(..)
97             | StatementKind::SetDiscriminant { .. }
98             | StatementKind::StorageLive(..)
99             | StatementKind::StorageDead(..)
100             | StatementKind::Retag { .. }
101             | StatementKind::AscribeUserType(..)
102             | StatementKind::Coverage(..)
103             | StatementKind::Nop => {
104                 // safe (at least as emitted during MIR construction)
105             }
106
107             StatementKind::CopyNonOverlapping(..) => unreachable!(),
108         }
109         self.super_statement(statement, location);
110     }
111
112     fn visit_rvalue(&mut self, rvalue: &Rvalue<'tcx>, location: Location) {
113         match rvalue {
114             Rvalue::Aggregate(box ref aggregate, _) => match aggregate {
115                 &AggregateKind::Array(..) | &AggregateKind::Tuple => {}
116                 &AggregateKind::Adt(adt_did, ..) => {
117                     match self.tcx.layout_scalar_valid_range(adt_did) {
118                         (Bound::Unbounded, Bound::Unbounded) => {}
119                         _ => self.require_unsafe(
120                             UnsafetyViolationKind::General,
121                             UnsafetyViolationDetails::InitializingTypeWith,
122                         ),
123                     }
124                 }
125                 &AggregateKind::Closure(def_id, _) | &AggregateKind::Generator(def_id, _, _) => {
126                     let UnsafetyCheckResult { violations, unsafe_blocks } =
127                         self.tcx.unsafety_check_result(def_id.expect_local());
128                     self.register_violations(&violations, &unsafe_blocks);
129                 }
130             },
131             _ => {}
132         }
133         self.super_rvalue(rvalue, location);
134     }
135
136     fn visit_place(&mut self, place: &Place<'tcx>, context: PlaceContext, _location: Location) {
137         // On types with `scalar_valid_range`, prevent
138         // * `&mut x.field`
139         // * `x.field = y;`
140         // * `&x.field` if `field`'s type has interior mutability
141         // because either of these would allow modifying the layout constrained field and
142         // insert values that violate the layout constraints.
143         if context.is_mutating_use() || context.is_borrow() {
144             self.check_mut_borrowing_layout_constrained_field(*place, context.is_mutating_use());
145         }
146
147         // Some checks below need the extra metainfo of the local declaration.
148         let decl = &self.body.local_decls[place.local];
149
150         // Check the base local: it might be an unsafe-to-access static. We only check derefs of the
151         // temporary holding the static pointer to avoid duplicate errors
152         // <https://github.com/rust-lang/rust/pull/78068#issuecomment-731753506>.
153         if decl.internal && place.projection.first() == Some(&ProjectionElem::Deref) {
154             // If the projection root is an artifical local that we introduced when
155             // desugaring `static`, give a more specific error message
156             // (avoid the general "raw pointer" clause below, that would only be confusing).
157             if let Some(box LocalInfo::StaticRef { def_id, .. }) = decl.local_info {
158                 if self.tcx.is_mutable_static(def_id) {
159                     self.require_unsafe(
160                         UnsafetyViolationKind::General,
161                         UnsafetyViolationDetails::UseOfMutableStatic,
162                     );
163                     return;
164                 } else if self.tcx.is_foreign_item(def_id) {
165                     self.require_unsafe(
166                         UnsafetyViolationKind::General,
167                         UnsafetyViolationDetails::UseOfExternStatic,
168                     );
169                     return;
170                 }
171             }
172         }
173
174         // Check for raw pointer `Deref`.
175         for (base, proj) in place.iter_projections() {
176             if proj == ProjectionElem::Deref {
177                 let base_ty = base.ty(self.body, self.tcx).ty;
178                 if base_ty.is_unsafe_ptr() {
179                     self.require_unsafe(
180                         UnsafetyViolationKind::General,
181                         UnsafetyViolationDetails::DerefOfRawPointer,
182                     )
183                 }
184             }
185         }
186
187         // Check for union fields. For this we traverse right-to-left, as the last `Deref` changes
188         // whether we *read* the union field or potentially *write* to it (if this place is being assigned to).
189         let mut saw_deref = false;
190         for (base, proj) in place.iter_projections().rev() {
191             if proj == ProjectionElem::Deref {
192                 saw_deref = true;
193                 continue;
194             }
195
196             let base_ty = base.ty(self.body, self.tcx).ty;
197             if base_ty.is_union() {
198                 // If we did not hit a `Deref` yet and the overall place use is an assignment, the
199                 // rules are different.
200                 let assign_to_field = !saw_deref
201                     && matches!(
202                         context,
203                         PlaceContext::MutatingUse(
204                             MutatingUseContext::Store
205                                 | MutatingUseContext::Drop
206                                 | MutatingUseContext::AsmOutput
207                         )
208                     );
209                 // If this is just an assignment, determine if the assigned type needs dropping.
210                 if assign_to_field {
211                     // We have to check the actual type of the assignment, as that determines if the
212                     // old value is being dropped.
213                     let assigned_ty = place.ty(&self.body.local_decls, self.tcx).ty;
214                     // To avoid semver hazard, we only consider `Copy` and `ManuallyDrop` non-dropping.
215                     let manually_drop = assigned_ty
216                         .ty_adt_def()
217                         .map_or(false, |adt_def| adt_def.is_manually_drop());
218                     let nodrop = manually_drop
219                         || assigned_ty.is_copy_modulo_regions(
220                             self.tcx.at(self.source_info.span),
221                             self.param_env,
222                         );
223                     if !nodrop {
224                         self.require_unsafe(
225                             UnsafetyViolationKind::General,
226                             UnsafetyViolationDetails::AssignToDroppingUnionField,
227                         );
228                     } else {
229                         // write to non-drop union field, safe
230                     }
231                 } else {
232                     self.require_unsafe(
233                         UnsafetyViolationKind::General,
234                         UnsafetyViolationDetails::AccessToUnionField,
235                     )
236                 }
237             }
238         }
239     }
240 }
241
242 impl<'tcx> UnsafetyChecker<'_, 'tcx> {
243     fn require_unsafe(&mut self, kind: UnsafetyViolationKind, details: UnsafetyViolationDetails) {
244         // Violations can turn out to be `UnsafeFn` during analysis, but they should not start out as such.
245         assert_ne!(kind, UnsafetyViolationKind::UnsafeFn);
246
247         let source_info = self.source_info;
248         let lint_root = self.body.source_scopes[self.source_info.scope]
249             .local_data
250             .as_ref()
251             .assert_crate_local()
252             .lint_root;
253         self.register_violations(
254             &[UnsafetyViolation { source_info, lint_root, kind, details }],
255             &[],
256         );
257     }
258
259     fn register_violations(
260         &mut self,
261         violations: &[UnsafetyViolation],
262         unsafe_blocks: &[(hir::HirId, bool)],
263     ) {
264         let safety = self.body.source_scopes[self.source_info.scope]
265             .local_data
266             .as_ref()
267             .assert_crate_local()
268             .safety;
269         let within_unsafe = match safety {
270             // `unsafe` blocks are required in safe code
271             Safety::Safe => {
272                 for violation in violations {
273                     match violation.kind {
274                         UnsafetyViolationKind::General => {}
275                         UnsafetyViolationKind::UnsafeFn => {
276                             bug!("`UnsafetyViolationKind::UnsafeFn` in an `Safe` context")
277                         }
278                     }
279                     if !self.violations.contains(violation) {
280                         self.violations.push(*violation)
281                     }
282                 }
283                 false
284             }
285             // With the RFC 2585, no longer allow `unsafe` operations in `unsafe fn`s
286             Safety::FnUnsafe => {
287                 for violation in violations {
288                     let mut violation = *violation;
289
290                     violation.kind = UnsafetyViolationKind::UnsafeFn;
291                     if !self.violations.contains(&violation) {
292                         self.violations.push(violation)
293                     }
294                 }
295                 false
296             }
297             Safety::BuiltinUnsafe => true,
298             Safety::ExplicitUnsafe(hir_id) => {
299                 // mark unsafe block as used if there are any unsafe operations inside
300                 if !violations.is_empty() {
301                     self.used_unsafe.insert(hir_id);
302                 }
303                 true
304             }
305         };
306         self.inherited_blocks.extend(
307             unsafe_blocks.iter().map(|&(hir_id, is_used)| (hir_id, is_used && !within_unsafe)),
308         );
309     }
310     fn check_mut_borrowing_layout_constrained_field(
311         &mut self,
312         place: Place<'tcx>,
313         is_mut_use: bool,
314     ) {
315         for (place_base, elem) in place.iter_projections().rev() {
316             match elem {
317                 // Modifications behind a dereference don't affect the value of
318                 // the pointer.
319                 ProjectionElem::Deref => return,
320                 ProjectionElem::Field(..) => {
321                     let ty = place_base.ty(&self.body.local_decls, self.tcx).ty;
322                     if let ty::Adt(def, _) = ty.kind() {
323                         if self.tcx.layout_scalar_valid_range(def.did)
324                             != (Bound::Unbounded, Bound::Unbounded)
325                         {
326                             let details = if is_mut_use {
327                                 UnsafetyViolationDetails::MutationOfLayoutConstrainedField
328
329                             // Check `is_freeze` as late as possible to avoid cycle errors
330                             // with opaque types.
331                             } else if !place
332                                 .ty(self.body, self.tcx)
333                                 .ty
334                                 .is_freeze(self.tcx.at(self.source_info.span), self.param_env)
335                             {
336                                 UnsafetyViolationDetails::BorrowOfLayoutConstrainedField
337                             } else {
338                                 continue;
339                             };
340                             self.require_unsafe(UnsafetyViolationKind::General, details);
341                         }
342                     }
343                 }
344                 _ => {}
345             }
346         }
347     }
348
349     /// Checks whether calling `func_did` needs an `unsafe` context or not, i.e. whether
350     /// the called function has target features the calling function hasn't.
351     fn check_target_features(&mut self, func_did: DefId) {
352         // Unsafety isn't required on wasm targets. For more information see
353         // the corresponding check in typeck/src/collect.rs
354         if self.tcx.sess.target.options.is_like_wasm {
355             return;
356         }
357
358         let callee_features = &self.tcx.codegen_fn_attrs(func_did).target_features;
359         let self_features = &self.tcx.codegen_fn_attrs(self.body_did).target_features;
360
361         // Is `callee_features` a subset of `calling_features`?
362         if !callee_features.iter().all(|feature| self_features.contains(feature)) {
363             self.require_unsafe(
364                 UnsafetyViolationKind::General,
365                 UnsafetyViolationDetails::CallToFunctionWith,
366             )
367         }
368     }
369 }
370
371 pub(crate) fn provide(providers: &mut Providers) {
372     *providers = Providers {
373         unsafety_check_result: |tcx, def_id| {
374             if let Some(def) = ty::WithOptConstParam::try_lookup(def_id, tcx) {
375                 tcx.unsafety_check_result_for_const_arg(def)
376             } else {
377                 unsafety_check_result(tcx, ty::WithOptConstParam::unknown(def_id))
378             }
379         },
380         unsafety_check_result_for_const_arg: |tcx, (did, param_did)| {
381             unsafety_check_result(
382                 tcx,
383                 ty::WithOptConstParam { did, const_param_did: Some(param_did) },
384             )
385         },
386         ..*providers
387     };
388 }
389
390 struct UnusedUnsafeVisitor<'a> {
391     used_unsafe: &'a FxHashSet<hir::HirId>,
392     unsafe_blocks: &'a mut Vec<(hir::HirId, bool)>,
393 }
394
395 impl<'tcx> intravisit::Visitor<'tcx> for UnusedUnsafeVisitor<'_> {
396     fn visit_block(&mut self, block: &'tcx hir::Block<'tcx>) {
397         intravisit::walk_block(self, block);
398
399         if let hir::BlockCheckMode::UnsafeBlock(hir::UnsafeSource::UserProvided) = block.rules {
400             self.unsafe_blocks.push((block.hir_id, self.used_unsafe.contains(&block.hir_id)));
401         }
402     }
403 }
404
405 fn check_unused_unsafe(
406     tcx: TyCtxt<'_>,
407     def_id: LocalDefId,
408     used_unsafe: &FxHashSet<hir::HirId>,
409     unsafe_blocks: &mut Vec<(hir::HirId, bool)>,
410 ) {
411     let body_id = tcx.hir().maybe_body_owned_by(tcx.hir().local_def_id_to_hir_id(def_id));
412
413     let body_id = match body_id {
414         Some(body) => body,
415         None => {
416             debug!("check_unused_unsafe({:?}) - no body found", def_id);
417             return;
418         }
419     };
420     let body = tcx.hir().body(body_id);
421     debug!("check_unused_unsafe({:?}, body={:?}, used_unsafe={:?})", def_id, body, used_unsafe);
422
423     let mut visitor = UnusedUnsafeVisitor { used_unsafe, unsafe_blocks };
424     intravisit::Visitor::visit_body(&mut visitor, body);
425 }
426
427 fn unsafety_check_result<'tcx>(
428     tcx: TyCtxt<'tcx>,
429     def: ty::WithOptConstParam<LocalDefId>,
430 ) -> &'tcx UnsafetyCheckResult {
431     debug!("unsafety_violations({:?})", def);
432
433     // N.B., this borrow is valid because all the consumers of
434     // `mir_built` force this.
435     let body = &tcx.mir_built(def).borrow();
436
437     let param_env = tcx.param_env(def.did);
438
439     let mut checker = UnsafetyChecker::new(body, def.did, tcx, param_env);
440     checker.visit_body(&body);
441
442     check_unused_unsafe(tcx, def.did, &checker.used_unsafe, &mut checker.inherited_blocks);
443
444     tcx.arena.alloc(UnsafetyCheckResult {
445         violations: checker.violations.into(),
446         unsafe_blocks: checker.inherited_blocks.into(),
447     })
448 }
449
450 /// Returns the `HirId` for an enclosing scope that is also `unsafe`.
451 fn is_enclosed(
452     tcx: TyCtxt<'_>,
453     used_unsafe: &FxHashSet<hir::HirId>,
454     id: hir::HirId,
455     unsafe_op_in_unsafe_fn_allowed: bool,
456 ) -> Option<(&'static str, hir::HirId)> {
457     let parent_id = tcx.hir().get_parent_node(id);
458     if parent_id != id {
459         if used_unsafe.contains(&parent_id) {
460             Some(("block", parent_id))
461         } else if let Some(Node::Item(&hir::Item {
462             kind: hir::ItemKind::Fn(ref sig, _, _), ..
463         })) = tcx.hir().find(parent_id)
464         {
465             if sig.header.unsafety == hir::Unsafety::Unsafe && unsafe_op_in_unsafe_fn_allowed {
466                 Some(("fn", parent_id))
467             } else {
468                 None
469             }
470         } else {
471             is_enclosed(tcx, used_unsafe, parent_id, unsafe_op_in_unsafe_fn_allowed)
472         }
473     } else {
474         None
475     }
476 }
477
478 fn report_unused_unsafe(tcx: TyCtxt<'_>, used_unsafe: &FxHashSet<hir::HirId>, id: hir::HirId) {
479     let span = tcx.sess.source_map().guess_head_span(tcx.hir().span(id));
480     tcx.struct_span_lint_hir(UNUSED_UNSAFE, id, span, |lint| {
481         let msg = "unnecessary `unsafe` block";
482         let mut db = lint.build(msg);
483         db.span_label(span, msg);
484         if let Some((kind, id)) =
485             is_enclosed(tcx, used_unsafe, id, unsafe_op_in_unsafe_fn_allowed(tcx, id))
486         {
487             db.span_label(
488                 tcx.sess.source_map().guess_head_span(tcx.hir().span(id)),
489                 format!("because it's nested under this `unsafe` {}", kind),
490             );
491         }
492         db.emit();
493     });
494 }
495
496 pub fn check_unsafety(tcx: TyCtxt<'_>, def_id: LocalDefId) {
497     debug!("check_unsafety({:?})", def_id);
498
499     // closures are handled by their parent fn.
500     if tcx.is_closure(def_id.to_def_id()) {
501         return;
502     }
503
504     let UnsafetyCheckResult { violations, unsafe_blocks } = tcx.unsafety_check_result(def_id);
505
506     for &UnsafetyViolation { source_info, lint_root, kind, details } in violations.iter() {
507         let (description, note) = details.description_and_note();
508
509         // Report an error.
510         let unsafe_fn_msg =
511             if unsafe_op_in_unsafe_fn_allowed(tcx, lint_root) { " function or" } else { "" };
512
513         match kind {
514             UnsafetyViolationKind::General => {
515                 // once
516                 struct_span_err!(
517                     tcx.sess,
518                     source_info.span,
519                     E0133,
520                     "{} is unsafe and requires unsafe{} block",
521                     description,
522                     unsafe_fn_msg,
523                 )
524                 .span_label(source_info.span, description)
525                 .note(note)
526                 .emit();
527             }
528             UnsafetyViolationKind::UnsafeFn => tcx.struct_span_lint_hir(
529                 UNSAFE_OP_IN_UNSAFE_FN,
530                 lint_root,
531                 source_info.span,
532                 |lint| {
533                     lint.build(&format!(
534                         "{} is unsafe and requires unsafe block (error E0133)",
535                         description,
536                     ))
537                     .span_label(source_info.span, description)
538                     .note(note)
539                     .emit();
540                 },
541             ),
542         }
543     }
544
545     let (mut unsafe_used, mut unsafe_unused): (FxHashSet<_>, Vec<_>) = Default::default();
546     for &(block_id, is_used) in unsafe_blocks.iter() {
547         if is_used {
548             unsafe_used.insert(block_id);
549         } else {
550             unsafe_unused.push(block_id);
551         }
552     }
553     // The unused unsafe blocks might not be in source order; sort them so that the unused unsafe
554     // error messages are properly aligned and the issue-45107 and lint-unused-unsafe tests pass.
555     unsafe_unused.sort_by_cached_key(|hir_id| tcx.hir().span(*hir_id));
556
557     for &block_id in &unsafe_unused {
558         report_unused_unsafe(tcx, &unsafe_used, block_id);
559     }
560 }
561
562 fn unsafe_op_in_unsafe_fn_allowed(tcx: TyCtxt<'_>, id: HirId) -> bool {
563     tcx.lint_level_at_node(UNSAFE_OP_IN_UNSAFE_FN, id).0 == Level::Allow
564 }