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