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