]> git.lizzy.rs Git - rust.git/blob - src/librustc_mir/transform/check_unsafety.rs
pin docs: add some forward references
[rust.git] / src / librustc_mir / 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::{SAFE_PACKED_BORROWS, UNSAFE_OP_IN_UNSAFE_FN, UNUSED_UNSAFE};
14 use rustc_session::lint::Level;
15 use rustc_span::symbol::sym;
16
17 use std::ops::Bound;
18
19 use crate::const_eval::is_min_const_fn;
20 use crate::util;
21
22 pub struct UnsafetyChecker<'a, 'tcx> {
23     body: &'a Body<'tcx>,
24     body_did: LocalDefId,
25     const_context: bool,
26     min_const_fn: bool,
27     violations: Vec<UnsafetyViolation>,
28     source_info: SourceInfo,
29     tcx: TyCtxt<'tcx>,
30     param_env: ty::ParamEnv<'tcx>,
31     /// Mark an `unsafe` block as used, so we don't lint it.
32     used_unsafe: FxHashSet<hir::HirId>,
33     inherited_blocks: Vec<(hir::HirId, bool)>,
34 }
35
36 impl<'a, 'tcx> UnsafetyChecker<'a, 'tcx> {
37     fn new(
38         const_context: bool,
39         min_const_fn: bool,
40         body: &'a Body<'tcx>,
41         body_did: LocalDefId,
42         tcx: TyCtxt<'tcx>,
43         param_env: ty::ParamEnv<'tcx>,
44     ) -> Self {
45         // sanity check
46         if min_const_fn {
47             assert!(const_context);
48         }
49         Self {
50             body,
51             body_did,
52             const_context,
53             min_const_fn,
54             violations: vec![],
55             source_info: SourceInfo::outermost(body.span),
56             tcx,
57             param_env,
58             used_unsafe: Default::default(),
59             inherited_blocks: vec![],
60         }
61     }
62 }
63
64 impl<'a, 'tcx> Visitor<'tcx> for UnsafetyChecker<'a, 'tcx> {
65     fn visit_terminator(&mut self, terminator: &Terminator<'tcx>, location: Location) {
66         self.source_info = terminator.source_info;
67         match terminator.kind {
68             TerminatorKind::Goto { .. }
69             | TerminatorKind::SwitchInt { .. }
70             | TerminatorKind::Drop { .. }
71             | TerminatorKind::Yield { .. }
72             | TerminatorKind::Assert { .. }
73             | TerminatorKind::DropAndReplace { .. }
74             | TerminatorKind::GeneratorDrop
75             | TerminatorKind::Resume
76             | TerminatorKind::Abort
77             | TerminatorKind::Return
78             | TerminatorKind::Unreachable
79             | TerminatorKind::FalseEdge { .. }
80             | TerminatorKind::FalseUnwind { .. } => {
81                 // safe (at least as emitted during MIR construction)
82             }
83
84             TerminatorKind::Call { ref func, .. } => {
85                 let func_ty = func.ty(self.body, self.tcx);
86                 let sig = func_ty.fn_sig(self.tcx);
87                 if let hir::Unsafety::Unsafe = sig.unsafety() {
88                     self.require_unsafe(
89                         UnsafetyViolationKind::GeneralAndConstFn,
90                         UnsafetyViolationDetails::CallToUnsafeFunction,
91                     )
92                 }
93
94                 if let ty::FnDef(func_id, _) = func_ty.kind {
95                     self.check_target_features(func_id);
96                 }
97             }
98
99             TerminatorKind::InlineAsm { .. } => self.require_unsafe(
100                 UnsafetyViolationKind::General,
101                 UnsafetyViolationDetails::UseOfInlineAssembly,
102             ),
103         }
104         self.super_terminator(terminator, location);
105     }
106
107     fn visit_statement(&mut self, statement: &Statement<'tcx>, location: Location) {
108         self.source_info = statement.source_info;
109         match statement.kind {
110             StatementKind::Assign(..)
111             | StatementKind::FakeRead(..)
112             | StatementKind::SetDiscriminant { .. }
113             | StatementKind::StorageLive(..)
114             | StatementKind::StorageDead(..)
115             | StatementKind::Retag { .. }
116             | StatementKind::AscribeUserType(..)
117             | StatementKind::Nop => {
118                 // safe (at least as emitted during MIR construction)
119             }
120
121             StatementKind::LlvmInlineAsm { .. } => self.require_unsafe(
122                 UnsafetyViolationKind::General,
123                 UnsafetyViolationDetails::UseOfInlineAssembly,
124             ),
125         }
126         self.super_statement(statement, location);
127     }
128
129     fn visit_rvalue(&mut self, rvalue: &Rvalue<'tcx>, location: Location) {
130         match rvalue {
131             Rvalue::Aggregate(box ref aggregate, _) => match aggregate {
132                 &AggregateKind::Array(..) | &AggregateKind::Tuple => {}
133                 &AggregateKind::Adt(ref def, ..) => {
134                     match self.tcx.layout_scalar_valid_range(def.did) {
135                         (Bound::Unbounded, Bound::Unbounded) => {}
136                         _ => self.require_unsafe(
137                             UnsafetyViolationKind::GeneralAndConstFn,
138                             UnsafetyViolationDetails::InitializingTypeWith,
139                         ),
140                     }
141                 }
142                 &AggregateKind::Closure(def_id, _) | &AggregateKind::Generator(def_id, _, _) => {
143                     let UnsafetyCheckResult { violations, unsafe_blocks } =
144                         self.tcx.unsafety_check_result(def_id.expect_local());
145                     self.register_violations(&violations, &unsafe_blocks);
146                 }
147             },
148             // casting pointers to ints is unsafe in const fn because the const evaluator cannot
149             // possibly know what the result of various operations like `address / 2` would be
150             // pointers during const evaluation have no integral address, only an abstract one
151             Rvalue::Cast(CastKind::Misc, ref operand, cast_ty)
152                 if self.const_context && self.tcx.features().const_raw_ptr_to_usize_cast =>
153             {
154                 let operand_ty = operand.ty(self.body, self.tcx);
155                 let cast_in = CastTy::from_ty(operand_ty).expect("bad input type for cast");
156                 let cast_out = CastTy::from_ty(cast_ty).expect("bad output type for cast");
157                 match (cast_in, cast_out) {
158                     (CastTy::Ptr(_) | CastTy::FnPtr, CastTy::Int(_)) => {
159                         self.require_unsafe(
160                             UnsafetyViolationKind::General,
161                             UnsafetyViolationDetails::CastOfPointerToInt,
162                         );
163                     }
164                     _ => {}
165                 }
166             }
167             _ => {}
168         }
169         self.super_rvalue(rvalue, location);
170     }
171
172     fn visit_place(&mut self, place: &Place<'tcx>, context: PlaceContext, _location: Location) {
173         // On types with `scalar_valid_range`, prevent
174         // * `&mut x.field`
175         // * `x.field = y;`
176         // * `&x.field` if `field`'s type has interior mutability
177         // because either of these would allow modifying the layout constrained field and
178         // insert values that violate the layout constraints.
179         if context.is_mutating_use() || context.is_borrow() {
180             self.check_mut_borrowing_layout_constrained_field(*place, context.is_mutating_use());
181         }
182
183         if context.is_borrow() {
184             if util::is_disaligned(self.tcx, self.body, self.param_env, *place) {
185                 self.require_unsafe(
186                     UnsafetyViolationKind::BorrowPacked,
187                     UnsafetyViolationDetails::BorrowOfPackedField,
188                 );
189             }
190         }
191
192         for (i, elem) in place.projection.iter().enumerate() {
193             let proj_base = &place.projection[..i];
194             if context.is_borrow() {
195                 if util::is_disaligned(self.tcx, self.body, self.param_env, *place) {
196                     self.require_unsafe(
197                         UnsafetyViolationKind::BorrowPacked,
198                         UnsafetyViolationDetails::BorrowOfPackedField,
199                     );
200                 }
201             }
202             let source_info = self.source_info;
203             if let [] = proj_base {
204                 let decl = &self.body.local_decls[place.local];
205                 if decl.internal {
206                     if let Some(box LocalInfo::StaticRef { def_id, .. }) = decl.local_info {
207                         if self.tcx.is_mutable_static(def_id) {
208                             self.require_unsafe(
209                                 UnsafetyViolationKind::General,
210                                 UnsafetyViolationDetails::UseOfMutableStatic,
211                             );
212                             return;
213                         } else if self.tcx.is_foreign_item(def_id) {
214                             self.require_unsafe(
215                                 UnsafetyViolationKind::General,
216                                 UnsafetyViolationDetails::UseOfExternStatic,
217                             );
218                             return;
219                         }
220                     } else {
221                         // Internal locals are used in the `move_val_init` desugaring.
222                         // We want to check unsafety against the source info of the
223                         // desugaring, rather than the source info of the RHS.
224                         self.source_info = self.body.local_decls[place.local].source_info;
225                     }
226                 }
227             }
228             let base_ty = Place::ty_from(place.local, proj_base, self.body, self.tcx).ty;
229             match base_ty.kind {
230                 ty::RawPtr(..) => self.require_unsafe(
231                     UnsafetyViolationKind::General,
232                     UnsafetyViolationDetails::DerefOfRawPointer,
233                 ),
234                 ty::Adt(adt, _) => {
235                     if adt.is_union() {
236                         if context == PlaceContext::MutatingUse(MutatingUseContext::Store)
237                             || context == PlaceContext::MutatingUse(MutatingUseContext::Drop)
238                             || context == PlaceContext::MutatingUse(MutatingUseContext::AsmOutput)
239                         {
240                             let elem_ty = match elem {
241                                 ProjectionElem::Field(_, ty) => ty,
242                                 _ => span_bug!(
243                                     self.source_info.span,
244                                     "non-field projection {:?} from union?",
245                                     place
246                                 ),
247                             };
248                             if !elem_ty.is_copy_modulo_regions(
249                                 self.tcx.at(self.source_info.span),
250                                 self.param_env,
251                             ) {
252                                 self.require_unsafe(
253                                     UnsafetyViolationKind::GeneralAndConstFn,
254                                     UnsafetyViolationDetails::AssignToNonCopyUnionField,
255                                 )
256                             } else {
257                                 // write to non-move union, safe
258                             }
259                         } else {
260                             self.require_unsafe(
261                                 UnsafetyViolationKind::GeneralAndConstFn,
262                                 UnsafetyViolationDetails::AccessToUnionField,
263                             )
264                         }
265                     }
266                 }
267                 _ => {}
268             }
269             self.source_info = source_info;
270         }
271     }
272 }
273
274 impl<'a, 'tcx> UnsafetyChecker<'a, 'tcx> {
275     fn require_unsafe(&mut self, kind: UnsafetyViolationKind, details: UnsafetyViolationDetails) {
276         let source_info = self.source_info;
277         let lint_root = self.body.source_scopes[self.source_info.scope]
278             .local_data
279             .as_ref()
280             .assert_crate_local()
281             .lint_root;
282         self.register_violations(
283             &[UnsafetyViolation { source_info, lint_root, kind, details }],
284             &[],
285         );
286     }
287
288     fn register_violations(
289         &mut self,
290         violations: &[UnsafetyViolation],
291         unsafe_blocks: &[(hir::HirId, bool)],
292     ) {
293         let safety = self.body.source_scopes[self.source_info.scope]
294             .local_data
295             .as_ref()
296             .assert_crate_local()
297             .safety;
298         let within_unsafe = match safety {
299             // `unsafe` blocks are required in safe code
300             Safety::Safe => {
301                 for violation in violations {
302                     let mut violation = *violation;
303                     match violation.kind {
304                         UnsafetyViolationKind::GeneralAndConstFn
305                         | UnsafetyViolationKind::General => {}
306                         UnsafetyViolationKind::BorrowPacked => {
307                             if self.min_const_fn {
308                                 // const fns don't need to be backwards compatible and can
309                                 // emit these violations as a hard error instead of a backwards
310                                 // compat lint
311                                 violation.kind = UnsafetyViolationKind::General;
312                             }
313                         }
314                         UnsafetyViolationKind::UnsafeFn
315                         | UnsafetyViolationKind::UnsafeFnBorrowPacked => {
316                             bug!("`UnsafetyViolationKind::UnsafeFn` in an `Safe` context")
317                         }
318                     }
319                     if !self.violations.contains(&violation) {
320                         self.violations.push(violation)
321                     }
322                 }
323                 false
324             }
325             // With the RFC 2585, no longer allow `unsafe` operations in `unsafe fn`s
326             Safety::FnUnsafe if self.tcx.features().unsafe_block_in_unsafe_fn => {
327                 for violation in violations {
328                     let mut violation = *violation;
329
330                     if violation.kind == UnsafetyViolationKind::BorrowPacked {
331                         violation.kind = UnsafetyViolationKind::UnsafeFnBorrowPacked;
332                     } else {
333                         violation.kind = UnsafetyViolationKind::UnsafeFn;
334                     }
335                     if !self.violations.contains(&violation) {
336                         self.violations.push(violation)
337                     }
338                 }
339                 false
340             }
341             // `unsafe` function bodies allow unsafe without additional unsafe blocks (before RFC 2585)
342             Safety::BuiltinUnsafe | Safety::FnUnsafe => true,
343             Safety::ExplicitUnsafe(hir_id) => {
344                 // mark unsafe block as used if there are any unsafe operations inside
345                 if !violations.is_empty() {
346                     self.used_unsafe.insert(hir_id);
347                 }
348                 // only some unsafety is allowed in const fn
349                 if self.min_const_fn {
350                     for violation in violations {
351                         match violation.kind {
352                             // these unsafe things are stable in const fn
353                             UnsafetyViolationKind::GeneralAndConstFn => {}
354                             // these things are forbidden in const fns
355                             UnsafetyViolationKind::General
356                             | UnsafetyViolationKind::BorrowPacked => {
357                                 let mut violation = *violation;
358                                 // const fns don't need to be backwards compatible and can
359                                 // emit these violations as a hard error instead of a backwards
360                                 // compat lint
361                                 violation.kind = UnsafetyViolationKind::General;
362                                 if !self.violations.contains(&violation) {
363                                     self.violations.push(violation)
364                                 }
365                             }
366                             UnsafetyViolationKind::UnsafeFn
367                             | UnsafetyViolationKind::UnsafeFnBorrowPacked => bug!(
368                                 "`UnsafetyViolationKind::UnsafeFn` in an `ExplicitUnsafe` context"
369                             ),
370                         }
371                     }
372                 }
373                 true
374             }
375         };
376         self.inherited_blocks.extend(
377             unsafe_blocks.iter().map(|&(hir_id, is_used)| (hir_id, is_used && !within_unsafe)),
378         );
379     }
380     fn check_mut_borrowing_layout_constrained_field(
381         &mut self,
382         place: Place<'tcx>,
383         is_mut_use: bool,
384     ) {
385         let mut cursor = place.projection.as_ref();
386         while let &[ref proj_base @ .., elem] = cursor {
387             cursor = proj_base;
388
389             match elem {
390                 // Modifications behind a dereference don't affect the value of
391                 // the pointer.
392                 ProjectionElem::Deref => return,
393                 ProjectionElem::Field(..) => {
394                     let ty =
395                         Place::ty_from(place.local, proj_base, &self.body.local_decls, self.tcx).ty;
396                     if let ty::Adt(def, _) = ty.kind {
397                         if self.tcx.layout_scalar_valid_range(def.did)
398                             != (Bound::Unbounded, Bound::Unbounded)
399                         {
400                             let details = if is_mut_use {
401                                 UnsafetyViolationDetails::MutationOfLayoutConstrainedField
402
403                             // Check `is_freeze` as late as possible to avoid cycle errors
404                             // with opaque types.
405                             } else if !place
406                                 .ty(self.body, self.tcx)
407                                 .ty
408                                 .is_freeze(self.tcx.at(self.source_info.span), self.param_env)
409                             {
410                                 UnsafetyViolationDetails::BorrowOfLayoutConstrainedField
411                             } else {
412                                 continue;
413                             };
414                             self.require_unsafe(UnsafetyViolationKind::GeneralAndConstFn, details);
415                         }
416                     }
417                 }
418                 _ => {}
419             }
420         }
421     }
422
423     /// Checks whether calling `func_did` needs an `unsafe` context or not, i.e. whether
424     /// the called function has target features the calling function hasn't.
425     fn check_target_features(&mut self, func_did: DefId) {
426         let callee_features = &self.tcx.codegen_fn_attrs(func_did).target_features;
427         let self_features = &self.tcx.codegen_fn_attrs(self.body_did).target_features;
428
429         // Is `callee_features` a subset of `calling_features`?
430         if !callee_features.iter().all(|feature| self_features.contains(feature)) {
431             self.require_unsafe(
432                 UnsafetyViolationKind::GeneralAndConstFn,
433                 UnsafetyViolationDetails::CallToFunctionWith,
434             )
435         }
436     }
437 }
438
439 pub(crate) fn provide(providers: &mut Providers) {
440     *providers = Providers {
441         unsafety_check_result: |tcx, def_id| {
442             if let Some(def) = ty::WithOptConstParam::try_lookup(def_id, tcx) {
443                 tcx.unsafety_check_result_for_const_arg(def)
444             } else {
445                 unsafety_check_result(tcx, ty::WithOptConstParam::unknown(def_id))
446             }
447         },
448         unsafety_check_result_for_const_arg: |tcx, (did, param_did)| {
449             unsafety_check_result(
450                 tcx,
451                 ty::WithOptConstParam { did, const_param_did: Some(param_did) },
452             )
453         },
454         unsafe_derive_on_repr_packed,
455         ..*providers
456     };
457 }
458
459 struct UnusedUnsafeVisitor<'a> {
460     used_unsafe: &'a FxHashSet<hir::HirId>,
461     unsafe_blocks: &'a mut Vec<(hir::HirId, bool)>,
462 }
463
464 impl<'a, 'tcx> intravisit::Visitor<'tcx> for UnusedUnsafeVisitor<'a> {
465     type Map = intravisit::ErasedMap<'tcx>;
466
467     fn nested_visit_map(&mut self) -> intravisit::NestedVisitorMap<Self::Map> {
468         intravisit::NestedVisitorMap::None
469     }
470
471     fn visit_block(&mut self, block: &'tcx hir::Block<'tcx>) {
472         intravisit::walk_block(self, block);
473
474         if let hir::BlockCheckMode::UnsafeBlock(hir::UnsafeSource::UserProvided) = block.rules {
475             self.unsafe_blocks.push((block.hir_id, self.used_unsafe.contains(&block.hir_id)));
476         }
477     }
478 }
479
480 fn check_unused_unsafe(
481     tcx: TyCtxt<'_>,
482     def_id: LocalDefId,
483     used_unsafe: &FxHashSet<hir::HirId>,
484     unsafe_blocks: &mut Vec<(hir::HirId, bool)>,
485 ) {
486     let body_id = tcx.hir().maybe_body_owned_by(tcx.hir().as_local_hir_id(def_id));
487
488     let body_id = match body_id {
489         Some(body) => body,
490         None => {
491             debug!("check_unused_unsafe({:?}) - no body found", def_id);
492             return;
493         }
494     };
495     let body = tcx.hir().body(body_id);
496     debug!("check_unused_unsafe({:?}, body={:?}, used_unsafe={:?})", def_id, body, used_unsafe);
497
498     let mut visitor = UnusedUnsafeVisitor { used_unsafe, unsafe_blocks };
499     intravisit::Visitor::visit_body(&mut visitor, body);
500 }
501
502 fn unsafety_check_result<'tcx>(
503     tcx: TyCtxt<'tcx>,
504     def: ty::WithOptConstParam<LocalDefId>,
505 ) -> &'tcx UnsafetyCheckResult {
506     debug!("unsafety_violations({:?})", def);
507
508     // N.B., this borrow is valid because all the consumers of
509     // `mir_built` force this.
510     let body = &tcx.mir_built(def).borrow();
511
512     let param_env = tcx.param_env(def.did);
513
514     let id = tcx.hir().as_local_hir_id(def.did);
515     let (const_context, min_const_fn) = match tcx.hir().body_owner_kind(id) {
516         hir::BodyOwnerKind::Closure => (false, false),
517         hir::BodyOwnerKind::Fn => {
518             (tcx.is_const_fn_raw(def.did.to_def_id()), is_min_const_fn(tcx, def.did.to_def_id()))
519         }
520         hir::BodyOwnerKind::Const | hir::BodyOwnerKind::Static(_) => (true, false),
521     };
522     let mut checker =
523         UnsafetyChecker::new(const_context, min_const_fn, body, def.did, tcx, param_env);
524     checker.visit_body(&body);
525
526     check_unused_unsafe(tcx, def.did, &checker.used_unsafe, &mut checker.inherited_blocks);
527
528     tcx.arena.alloc(UnsafetyCheckResult {
529         violations: checker.violations.into(),
530         unsafe_blocks: checker.inherited_blocks.into(),
531     })
532 }
533
534 fn unsafe_derive_on_repr_packed(tcx: TyCtxt<'_>, def_id: LocalDefId) {
535     let lint_hir_id = tcx.hir().as_local_hir_id(def_id);
536
537     tcx.struct_span_lint_hir(SAFE_PACKED_BORROWS, lint_hir_id, tcx.def_span(def_id), |lint| {
538         // FIXME: when we make this a hard error, this should have its
539         // own error code.
540         let message = if tcx.generics_of(def_id).own_requires_monomorphization() {
541             "`#[derive]` can't be used on a `#[repr(packed)]` struct with \
542              type or const parameters (error E0133)"
543                 .to_string()
544         } else {
545             "`#[derive]` can't be used on a `#[repr(packed)]` struct that \
546              does not derive Copy (error E0133)"
547                 .to_string()
548         };
549         lint.build(&message).emit()
550     });
551 }
552
553 /// Returns the `HirId` for an enclosing scope that is also `unsafe`.
554 fn is_enclosed(
555     tcx: TyCtxt<'_>,
556     used_unsafe: &FxHashSet<hir::HirId>,
557     id: hir::HirId,
558 ) -> Option<(String, hir::HirId)> {
559     let parent_id = tcx.hir().get_parent_node(id);
560     if parent_id != id {
561         if used_unsafe.contains(&parent_id) {
562             Some(("block".to_string(), parent_id))
563         } else if let Some(Node::Item(&hir::Item {
564             kind: hir::ItemKind::Fn(ref sig, _, _), ..
565         })) = tcx.hir().find(parent_id)
566         {
567             if sig.header.unsafety == hir::Unsafety::Unsafe
568                 && !tcx.features().unsafe_block_in_unsafe_fn
569             {
570                 Some(("fn".to_string(), parent_id))
571             } else {
572                 None
573             }
574         } else {
575             is_enclosed(tcx, used_unsafe, parent_id)
576         }
577     } else {
578         None
579     }
580 }
581
582 fn report_unused_unsafe(tcx: TyCtxt<'_>, used_unsafe: &FxHashSet<hir::HirId>, id: hir::HirId) {
583     let span = tcx.sess.source_map().guess_head_span(tcx.hir().span(id));
584     tcx.struct_span_lint_hir(UNUSED_UNSAFE, id, span, |lint| {
585         let msg = "unnecessary `unsafe` block";
586         let mut db = lint.build(msg);
587         db.span_label(span, msg);
588         if let Some((kind, id)) = is_enclosed(tcx, used_unsafe, id) {
589             db.span_label(
590                 tcx.sess.source_map().guess_head_span(tcx.hir().span(id)),
591                 format!("because it's nested under this `unsafe` {}", kind),
592             );
593         }
594         db.emit();
595     });
596 }
597
598 fn builtin_derive_def_id(tcx: TyCtxt<'_>, def_id: DefId) -> Option<DefId> {
599     debug!("builtin_derive_def_id({:?})", def_id);
600     if let Some(impl_def_id) = tcx.impl_of_method(def_id) {
601         if tcx.has_attr(impl_def_id, sym::automatically_derived) {
602             debug!("builtin_derive_def_id({:?}) - is {:?}", def_id, impl_def_id);
603             Some(impl_def_id)
604         } else {
605             debug!("builtin_derive_def_id({:?}) - not automatically derived", def_id);
606             None
607         }
608     } else {
609         debug!("builtin_derive_def_id({:?}) - not a method", def_id);
610         None
611     }
612 }
613
614 pub fn check_unsafety(tcx: TyCtxt<'_>, def_id: LocalDefId) {
615     debug!("check_unsafety({:?})", def_id);
616
617     // closures are handled by their parent fn.
618     if tcx.is_closure(def_id.to_def_id()) {
619         return;
620     }
621
622     let UnsafetyCheckResult { violations, unsafe_blocks } = tcx.unsafety_check_result(def_id);
623
624     for &UnsafetyViolation { source_info, lint_root, kind, details } in violations.iter() {
625         let (description, note) = details.description_and_note();
626
627         // Report an error.
628         let unsafe_fn_msg =
629             if unsafe_op_in_unsafe_fn_allowed(tcx, lint_root) { " function or" } else { "" };
630
631         match kind {
632             UnsafetyViolationKind::GeneralAndConstFn | UnsafetyViolationKind::General => {
633                 // once
634                 struct_span_err!(
635                     tcx.sess,
636                     source_info.span,
637                     E0133,
638                     "{} is unsafe and requires unsafe{} block",
639                     description,
640                     unsafe_fn_msg,
641                 )
642                 .span_label(source_info.span, description)
643                 .note(note)
644                 .emit();
645             }
646             UnsafetyViolationKind::BorrowPacked => {
647                 if let Some(impl_def_id) = builtin_derive_def_id(tcx, def_id.to_def_id()) {
648                     // If a method is defined in the local crate,
649                     // the impl containing that method should also be.
650                     tcx.ensure().unsafe_derive_on_repr_packed(impl_def_id.expect_local());
651                 } else {
652                     tcx.struct_span_lint_hir(
653                         SAFE_PACKED_BORROWS,
654                         lint_root,
655                         source_info.span,
656                         |lint| {
657                             lint.build(&format!(
658                                 "{} is unsafe and requires unsafe{} block (error E0133)",
659                                 description, unsafe_fn_msg,
660                             ))
661                             .note(note)
662                             .emit()
663                         },
664                     )
665                 }
666             }
667             UnsafetyViolationKind::UnsafeFn => tcx.struct_span_lint_hir(
668                 UNSAFE_OP_IN_UNSAFE_FN,
669                 lint_root,
670                 source_info.span,
671                 |lint| {
672                     lint.build(&format!(
673                         "{} is unsafe and requires unsafe block (error E0133)",
674                         description,
675                     ))
676                     .span_label(source_info.span, description)
677                     .note(note)
678                     .emit();
679                 },
680             ),
681             UnsafetyViolationKind::UnsafeFnBorrowPacked => {
682                 // When `unsafe_op_in_unsafe_fn` is disallowed, the behavior of safe and unsafe functions
683                 // should be the same in terms of warnings and errors. Therefore, with `#[warn(safe_packed_borrows)]`,
684                 // a safe packed borrow should emit a warning *but not an error* in an unsafe function,
685                 // just like in a safe function, even if `unsafe_op_in_unsafe_fn` is `deny`.
686                 //
687                 // Also, `#[warn(unsafe_op_in_unsafe_fn)]` can't cause any new errors. Therefore, with
688                 // `#[deny(safe_packed_borrows)]` and `#[warn(unsafe_op_in_unsafe_fn)]`, a packed borrow
689                 // should only issue a warning for the sake of backwards compatibility.
690                 //
691                 // The solution those 2 expectations is to always take the minimum of both lints.
692                 // This prevent any new errors (unless both lints are explicitely set to `deny`).
693                 let lint = if tcx.lint_level_at_node(SAFE_PACKED_BORROWS, lint_root).0
694                     <= tcx.lint_level_at_node(UNSAFE_OP_IN_UNSAFE_FN, lint_root).0
695                 {
696                     SAFE_PACKED_BORROWS
697                 } else {
698                     UNSAFE_OP_IN_UNSAFE_FN
699                 };
700                 tcx.struct_span_lint_hir(&lint, lint_root, source_info.span, |lint| {
701                     lint.build(&format!(
702                         "{} is unsafe and requires unsafe block (error E0133)",
703                         description,
704                     ))
705                     .span_label(source_info.span, description)
706                     .note(note)
707                     .emit();
708                 })
709             }
710         }
711     }
712
713     let (mut unsafe_used, mut unsafe_unused): (FxHashSet<_>, Vec<_>) = Default::default();
714     for &(block_id, is_used) in unsafe_blocks.iter() {
715         if is_used {
716             unsafe_used.insert(block_id);
717         } else {
718             unsafe_unused.push(block_id);
719         }
720     }
721     // The unused unsafe blocks might not be in source order; sort them so that the unused unsafe
722     // error messages are properly aligned and the issue-45107 and lint-unused-unsafe tests pass.
723     unsafe_unused.sort_by_cached_key(|hir_id| tcx.hir().span(*hir_id));
724
725     for &block_id in &unsafe_unused {
726         report_unused_unsafe(tcx, &unsafe_used, block_id);
727     }
728 }
729
730 fn unsafe_op_in_unsafe_fn_allowed(tcx: TyCtxt<'_>, id: HirId) -> bool {
731     tcx.lint_level_at_node(UNSAFE_OP_IN_UNSAFE_FN, id).0 == Level::Allow
732 }