]> git.lizzy.rs Git - rust.git/blob - src/librustc_mir/transform/check_unsafety.rs
017d0f34674105ef48bbc17e7d629677cce10747
[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         }
198
199         for (i, elem) in place.projection.iter().enumerate() {
200             let proj_base = &place.projection[..i];
201
202             if context.is_borrow() {
203                 if util::is_disaligned(self.tcx, self.body, self.param_env, place) {
204                     let source_info = self.source_info;
205                     let lint_root = self.body.source_scopes[source_info.scope]
206                         .local_data
207                         .as_ref()
208                         .assert_crate_local()
209                         .lint_root;
210                     self.register_violations(
211                         &[UnsafetyViolation {
212                             source_info,
213                             description: Symbol::intern("borrow of packed field"),
214                             details: Symbol::intern(
215                                 "fields of packed structs might be misaligned: dereferencing a \
216                             misaligned pointer or even just creating a misaligned reference \
217                             is undefined behavior",
218                             ),
219                             kind: UnsafetyViolationKind::BorrowPacked(lint_root),
220                         }],
221                         &[],
222                     );
223                 }
224             }
225             let is_borrow_of_interior_mut = context.is_borrow()
226                 && !Place::ty_from(&place.base, proj_base, self.body, self.tcx).ty.is_freeze(
227                     self.tcx,
228                     self.param_env,
229                     self.source_info.span,
230                 );
231             // prevent
232             // * `&mut x.field`
233             // * `x.field = y;`
234             // * `&x.field` if `field`'s type has interior mutability
235             // because either of these would allow modifying the layout constrained field and
236             // insert values that violate the layout constraints.
237             if context.is_mutating_use() || is_borrow_of_interior_mut {
238                 self.check_mut_borrowing_layout_constrained_field(place, context.is_mutating_use());
239             }
240             let old_source_info = self.source_info;
241             if let (PlaceBase::Local(local), []) = (&place.base, proj_base) {
242                 let decl = &self.body.local_decls[*local];
243                 if decl.internal {
244                     // Internal locals are used in the `move_val_init` desugaring.
245                     // We want to check unsafety against the source info of the
246                     // desugaring, rather than the source info of the RHS.
247                     self.source_info = self.body.local_decls[*local].source_info;
248                 } else if let LocalInfo::StaticRef { def_id, .. } = decl.local_info {
249                     if self.tcx.is_mutable_static(def_id) {
250                         self.require_unsafe(
251                             "use of mutable static",
252                             "mutable statics can be mutated by multiple threads: aliasing \
253                         violations or data races will cause undefined behavior",
254                             UnsafetyViolationKind::General,
255                         );
256                         return;
257                     } else if self.tcx.is_foreign_item(def_id) {
258                         self.require_unsafe(
259                             "use of extern static",
260                             "extern statics are not controlled by the Rust type system: \
261                         invalid data, aliasing violations or data races will cause \
262                         undefined behavior",
263                             UnsafetyViolationKind::General,
264                         );
265                         return;
266                     }
267                 }
268             }
269             let base_ty = Place::ty_from(&place.base, proj_base, self.body, self.tcx).ty;
270             match base_ty.kind {
271                 ty::RawPtr(..) => self.require_unsafe(
272                     "dereference of raw pointer",
273                     "raw pointers may be NULL, dangling or unaligned; they can violate \
274                          aliasing rules and cause data races: all of these are undefined \
275                          behavior",
276                     UnsafetyViolationKind::General,
277                 ),
278                 ty::Adt(adt, _) => {
279                     if adt.is_union() {
280                         if context == PlaceContext::MutatingUse(MutatingUseContext::Store)
281                             || context == PlaceContext::MutatingUse(MutatingUseContext::Drop)
282                             || context == PlaceContext::MutatingUse(MutatingUseContext::AsmOutput)
283                         {
284                             let elem_ty = match elem {
285                                 ProjectionElem::Field(_, ty) => ty,
286                                 _ => span_bug!(
287                                     self.source_info.span,
288                                     "non-field projection {:?} from union?",
289                                     place
290                                 ),
291                             };
292                             if !elem_ty.is_copy_modulo_regions(
293                                 self.tcx,
294                                 self.param_env,
295                                 self.source_info.span,
296                             ) {
297                                 self.require_unsafe(
298                                     "assignment to non-`Copy` union field",
299                                     "the previous content of the field will be dropped, which \
300                                      causes undefined behavior if the field was not properly \
301                                      initialized",
302                                     UnsafetyViolationKind::GeneralAndConstFn,
303                                 )
304                             } else {
305                                 // write to non-move union, safe
306                             }
307                         } else {
308                             self.require_unsafe(
309                                 "access to union field",
310                                 "the field may not be properly initialized: using \
311                                  uninitialized data will cause undefined behavior",
312                                 UnsafetyViolationKind::GeneralAndConstFn,
313                             )
314                         }
315                     }
316                 }
317                 _ => {}
318             }
319             self.source_info = old_source_info;
320         }
321     }
322 }
323
324 impl<'a, 'tcx> UnsafetyChecker<'a, 'tcx> {
325     fn require_unsafe(
326         &mut self,
327         description: &'static str,
328         details: &'static str,
329         kind: UnsafetyViolationKind,
330     ) {
331         let source_info = self.source_info;
332         self.register_violations(
333             &[UnsafetyViolation {
334                 source_info,
335                 description: Symbol::intern(description),
336                 details: Symbol::intern(details),
337                 kind,
338             }],
339             &[],
340         );
341     }
342
343     fn register_violations(
344         &mut self,
345         violations: &[UnsafetyViolation],
346         unsafe_blocks: &[(hir::HirId, bool)],
347     ) {
348         let safety = self.body.source_scopes[self.source_info.scope]
349             .local_data
350             .as_ref()
351             .assert_crate_local()
352             .safety;
353         let within_unsafe = match safety {
354             // `unsafe` blocks are required in safe code
355             Safety::Safe => {
356                 for violation in violations {
357                     let mut violation = violation.clone();
358                     match violation.kind {
359                         UnsafetyViolationKind::GeneralAndConstFn
360                         | UnsafetyViolationKind::General => {}
361                         UnsafetyViolationKind::BorrowPacked(_) => {
362                             if self.min_const_fn {
363                                 // const fns don't need to be backwards compatible and can
364                                 // emit these violations as a hard error instead of a backwards
365                                 // compat lint
366                                 violation.kind = UnsafetyViolationKind::General;
367                             }
368                         }
369                     }
370                     if !self.violations.contains(&violation) {
371                         self.violations.push(violation)
372                     }
373                 }
374                 false
375             }
376             // `unsafe` function bodies allow unsafe without additional unsafe blocks
377             Safety::BuiltinUnsafe | Safety::FnUnsafe => true,
378             Safety::ExplicitUnsafe(hir_id) => {
379                 // mark unsafe block as used if there are any unsafe operations inside
380                 if !violations.is_empty() {
381                     self.used_unsafe.insert(hir_id);
382                 }
383                 // only some unsafety is allowed in const fn
384                 if self.min_const_fn {
385                     for violation in violations {
386                         match violation.kind {
387                             // these unsafe things are stable in const fn
388                             UnsafetyViolationKind::GeneralAndConstFn => {}
389                             // these things are forbidden in const fns
390                             UnsafetyViolationKind::General
391                             | UnsafetyViolationKind::BorrowPacked(_) => {
392                                 let mut violation = violation.clone();
393                                 // const fns don't need to be backwards compatible and can
394                                 // emit these violations as a hard error instead of a backwards
395                                 // compat lint
396                                 violation.kind = UnsafetyViolationKind::General;
397                                 if !self.violations.contains(&violation) {
398                                     self.violations.push(violation)
399                                 }
400                             }
401                         }
402                     }
403                 }
404                 true
405             }
406         };
407         self.inherited_blocks.extend(
408             unsafe_blocks.iter().map(|&(hir_id, is_used)| (hir_id, is_used && !within_unsafe)),
409         );
410     }
411     fn check_mut_borrowing_layout_constrained_field(
412         &mut self,
413         place: &Place<'tcx>,
414         is_mut_use: bool,
415     ) {
416         let mut cursor = place.projection.as_ref();
417         while let &[ref proj_base @ .., elem] = cursor {
418             cursor = proj_base;
419
420             match elem {
421                 ProjectionElem::Field(..) => {
422                     let ty =
423                         Place::ty_from(&place.base, proj_base, &self.body.local_decls, self.tcx).ty;
424                     match ty.kind {
425                         ty::Adt(def, _) => match self.tcx.layout_scalar_valid_range(def.did) {
426                             (Bound::Unbounded, Bound::Unbounded) => {}
427                             _ => {
428                                 let (description, details) = if is_mut_use {
429                                     (
430                                         "mutation of layout constrained field",
431                                         "mutating layout constrained fields cannot statically be \
432                                         checked for valid values",
433                                     )
434                                 } else {
435                                     (
436                                         "borrow of layout constrained field with interior \
437                                         mutability",
438                                         "references to fields of layout constrained fields \
439                                         lose the constraints. Coupled with interior mutability, \
440                                         the field can be changed to invalid values",
441                                     )
442                                 };
443                                 let source_info = self.source_info;
444                                 self.register_violations(
445                                     &[UnsafetyViolation {
446                                         source_info,
447                                         description: Symbol::intern(description),
448                                         details: Symbol::intern(details),
449                                         kind: UnsafetyViolationKind::GeneralAndConstFn,
450                                     }],
451                                     &[],
452                                 );
453                             }
454                         },
455                         _ => {}
456                     }
457                 }
458                 _ => {}
459             }
460         }
461     }
462 }
463
464 pub(crate) fn provide(providers: &mut Providers<'_>) {
465     *providers = Providers { unsafety_check_result, unsafe_derive_on_repr_packed, ..*providers };
466 }
467
468 struct UnusedUnsafeVisitor<'a> {
469     used_unsafe: &'a FxHashSet<hir::HirId>,
470     unsafe_blocks: &'a mut Vec<(hir::HirId, bool)>,
471 }
472
473 impl<'a, 'tcx> intravisit::Visitor<'tcx> for UnusedUnsafeVisitor<'a> {
474     type Map = Map<'tcx>;
475
476     fn nested_visit_map<'this>(&'this mut self) -> intravisit::NestedVisitorMap<'this, Self::Map> {
477         intravisit::NestedVisitorMap::None
478     }
479
480     fn visit_block(&mut self, block: &'tcx hir::Block<'tcx>) {
481         intravisit::walk_block(self, block);
482
483         if let hir::BlockCheckMode::UnsafeBlock(hir::UnsafeSource::UserProvided) = block.rules {
484             self.unsafe_blocks.push((block.hir_id, self.used_unsafe.contains(&block.hir_id)));
485         }
486     }
487 }
488
489 fn check_unused_unsafe(
490     tcx: TyCtxt<'_>,
491     def_id: DefId,
492     used_unsafe: &FxHashSet<hir::HirId>,
493     unsafe_blocks: &mut Vec<(hir::HirId, bool)>,
494 ) {
495     let body_id =
496         tcx.hir().as_local_hir_id(def_id).and_then(|hir_id| tcx.hir().maybe_body_owned_by(hir_id));
497
498     let body_id = match body_id {
499         Some(body) => body,
500         None => {
501             debug!("check_unused_unsafe({:?}) - no body found", def_id);
502             return;
503         }
504     };
505     let body = tcx.hir().body(body_id);
506     debug!("check_unused_unsafe({:?}, body={:?}, used_unsafe={:?})", def_id, body, used_unsafe);
507
508     let mut visitor = UnusedUnsafeVisitor { used_unsafe, unsafe_blocks };
509     intravisit::Visitor::visit_body(&mut visitor, body);
510 }
511
512 fn unsafety_check_result(tcx: TyCtxt<'_>, def_id: DefId) -> UnsafetyCheckResult {
513     debug!("unsafety_violations({:?})", def_id);
514
515     // N.B., this borrow is valid because all the consumers of
516     // `mir_built` force this.
517     let body = &tcx.mir_built(def_id).borrow();
518
519     let param_env = tcx.param_env(def_id);
520
521     let id = tcx.hir().as_local_hir_id(def_id).unwrap();
522     let (const_context, min_const_fn) = match tcx.hir().body_owner_kind(id) {
523         hir::BodyOwnerKind::Closure => (false, false),
524         hir::BodyOwnerKind::Fn => (is_const_fn(tcx, def_id), is_min_const_fn(tcx, def_id)),
525         hir::BodyOwnerKind::Const | hir::BodyOwnerKind::Static(_) => (true, false),
526     };
527     let mut checker = UnsafetyChecker::new(const_context, min_const_fn, body, tcx, param_env);
528     // mir_built ensures that body has a computed cache, so we don't (and can't) attempt to
529     // recompute it here.
530     let body = body.unwrap_read_only();
531     checker.visit_body(body);
532
533     check_unused_unsafe(tcx, def_id, &checker.used_unsafe, &mut checker.inherited_blocks);
534     UnsafetyCheckResult {
535         violations: checker.violations.into(),
536         unsafe_blocks: checker.inherited_blocks.into(),
537     }
538 }
539
540 fn unsafe_derive_on_repr_packed(tcx: TyCtxt<'_>, def_id: DefId) {
541     let lint_hir_id = tcx
542         .hir()
543         .as_local_hir_id(def_id)
544         .unwrap_or_else(|| bug!("checking unsafety for non-local def id {:?}", def_id));
545
546     // FIXME: when we make this a hard error, this should have its
547     // own error code.
548     let message = if tcx.generics_of(def_id).own_requires_monomorphization() {
549         "`#[derive]` can't be used on a `#[repr(packed)]` struct with \
550          type or const parameters (error E0133)"
551             .to_string()
552     } else {
553         "`#[derive]` can't be used on a `#[repr(packed)]` struct that \
554          does not derive Copy (error E0133)"
555             .to_string()
556     };
557     tcx.lint_hir(SAFE_PACKED_BORROWS, lint_hir_id, tcx.def_span(def_id), &message);
558 }
559
560 /// Returns the `HirId` for an enclosing scope that is also `unsafe`.
561 fn is_enclosed(
562     tcx: TyCtxt<'_>,
563     used_unsafe: &FxHashSet<hir::HirId>,
564     id: hir::HirId,
565 ) -> Option<(String, hir::HirId)> {
566     let parent_id = tcx.hir().get_parent_node(id);
567     if parent_id != id {
568         if used_unsafe.contains(&parent_id) {
569             Some(("block".to_string(), parent_id))
570         } else if let Some(Node::Item(&hir::Item {
571             kind: hir::ItemKind::Fn(ref sig, _, _), ..
572         })) = tcx.hir().find(parent_id)
573         {
574             match sig.header.unsafety {
575                 hir::Unsafety::Unsafe => Some(("fn".to_string(), parent_id)),
576                 hir::Unsafety::Normal => None,
577             }
578         } else {
579             is_enclosed(tcx, used_unsafe, parent_id)
580         }
581     } else {
582         None
583     }
584 }
585
586 fn report_unused_unsafe(tcx: TyCtxt<'_>, used_unsafe: &FxHashSet<hir::HirId>, id: hir::HirId) {
587     let span = tcx.sess.source_map().def_span(tcx.hir().span(id));
588     let msg = "unnecessary `unsafe` block";
589     let mut db = tcx.struct_span_lint_hir(UNUSED_UNSAFE, id, span, msg);
590     db.span_label(span, msg);
591     if let Some((kind, id)) = is_enclosed(tcx, used_unsafe, id) {
592         db.span_label(
593             tcx.sess.source_map().def_span(tcx.hir().span(id)),
594             format!("because it's nested under this `unsafe` {}", kind),
595         );
596     }
597     db.emit();
598 }
599
600 fn builtin_derive_def_id(tcx: TyCtxt<'_>, def_id: DefId) -> Option<DefId> {
601     debug!("builtin_derive_def_id({:?})", def_id);
602     if let Some(impl_def_id) = tcx.impl_of_method(def_id) {
603         if tcx.has_attr(impl_def_id, sym::automatically_derived) {
604             debug!("builtin_derive_def_id({:?}) - is {:?}", def_id, impl_def_id);
605             Some(impl_def_id)
606         } else {
607             debug!("builtin_derive_def_id({:?}) - not automatically derived", def_id);
608             None
609         }
610     } else {
611         debug!("builtin_derive_def_id({:?}) - not a method", def_id);
612         None
613     }
614 }
615
616 pub fn check_unsafety(tcx: TyCtxt<'_>, def_id: DefId) {
617     debug!("check_unsafety({:?})", def_id);
618
619     // closures are handled by their parent fn.
620     if tcx.is_closure(def_id) {
621         return;
622     }
623
624     let UnsafetyCheckResult { violations, unsafe_blocks } = tcx.unsafety_check_result(def_id);
625
626     for &UnsafetyViolation { source_info, description, details, kind } in violations.iter() {
627         // Report an error.
628         match kind {
629             UnsafetyViolationKind::GeneralAndConstFn | UnsafetyViolationKind::General => {
630                 struct_span_err!(
631                     tcx.sess,
632                     source_info.span,
633                     E0133,
634                     "{} is unsafe and requires unsafe function or block",
635                     description
636                 )
637                 .span_label(source_info.span, &*description.as_str())
638                 .note(&details.as_str())
639                 .emit();
640             }
641             UnsafetyViolationKind::BorrowPacked(lint_hir_id) => {
642                 if let Some(impl_def_id) = builtin_derive_def_id(tcx, def_id) {
643                     tcx.unsafe_derive_on_repr_packed(impl_def_id);
644                 } else {
645                     tcx.lint_node_note(
646                         SAFE_PACKED_BORROWS,
647                         lint_hir_id,
648                         source_info.span,
649                         &format!(
650                             "{} is unsafe and requires unsafe function or block \
651                                             (error E0133)",
652                             description
653                         ),
654                         &details.as_str(),
655                     );
656                 }
657             }
658         }
659     }
660
661     let mut unsafe_blocks: Vec<_> = unsafe_blocks.into_iter().collect();
662     unsafe_blocks.sort_by_cached_key(|(hir_id, _)| tcx.hir().hir_to_node_id(*hir_id));
663     let used_unsafe: FxHashSet<_> =
664         unsafe_blocks.iter().flat_map(|&&(id, used)| used.then_some(id)).collect();
665     for &(block_id, is_used) in unsafe_blocks {
666         if !is_used {
667             report_unused_unsafe(tcx, &used_unsafe, block_id);
668         }
669     }
670 }