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