]> git.lizzy.rs Git - rust.git/blob - compiler/rustc_mir/src/transform/check_unsafety.rs
Remove some last remants of {push,pop}_unsafe!
[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::ExplicitUnsafe(hir_id) => {
325                 // mark unsafe block as used if there are any unsafe operations inside
326                 if !violations.is_empty() {
327                     self.used_unsafe.insert(hir_id);
328                 }
329                 true
330             }
331         };
332         self.inherited_blocks.extend(
333             unsafe_blocks.iter().map(|&(hir_id, is_used)| (hir_id, is_used && !within_unsafe)),
334         );
335     }
336     fn check_mut_borrowing_layout_constrained_field(
337         &mut self,
338         place: Place<'tcx>,
339         is_mut_use: bool,
340     ) {
341         for (place_base, elem) in place.iter_projections().rev() {
342             match elem {
343                 // Modifications behind a dereference don't affect the value of
344                 // the pointer.
345                 ProjectionElem::Deref => return,
346                 ProjectionElem::Field(..) => {
347                     let ty = place_base.ty(&self.body.local_decls, self.tcx).ty;
348                     if let ty::Adt(def, _) = ty.kind() {
349                         if self.tcx.layout_scalar_valid_range(def.did)
350                             != (Bound::Unbounded, Bound::Unbounded)
351                         {
352                             let details = if is_mut_use {
353                                 UnsafetyViolationDetails::MutationOfLayoutConstrainedField
354
355                             // Check `is_freeze` as late as possible to avoid cycle errors
356                             // with opaque types.
357                             } else if !place
358                                 .ty(self.body, self.tcx)
359                                 .ty
360                                 .is_freeze(self.tcx.at(self.source_info.span), self.param_env)
361                             {
362                                 UnsafetyViolationDetails::BorrowOfLayoutConstrainedField
363                             } else {
364                                 continue;
365                             };
366                             self.require_unsafe(UnsafetyViolationKind::General, details);
367                         }
368                     }
369                 }
370                 _ => {}
371             }
372         }
373     }
374
375     /// Checks whether calling `func_did` needs an `unsafe` context or not, i.e. whether
376     /// the called function has target features the calling function hasn't.
377     fn check_target_features(&mut self, func_did: DefId) {
378         // Unsafety isn't required on wasm targets. For more information see
379         // the corresponding check in typeck/src/collect.rs
380         if self.tcx.sess.target.options.is_like_wasm {
381             return;
382         }
383
384         let callee_features = &self.tcx.codegen_fn_attrs(func_did).target_features;
385         let self_features = &self.tcx.codegen_fn_attrs(self.body_did).target_features;
386
387         // Is `callee_features` a subset of `calling_features`?
388         if !callee_features.iter().all(|feature| self_features.contains(feature)) {
389             self.require_unsafe(
390                 UnsafetyViolationKind::General,
391                 UnsafetyViolationDetails::CallToFunctionWith,
392             )
393         }
394     }
395 }
396
397 pub(crate) fn provide(providers: &mut Providers) {
398     *providers = Providers {
399         unsafety_check_result: |tcx, def_id| {
400             if let Some(def) = ty::WithOptConstParam::try_lookup(def_id, tcx) {
401                 tcx.unsafety_check_result_for_const_arg(def)
402             } else {
403                 unsafety_check_result(tcx, ty::WithOptConstParam::unknown(def_id))
404             }
405         },
406         unsafety_check_result_for_const_arg: |tcx, (did, param_did)| {
407             unsafety_check_result(
408                 tcx,
409                 ty::WithOptConstParam { did, const_param_did: Some(param_did) },
410             )
411         },
412         ..*providers
413     };
414 }
415
416 struct UnusedUnsafeVisitor<'a> {
417     used_unsafe: &'a FxHashSet<hir::HirId>,
418     unsafe_blocks: &'a mut Vec<(hir::HirId, bool)>,
419 }
420
421 impl<'a, 'tcx> intravisit::Visitor<'tcx> for UnusedUnsafeVisitor<'a> {
422     type Map = intravisit::ErasedMap<'tcx>;
423
424     fn nested_visit_map(&mut self) -> intravisit::NestedVisitorMap<Self::Map> {
425         intravisit::NestedVisitorMap::None
426     }
427
428     fn visit_block(&mut self, block: &'tcx hir::Block<'tcx>) {
429         intravisit::walk_block(self, block);
430
431         if let hir::BlockCheckMode::UnsafeBlock(hir::UnsafeSource::UserProvided) = block.rules {
432             self.unsafe_blocks.push((block.hir_id, self.used_unsafe.contains(&block.hir_id)));
433         }
434     }
435 }
436
437 fn check_unused_unsafe(
438     tcx: TyCtxt<'_>,
439     def_id: LocalDefId,
440     used_unsafe: &FxHashSet<hir::HirId>,
441     unsafe_blocks: &mut Vec<(hir::HirId, bool)>,
442 ) {
443     let body_id = tcx.hir().maybe_body_owned_by(tcx.hir().local_def_id_to_hir_id(def_id));
444
445     let body_id = match body_id {
446         Some(body) => body,
447         None => {
448             debug!("check_unused_unsafe({:?}) - no body found", def_id);
449             return;
450         }
451     };
452     let body = tcx.hir().body(body_id);
453     debug!("check_unused_unsafe({:?}, body={:?}, used_unsafe={:?})", def_id, body, used_unsafe);
454
455     let mut visitor = UnusedUnsafeVisitor { used_unsafe, unsafe_blocks };
456     intravisit::Visitor::visit_body(&mut visitor, body);
457 }
458
459 fn unsafety_check_result<'tcx>(
460     tcx: TyCtxt<'tcx>,
461     def: ty::WithOptConstParam<LocalDefId>,
462 ) -> &'tcx UnsafetyCheckResult {
463     debug!("unsafety_violations({:?})", def);
464
465     // N.B., this borrow is valid because all the consumers of
466     // `mir_built` force this.
467     let body = &tcx.mir_built(def).borrow();
468
469     let param_env = tcx.param_env(def.did);
470
471     let id = tcx.hir().local_def_id_to_hir_id(def.did);
472     let const_context = match tcx.hir().body_owner_kind(id) {
473         hir::BodyOwnerKind::Closure => false,
474         hir::BodyOwnerKind::Fn => tcx.is_const_fn_raw(def.did.to_def_id()),
475         hir::BodyOwnerKind::Const | hir::BodyOwnerKind::Static(_) => true,
476     };
477     let mut checker = UnsafetyChecker::new(const_context, body, def.did, tcx, param_env);
478     checker.visit_body(&body);
479
480     check_unused_unsafe(tcx, def.did, &checker.used_unsafe, &mut checker.inherited_blocks);
481
482     tcx.arena.alloc(UnsafetyCheckResult {
483         violations: checker.violations.into(),
484         unsafe_blocks: checker.inherited_blocks.into(),
485     })
486 }
487
488 /// Returns the `HirId` for an enclosing scope that is also `unsafe`.
489 fn is_enclosed(
490     tcx: TyCtxt<'_>,
491     used_unsafe: &FxHashSet<hir::HirId>,
492     id: hir::HirId,
493     unsafe_op_in_unsafe_fn_allowed: bool,
494 ) -> Option<(&'static str, hir::HirId)> {
495     let parent_id = tcx.hir().get_parent_node(id);
496     if parent_id != id {
497         if used_unsafe.contains(&parent_id) {
498             Some(("block", parent_id))
499         } else if let Some(Node::Item(&hir::Item {
500             kind: hir::ItemKind::Fn(ref sig, _, _), ..
501         })) = tcx.hir().find(parent_id)
502         {
503             if sig.header.unsafety == hir::Unsafety::Unsafe && unsafe_op_in_unsafe_fn_allowed {
504                 Some(("fn", parent_id))
505             } else {
506                 None
507             }
508         } else {
509             is_enclosed(tcx, used_unsafe, parent_id, unsafe_op_in_unsafe_fn_allowed)
510         }
511     } else {
512         None
513     }
514 }
515
516 fn report_unused_unsafe(tcx: TyCtxt<'_>, used_unsafe: &FxHashSet<hir::HirId>, id: hir::HirId) {
517     let span = tcx.sess.source_map().guess_head_span(tcx.hir().span(id));
518     tcx.struct_span_lint_hir(UNUSED_UNSAFE, id, span, |lint| {
519         let msg = "unnecessary `unsafe` block";
520         let mut db = lint.build(msg);
521         db.span_label(span, msg);
522         if let Some((kind, id)) =
523             is_enclosed(tcx, used_unsafe, id, unsafe_op_in_unsafe_fn_allowed(tcx, id))
524         {
525             db.span_label(
526                 tcx.sess.source_map().guess_head_span(tcx.hir().span(id)),
527                 format!("because it's nested under this `unsafe` {}", kind),
528             );
529         }
530         db.emit();
531     });
532 }
533
534 pub fn check_unsafety(tcx: TyCtxt<'_>, def_id: LocalDefId) {
535     debug!("check_unsafety({:?})", def_id);
536
537     // closures are handled by their parent fn.
538     if tcx.is_closure(def_id.to_def_id()) {
539         return;
540     }
541
542     let UnsafetyCheckResult { violations, unsafe_blocks } = tcx.unsafety_check_result(def_id);
543
544     for &UnsafetyViolation { source_info, lint_root, kind, details } in violations.iter() {
545         let (description, note) = details.description_and_note();
546
547         // Report an error.
548         let unsafe_fn_msg =
549             if unsafe_op_in_unsafe_fn_allowed(tcx, lint_root) { " function or" } else { "" };
550
551         match kind {
552             UnsafetyViolationKind::General => {
553                 // once
554                 struct_span_err!(
555                     tcx.sess,
556                     source_info.span,
557                     E0133,
558                     "{} is unsafe and requires unsafe{} block",
559                     description,
560                     unsafe_fn_msg,
561                 )
562                 .span_label(source_info.span, description)
563                 .note(note)
564                 .emit();
565             }
566             UnsafetyViolationKind::UnsafeFn => tcx.struct_span_lint_hir(
567                 UNSAFE_OP_IN_UNSAFE_FN,
568                 lint_root,
569                 source_info.span,
570                 |lint| {
571                     lint.build(&format!(
572                         "{} is unsafe and requires unsafe block (error E0133)",
573                         description,
574                     ))
575                     .span_label(source_info.span, description)
576                     .note(note)
577                     .emit();
578                 },
579             ),
580         }
581     }
582
583     let (mut unsafe_used, mut unsafe_unused): (FxHashSet<_>, Vec<_>) = Default::default();
584     for &(block_id, is_used) in unsafe_blocks.iter() {
585         if is_used {
586             unsafe_used.insert(block_id);
587         } else {
588             unsafe_unused.push(block_id);
589         }
590     }
591     // The unused unsafe blocks might not be in source order; sort them so that the unused unsafe
592     // error messages are properly aligned and the issue-45107 and lint-unused-unsafe tests pass.
593     unsafe_unused.sort_by_cached_key(|hir_id| tcx.hir().span(*hir_id));
594
595     for &block_id in &unsafe_unused {
596         report_unused_unsafe(tcx, &unsafe_used, block_id);
597     }
598 }
599
600 fn unsafe_op_in_unsafe_fn_allowed(tcx: TyCtxt<'_>, id: HirId) -> bool {
601     tcx.lint_level_at_node(UNSAFE_OP_IN_UNSAFE_FN, id).0 == Level::Allow
602 }