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