]> git.lizzy.rs Git - rust.git/blob - src/librustc_mir/transform/check_unsafety.rs
Rollup merge of #68071 - estebank:ice-67995, r=Centril
[rust.git] / src / librustc_mir / transform / check_unsafety.rs
1 use rustc::hir::map::Map;
2 use rustc::lint::builtin::{SAFE_PACKED_BORROWS, UNUSED_UNSAFE};
3 use rustc::mir::visit::{MutatingUseContext, PlaceContext, Visitor};
4 use rustc::mir::*;
5 use rustc::ty::cast::CastTy;
6 use rustc::ty::query::Providers;
7 use rustc::ty::{self, TyCtxt};
8 use rustc_data_structures::fx::FxHashSet;
9 use rustc_errors::struct_span_err;
10 use rustc_hir as hir;
11 use rustc_hir::def_id::DefId;
12 use rustc_hir::intravisit;
13 use rustc_hir::Node;
14 use rustc_span::symbol::{sym, Symbol};
15
16 use std::ops::Bound;
17
18 use crate::const_eval::{is_const_fn, is_min_const_fn};
19 use crate::util;
20
21 use rustc_error_codes::*;
22
23 pub struct UnsafetyChecker<'a, 'tcx> {
24     body: &'a Body<'tcx>,
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         tcx: TyCtxt<'tcx>,
42         param_env: ty::ParamEnv<'tcx>,
43     ) -> Self {
44         // sanity check
45         if min_const_fn {
46             assert!(const_context);
47         }
48         Self {
49             body,
50             const_context,
51             min_const_fn,
52             violations: vec![],
53             source_info: SourceInfo { span: body.span, scope: OUTERMOST_SOURCE_SCOPE },
54             tcx,
55             param_env,
56             used_unsafe: Default::default(),
57             inherited_blocks: vec![],
58         }
59     }
60 }
61
62 impl<'a, 'tcx> Visitor<'tcx> for UnsafetyChecker<'a, 'tcx> {
63     fn visit_terminator(&mut self, terminator: &Terminator<'tcx>, location: Location) {
64         self.source_info = terminator.source_info;
65         match terminator.kind {
66             TerminatorKind::Goto { .. }
67             | TerminatorKind::SwitchInt { .. }
68             | TerminatorKind::Drop { .. }
69             | TerminatorKind::Yield { .. }
70             | TerminatorKind::Assert { .. }
71             | TerminatorKind::DropAndReplace { .. }
72             | TerminatorKind::GeneratorDrop
73             | TerminatorKind::Resume
74             | TerminatorKind::Abort
75             | TerminatorKind::Return
76             | TerminatorKind::Unreachable
77             | TerminatorKind::FalseEdges { .. }
78             | TerminatorKind::FalseUnwind { .. } => {
79                 // safe (at least as emitted during MIR construction)
80             }
81
82             TerminatorKind::Call { ref func, .. } => {
83                 let func_ty = func.ty(self.body, self.tcx);
84                 let sig = func_ty.fn_sig(self.tcx);
85                 if let hir::Unsafety::Unsafe = sig.unsafety() {
86                     self.require_unsafe(
87                         "call to unsafe function",
88                         "consult the function's documentation for information on how to avoid \
89                          undefined behavior",
90                         UnsafetyViolationKind::GeneralAndConstFn,
91                     )
92                 }
93             }
94         }
95         self.super_terminator(terminator, location);
96     }
97
98     fn visit_statement(&mut self, statement: &Statement<'tcx>, location: Location) {
99         self.source_info = statement.source_info;
100         match statement.kind {
101             StatementKind::Assign(..)
102             | StatementKind::FakeRead(..)
103             | StatementKind::SetDiscriminant { .. }
104             | StatementKind::StorageLive(..)
105             | StatementKind::StorageDead(..)
106             | StatementKind::Retag { .. }
107             | StatementKind::AscribeUserType(..)
108             | StatementKind::Nop => {
109                 // safe (at least as emitted during MIR construction)
110             }
111
112             StatementKind::InlineAsm { .. } => self.require_unsafe(
113                 "use of inline assembly",
114                 "inline assembly is entirely unchecked and can cause undefined behavior",
115                 UnsafetyViolationKind::General,
116             ),
117         }
118         self.super_statement(statement, location);
119     }
120
121     fn visit_rvalue(&mut self, rvalue: &Rvalue<'tcx>, location: Location) {
122         match rvalue {
123             Rvalue::Aggregate(box ref aggregate, _) => match aggregate {
124                 &AggregateKind::Array(..) | &AggregateKind::Tuple => {}
125                 &AggregateKind::Adt(ref def, ..) => {
126                     match self.tcx.layout_scalar_valid_range(def.did) {
127                         (Bound::Unbounded, Bound::Unbounded) => {}
128                         _ => self.require_unsafe(
129                             "initializing type with `rustc_layout_scalar_valid_range` attr",
130                             "initializing a layout restricted type's field with a value \
131                                 outside the valid range is undefined behavior",
132                             UnsafetyViolationKind::GeneralAndConstFn,
133                         ),
134                     }
135                 }
136                 &AggregateKind::Closure(def_id, _) | &AggregateKind::Generator(def_id, _, _) => {
137                     let UnsafetyCheckResult { violations, unsafe_blocks } =
138                         self.tcx.unsafety_check_result(def_id);
139                     self.register_violations(&violations, &unsafe_blocks);
140                 }
141             },
142             // casting pointers to ints is unsafe in const fn because the const evaluator cannot
143             // possibly know what the result of various operations like `address / 2` would be
144             // pointers during const evaluation have no integral address, only an abstract one
145             Rvalue::Cast(CastKind::Misc, ref operand, cast_ty)
146                 if self.const_context && self.tcx.features().const_raw_ptr_to_usize_cast =>
147             {
148                 let operand_ty = operand.ty(self.body, self.tcx);
149                 let cast_in = CastTy::from_ty(operand_ty).expect("bad input type for cast");
150                 let cast_out = CastTy::from_ty(cast_ty).expect("bad output type for cast");
151                 match (cast_in, cast_out) {
152                     (CastTy::Ptr(_), CastTy::Int(_)) | (CastTy::FnPtr, CastTy::Int(_)) => {
153                         self.register_violations(
154                             &[UnsafetyViolation {
155                                 source_info: self.source_info,
156                                 description: Symbol::intern("cast of pointer to int"),
157                                 details: Symbol::intern(
158                                     "casting pointers to integers in constants",
159                                 ),
160                                 kind: UnsafetyViolationKind::General,
161                             }],
162                             &[],
163                         );
164                     }
165                     _ => {}
166                 }
167             }
168             // raw pointer and fn pointer operations are unsafe as it is not clear whether one
169             // pointer would be "less" or "equal" to another, because we cannot know where llvm
170             // or the linker will place various statics in memory. Without this information the
171             // result of a comparison of addresses would differ between runtime and compile-time.
172             Rvalue::BinaryOp(_, ref lhs, _)
173                 if self.const_context && self.tcx.features().const_compare_raw_pointers =>
174             {
175                 if let ty::RawPtr(_) | ty::FnPtr(..) = lhs.ty(self.body, self.tcx).kind {
176                     self.register_violations(
177                         &[UnsafetyViolation {
178                             source_info: self.source_info,
179                             description: Symbol::intern("pointer operation"),
180                             details: Symbol::intern("operations on pointers in constants"),
181                             kind: UnsafetyViolationKind::General,
182                         }],
183                         &[],
184                     );
185                 }
186             }
187             _ => {}
188         }
189         self.super_rvalue(rvalue, location);
190     }
191
192     fn visit_place(&mut self, place: &Place<'tcx>, context: PlaceContext, _location: Location) {
193         match place.base {
194             PlaceBase::Local(..) => {
195                 // Locals are safe.
196             }
197             PlaceBase::Static(box Static { kind: StaticKind::Promoted(_, _), .. }) => {
198                 bug!("unsafety checking should happen before promotion");
199             }
200             PlaceBase::Static(box Static { kind: StaticKind::Static, .. }) => {
201                 bug!("StaticKind::Static should not exist");
202             }
203         }
204
205         for (i, elem) in place.projection.iter().enumerate() {
206             let proj_base = &place.projection[..i];
207
208             if context.is_borrow() {
209                 if util::is_disaligned(self.tcx, self.body, self.param_env, place) {
210                     let source_info = self.source_info;
211                     let lint_root = self.body.source_scopes[source_info.scope]
212                         .local_data
213                         .as_ref()
214                         .assert_crate_local()
215                         .lint_root;
216                     self.register_violations(
217                         &[UnsafetyViolation {
218                             source_info,
219                             description: Symbol::intern("borrow of packed field"),
220                             details: Symbol::intern(
221                                 "fields of packed structs might be misaligned: dereferencing a \
222                             misaligned pointer or even just creating a misaligned reference \
223                             is undefined behavior",
224                             ),
225                             kind: UnsafetyViolationKind::BorrowPacked(lint_root),
226                         }],
227                         &[],
228                     );
229                 }
230             }
231             let is_borrow_of_interior_mut = context.is_borrow()
232                 && !Place::ty_from(&place.base, proj_base, self.body, self.tcx).ty.is_freeze(
233                     self.tcx,
234                     self.param_env,
235                     self.source_info.span,
236                 );
237             // prevent
238             // * `&mut x.field`
239             // * `x.field = y;`
240             // * `&x.field` if `field`'s type has interior mutability
241             // because either of these would allow modifying the layout constrained field and
242             // insert values that violate the layout constraints.
243             if context.is_mutating_use() || is_borrow_of_interior_mut {
244                 self.check_mut_borrowing_layout_constrained_field(place, context.is_mutating_use());
245             }
246             let old_source_info = self.source_info;
247             if let (PlaceBase::Local(local), []) = (&place.base, proj_base) {
248                 let decl = &self.body.local_decls[*local];
249                 if decl.internal {
250                     // Internal locals are used in the `move_val_init` desugaring.
251                     // We want to check unsafety against the source info of the
252                     // desugaring, rather than the source info of the RHS.
253                     self.source_info = self.body.local_decls[*local].source_info;
254                 } else if let LocalInfo::StaticRef { def_id, .. } = decl.local_info {
255                     if self.tcx.is_mutable_static(def_id) {
256                         self.require_unsafe(
257                             "use of mutable static",
258                             "mutable statics can be mutated by multiple threads: aliasing \
259                         violations or data races will cause undefined behavior",
260                             UnsafetyViolationKind::General,
261                         );
262                         return;
263                     } else if self.tcx.is_foreign_item(def_id) {
264                         self.require_unsafe(
265                             "use of extern static",
266                             "extern statics are not controlled by the Rust type system: \
267                         invalid data, aliasing violations or data races will cause \
268                         undefined behavior",
269                             UnsafetyViolationKind::General,
270                         );
271                         return;
272                     }
273                 }
274             }
275             let base_ty = Place::ty_from(&place.base, proj_base, self.body, self.tcx).ty;
276             match base_ty.kind {
277                 ty::RawPtr(..) => self.require_unsafe(
278                     "dereference of raw pointer",
279                     "raw pointers may be NULL, dangling or unaligned; they can violate \
280                          aliasing rules and cause data races: all of these are undefined \
281                          behavior",
282                     UnsafetyViolationKind::General,
283                 ),
284                 ty::Adt(adt, _) => {
285                     if adt.is_union() {
286                         if context == PlaceContext::MutatingUse(MutatingUseContext::Store)
287                             || context == PlaceContext::MutatingUse(MutatingUseContext::Drop)
288                             || context == PlaceContext::MutatingUse(MutatingUseContext::AsmOutput)
289                         {
290                             let elem_ty = match elem {
291                                 ProjectionElem::Field(_, ty) => ty,
292                                 _ => span_bug!(
293                                     self.source_info.span,
294                                     "non-field projection {:?} from union?",
295                                     place
296                                 ),
297                             };
298                             if !elem_ty.is_copy_modulo_regions(
299                                 self.tcx,
300                                 self.param_env,
301                                 self.source_info.span,
302                             ) {
303                                 self.require_unsafe(
304                                     "assignment to non-`Copy` union field",
305                                     "the previous content of the field will be dropped, which \
306                                      causes undefined behavior if the field was not properly \
307                                      initialized",
308                                     UnsafetyViolationKind::GeneralAndConstFn,
309                                 )
310                             } else {
311                                 // write to non-move union, safe
312                             }
313                         } else {
314                             self.require_unsafe(
315                                 "access to union field",
316                                 "the field may not be properly initialized: using \
317                                  uninitialized data will cause undefined behavior",
318                                 UnsafetyViolationKind::GeneralAndConstFn,
319                             )
320                         }
321                     }
322                 }
323                 _ => {}
324             }
325             self.source_info = old_source_info;
326         }
327     }
328 }
329
330 impl<'a, 'tcx> UnsafetyChecker<'a, 'tcx> {
331     fn require_unsafe(
332         &mut self,
333         description: &'static str,
334         details: &'static str,
335         kind: UnsafetyViolationKind,
336     ) {
337         let source_info = self.source_info;
338         self.register_violations(
339             &[UnsafetyViolation {
340                 source_info,
341                 description: Symbol::intern(description),
342                 details: Symbol::intern(details),
343                 kind,
344             }],
345             &[],
346         );
347     }
348
349     fn register_violations(
350         &mut self,
351         violations: &[UnsafetyViolation],
352         unsafe_blocks: &[(hir::HirId, bool)],
353     ) {
354         let safety = self.body.source_scopes[self.source_info.scope]
355             .local_data
356             .as_ref()
357             .assert_crate_local()
358             .safety;
359         let within_unsafe = match safety {
360             // `unsafe` blocks are required in safe code
361             Safety::Safe => {
362                 for violation in violations {
363                     let mut violation = violation.clone();
364                     match violation.kind {
365                         UnsafetyViolationKind::GeneralAndConstFn
366                         | UnsafetyViolationKind::General => {}
367                         UnsafetyViolationKind::BorrowPacked(_) => {
368                             if self.min_const_fn {
369                                 // const fns don't need to be backwards compatible and can
370                                 // emit these violations as a hard error instead of a backwards
371                                 // compat lint
372                                 violation.kind = UnsafetyViolationKind::General;
373                             }
374                         }
375                     }
376                     if !self.violations.contains(&violation) {
377                         self.violations.push(violation)
378                     }
379                 }
380                 false
381             }
382             // `unsafe` function bodies allow unsafe without additional unsafe blocks
383             Safety::BuiltinUnsafe | Safety::FnUnsafe => true,
384             Safety::ExplicitUnsafe(hir_id) => {
385                 // mark unsafe block as used if there are any unsafe operations inside
386                 if !violations.is_empty() {
387                     self.used_unsafe.insert(hir_id);
388                 }
389                 // only some unsafety is allowed in const fn
390                 if self.min_const_fn {
391                     for violation in violations {
392                         match violation.kind {
393                             // these unsafe things are stable in const fn
394                             UnsafetyViolationKind::GeneralAndConstFn => {}
395                             // these things are forbidden in const fns
396                             UnsafetyViolationKind::General
397                             | UnsafetyViolationKind::BorrowPacked(_) => {
398                                 let mut violation = violation.clone();
399                                 // const fns don't need to be backwards compatible and can
400                                 // emit these violations as a hard error instead of a backwards
401                                 // compat lint
402                                 violation.kind = UnsafetyViolationKind::General;
403                                 if !self.violations.contains(&violation) {
404                                     self.violations.push(violation)
405                                 }
406                             }
407                         }
408                     }
409                 }
410                 true
411             }
412         };
413         self.inherited_blocks.extend(
414             unsafe_blocks.iter().map(|&(hir_id, is_used)| (hir_id, is_used && !within_unsafe)),
415         );
416     }
417     fn check_mut_borrowing_layout_constrained_field(
418         &mut self,
419         place: &Place<'tcx>,
420         is_mut_use: bool,
421     ) {
422         let mut cursor = place.projection.as_ref();
423         while let &[ref proj_base @ .., elem] = cursor {
424             cursor = proj_base;
425
426             match elem {
427                 ProjectionElem::Field(..) => {
428                     let ty =
429                         Place::ty_from(&place.base, proj_base, &self.body.local_decls, self.tcx).ty;
430                     match ty.kind {
431                         ty::Adt(def, _) => match self.tcx.layout_scalar_valid_range(def.did) {
432                             (Bound::Unbounded, Bound::Unbounded) => {}
433                             _ => {
434                                 let (description, details) = if is_mut_use {
435                                     (
436                                         "mutation of layout constrained field",
437                                         "mutating layout constrained fields cannot statically be \
438                                         checked for valid values",
439                                     )
440                                 } else {
441                                     (
442                                         "borrow of layout constrained field with interior \
443                                         mutability",
444                                         "references to fields of layout constrained fields \
445                                         lose the constraints. Coupled with interior mutability, \
446                                         the field can be changed to invalid values",
447                                     )
448                                 };
449                                 let source_info = self.source_info;
450                                 self.register_violations(
451                                     &[UnsafetyViolation {
452                                         source_info,
453                                         description: Symbol::intern(description),
454                                         details: Symbol::intern(details),
455                                         kind: UnsafetyViolationKind::GeneralAndConstFn,
456                                     }],
457                                     &[],
458                                 );
459                             }
460                         },
461                         _ => {}
462                     }
463                 }
464                 _ => {}
465             }
466         }
467     }
468 }
469
470 pub(crate) fn provide(providers: &mut Providers<'_>) {
471     *providers = Providers { unsafety_check_result, unsafe_derive_on_repr_packed, ..*providers };
472 }
473
474 struct UnusedUnsafeVisitor<'a> {
475     used_unsafe: &'a FxHashSet<hir::HirId>,
476     unsafe_blocks: &'a mut Vec<(hir::HirId, bool)>,
477 }
478
479 impl<'a, 'tcx> intravisit::Visitor<'tcx> for UnusedUnsafeVisitor<'a> {
480     type Map = Map<'tcx>;
481
482     fn nested_visit_map<'this>(&'this mut self) -> intravisit::NestedVisitorMap<'this, Self::Map> {
483         intravisit::NestedVisitorMap::None
484     }
485
486     fn visit_block(&mut self, block: &'tcx hir::Block<'tcx>) {
487         intravisit::walk_block(self, block);
488
489         if let hir::BlockCheckMode::UnsafeBlock(hir::UnsafeSource::UserProvided) = block.rules {
490             self.unsafe_blocks.push((block.hir_id, self.used_unsafe.contains(&block.hir_id)));
491         }
492     }
493 }
494
495 fn check_unused_unsafe(
496     tcx: TyCtxt<'_>,
497     def_id: DefId,
498     used_unsafe: &FxHashSet<hir::HirId>,
499     unsafe_blocks: &mut Vec<(hir::HirId, bool)>,
500 ) {
501     let body_id =
502         tcx.hir().as_local_hir_id(def_id).and_then(|hir_id| tcx.hir().maybe_body_owned_by(hir_id));
503
504     let body_id = match body_id {
505         Some(body) => body,
506         None => {
507             debug!("check_unused_unsafe({:?}) - no body found", def_id);
508             return;
509         }
510     };
511     let body = tcx.hir().body(body_id);
512     debug!("check_unused_unsafe({:?}, body={:?}, used_unsafe={:?})", def_id, body, used_unsafe);
513
514     let mut visitor = UnusedUnsafeVisitor { used_unsafe, unsafe_blocks };
515     intravisit::Visitor::visit_body(&mut visitor, body);
516 }
517
518 fn unsafety_check_result(tcx: TyCtxt<'_>, def_id: DefId) -> UnsafetyCheckResult {
519     debug!("unsafety_violations({:?})", def_id);
520
521     // N.B., this borrow is valid because all the consumers of
522     // `mir_built` force this.
523     let body = &tcx.mir_built(def_id).borrow();
524
525     let param_env = tcx.param_env(def_id);
526
527     let id = tcx.hir().as_local_hir_id(def_id).unwrap();
528     let (const_context, min_const_fn) = match tcx.hir().body_owner_kind(id) {
529         hir::BodyOwnerKind::Closure => (false, false),
530         hir::BodyOwnerKind::Fn => (is_const_fn(tcx, def_id), is_min_const_fn(tcx, def_id)),
531         hir::BodyOwnerKind::Const | hir::BodyOwnerKind::Static(_) => (true, false),
532     };
533     let mut checker = UnsafetyChecker::new(const_context, min_const_fn, body, tcx, param_env);
534     // mir_built ensures that body has a computed cache, so we don't (and can't) attempt to
535     // recompute it here.
536     let body = body.unwrap_read_only();
537     checker.visit_body(body);
538
539     check_unused_unsafe(tcx, def_id, &checker.used_unsafe, &mut checker.inherited_blocks);
540     UnsafetyCheckResult {
541         violations: checker.violations.into(),
542         unsafe_blocks: checker.inherited_blocks.into(),
543     }
544 }
545
546 fn unsafe_derive_on_repr_packed(tcx: TyCtxt<'_>, def_id: DefId) {
547     let lint_hir_id = tcx
548         .hir()
549         .as_local_hir_id(def_id)
550         .unwrap_or_else(|| bug!("checking unsafety for non-local def id {:?}", def_id));
551
552     // FIXME: when we make this a hard error, this should have its
553     // own error code.
554     let message = if tcx.generics_of(def_id).own_requires_monomorphization() {
555         "`#[derive]` can't be used on a `#[repr(packed)]` struct with \
556          type or const parameters (error E0133)"
557             .to_string()
558     } else {
559         "`#[derive]` can't be used on a `#[repr(packed)]` struct that \
560          does not derive Copy (error E0133)"
561             .to_string()
562     };
563     tcx.lint_hir(SAFE_PACKED_BORROWS, lint_hir_id, tcx.def_span(def_id), &message);
564 }
565
566 /// Returns the `HirId` for an enclosing scope that is also `unsafe`.
567 fn is_enclosed(
568     tcx: TyCtxt<'_>,
569     used_unsafe: &FxHashSet<hir::HirId>,
570     id: hir::HirId,
571 ) -> Option<(String, hir::HirId)> {
572     let parent_id = tcx.hir().get_parent_node(id);
573     if parent_id != id {
574         if used_unsafe.contains(&parent_id) {
575             Some(("block".to_string(), parent_id))
576         } else if let Some(Node::Item(&hir::Item {
577             kind: hir::ItemKind::Fn(ref sig, _, _), ..
578         })) = tcx.hir().find(parent_id)
579         {
580             match sig.header.unsafety {
581                 hir::Unsafety::Unsafe => Some(("fn".to_string(), parent_id)),
582                 hir::Unsafety::Normal => None,
583             }
584         } else {
585             is_enclosed(tcx, used_unsafe, parent_id)
586         }
587     } else {
588         None
589     }
590 }
591
592 fn report_unused_unsafe(tcx: TyCtxt<'_>, used_unsafe: &FxHashSet<hir::HirId>, id: hir::HirId) {
593     let span = tcx.sess.source_map().def_span(tcx.hir().span(id));
594     let msg = "unnecessary `unsafe` block";
595     let mut db = tcx.struct_span_lint_hir(UNUSED_UNSAFE, id, span, msg);
596     db.span_label(span, msg);
597     if let Some((kind, id)) = is_enclosed(tcx, used_unsafe, id) {
598         db.span_label(
599             tcx.sess.source_map().def_span(tcx.hir().span(id)),
600             format!("because it's nested under this `unsafe` {}", kind),
601         );
602     }
603     db.emit();
604 }
605
606 fn builtin_derive_def_id(tcx: TyCtxt<'_>, def_id: DefId) -> Option<DefId> {
607     debug!("builtin_derive_def_id({:?})", def_id);
608     if let Some(impl_def_id) = tcx.impl_of_method(def_id) {
609         if tcx.has_attr(impl_def_id, sym::automatically_derived) {
610             debug!("builtin_derive_def_id({:?}) - is {:?}", def_id, impl_def_id);
611             Some(impl_def_id)
612         } else {
613             debug!("builtin_derive_def_id({:?}) - not automatically derived", def_id);
614             None
615         }
616     } else {
617         debug!("builtin_derive_def_id({:?}) - not a method", def_id);
618         None
619     }
620 }
621
622 pub fn check_unsafety(tcx: TyCtxt<'_>, def_id: DefId) {
623     debug!("check_unsafety({:?})", def_id);
624
625     // closures are handled by their parent fn.
626     if tcx.is_closure(def_id) {
627         return;
628     }
629
630     let UnsafetyCheckResult { violations, unsafe_blocks } = tcx.unsafety_check_result(def_id);
631
632     for &UnsafetyViolation { source_info, description, details, kind } in violations.iter() {
633         // Report an error.
634         match kind {
635             UnsafetyViolationKind::GeneralAndConstFn | UnsafetyViolationKind::General => {
636                 struct_span_err!(
637                     tcx.sess,
638                     source_info.span,
639                     E0133,
640                     "{} is unsafe and requires unsafe function or block",
641                     description
642                 )
643                 .span_label(source_info.span, &*description.as_str())
644                 .note(&details.as_str())
645                 .emit();
646             }
647             UnsafetyViolationKind::BorrowPacked(lint_hir_id) => {
648                 if let Some(impl_def_id) = builtin_derive_def_id(tcx, def_id) {
649                     tcx.unsafe_derive_on_repr_packed(impl_def_id);
650                 } else {
651                     tcx.lint_node_note(
652                         SAFE_PACKED_BORROWS,
653                         lint_hir_id,
654                         source_info.span,
655                         &format!(
656                             "{} is unsafe and requires unsafe function or block \
657                                             (error E0133)",
658                             description
659                         ),
660                         &details.as_str(),
661                     );
662                 }
663             }
664         }
665     }
666
667     let mut unsafe_blocks: Vec<_> = unsafe_blocks.into_iter().collect();
668     unsafe_blocks.sort_by_cached_key(|(hir_id, _)| tcx.hir().hir_to_node_id(*hir_id));
669     let used_unsafe: FxHashSet<_> =
670         unsafe_blocks.iter().flat_map(|&&(id, used)| used.then_some(id)).collect();
671     for &(block_id, is_used) in unsafe_blocks {
672         if !is_used {
673             report_unused_unsafe(tcx, &used_unsafe, block_id);
674         }
675     }
676 }