]> git.lizzy.rs Git - rust.git/blob - src/librustc_mir/transform/check_unsafety.rs
Comment on the unsafety code for layout constrained fields
[rust.git] / src / librustc_mir / transform / check_unsafety.rs
1 // Copyright 2017 The Rust Project Developers. See the COPYRIGHT
2 // file at the top-level directory of this distribution and at
3 // http://rust-lang.org/COPYRIGHT.
4 //
5 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
6 // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
7 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
8 // option. This file may not be copied, modified, or distributed
9 // except according to those terms.
10
11 use rustc_data_structures::fx::FxHashSet;
12 use rustc_data_structures::indexed_vec::IndexVec;
13 use rustc_data_structures::sync::Lrc;
14
15 use rustc::ty::query::Providers;
16 use rustc::ty::{self, TyCtxt};
17 use rustc::hir;
18 use rustc::hir::Node;
19 use rustc::hir::def_id::DefId;
20 use rustc::lint::builtin::{SAFE_EXTERN_STATICS, SAFE_PACKED_BORROWS, UNUSED_UNSAFE};
21 use rustc::mir::*;
22 use rustc::mir::visit::{PlaceContext, Visitor, MutatingUseContext};
23
24 use syntax::ast;
25 use syntax::symbol::Symbol;
26
27 use std::ops::Bound;
28
29 use util;
30
31 pub struct UnsafetyChecker<'a, 'tcx: 'a> {
32     mir: &'a Mir<'tcx>,
33     min_const_fn: bool,
34     source_scope_local_data: &'a IndexVec<SourceScope, SourceScopeLocalData>,
35     violations: Vec<UnsafetyViolation>,
36     source_info: SourceInfo,
37     tcx: TyCtxt<'a, 'tcx, 'tcx>,
38     param_env: ty::ParamEnv<'tcx>,
39     /// mark an `unsafe` block as used, so we don't lint it
40     used_unsafe: FxHashSet<ast::NodeId>,
41     inherited_blocks: Vec<(ast::NodeId, bool)>,
42 }
43
44 impl<'a, 'gcx, 'tcx> UnsafetyChecker<'a, 'tcx> {
45     fn new(
46         min_const_fn: bool,
47         mir: &'a Mir<'tcx>,
48         source_scope_local_data: &'a IndexVec<SourceScope, SourceScopeLocalData>,
49         tcx: TyCtxt<'a, 'tcx, 'tcx>,
50         param_env: ty::ParamEnv<'tcx>,
51     ) -> Self {
52         Self {
53             mir,
54             min_const_fn,
55             source_scope_local_data,
56             violations: vec![],
57             source_info: SourceInfo {
58                 span: mir.span,
59                 scope: OUTERMOST_SOURCE_SCOPE
60             },
61             tcx,
62             param_env,
63             used_unsafe: Default::default(),
64             inherited_blocks: vec![],
65         }
66     }
67 }
68
69 impl<'a, 'tcx> Visitor<'tcx> for UnsafetyChecker<'a, 'tcx> {
70     fn visit_terminator(&mut self,
71                         block: BasicBlock,
72                         terminator: &Terminator<'tcx>,
73                         location: Location)
74     {
75         self.source_info = terminator.source_info;
76         match terminator.kind {
77             TerminatorKind::Goto { .. } |
78             TerminatorKind::SwitchInt { .. } |
79             TerminatorKind::Drop { .. } |
80             TerminatorKind::Yield { .. } |
81             TerminatorKind::Assert { .. } |
82             TerminatorKind::DropAndReplace { .. } |
83             TerminatorKind::GeneratorDrop |
84             TerminatorKind::Resume |
85             TerminatorKind::Abort |
86             TerminatorKind::Return |
87             TerminatorKind::Unreachable |
88             TerminatorKind::FalseEdges { .. } |
89             TerminatorKind::FalseUnwind { .. } => {
90                 // safe (at least as emitted during MIR construction)
91             }
92
93             TerminatorKind::Call { ref func, .. } => {
94                 let func_ty = func.ty(self.mir, self.tcx);
95                 let sig = func_ty.fn_sig(self.tcx);
96                 if let hir::Unsafety::Unsafe = sig.unsafety() {
97                     self.require_unsafe("call to unsafe function",
98                         "consult the function's documentation for information on how to avoid \
99                          undefined behavior", UnsafetyViolationKind::MinConstFn)
100                 }
101             }
102         }
103         self.super_terminator(block, terminator, location);
104     }
105
106     fn visit_statement(&mut self,
107                        block: BasicBlock,
108                        statement: &Statement<'tcx>,
109                        location: Location)
110     {
111         self.source_info = statement.source_info;
112         match statement.kind {
113             StatementKind::Assign(..) |
114             StatementKind::FakeRead(..) |
115             StatementKind::SetDiscriminant { .. } |
116             StatementKind::StorageLive(..) |
117             StatementKind::StorageDead(..) |
118             StatementKind::Retag { .. } |
119             StatementKind::EscapeToRaw { .. } |
120             StatementKind::AscribeUserType(..) |
121             StatementKind::Nop => {
122                 // safe (at least as emitted during MIR construction)
123             }
124
125             StatementKind::InlineAsm { .. } => {
126                 self.require_unsafe("use of inline assembly",
127                     "inline assembly is entirely unchecked and can cause undefined behavior",
128                     UnsafetyViolationKind::General)
129             },
130         }
131         self.super_statement(block, statement, location);
132     }
133
134     fn visit_rvalue(&mut self,
135                     rvalue: &Rvalue<'tcx>,
136                     location: Location)
137     {
138         if let &Rvalue::Aggregate(box ref aggregate, _) = rvalue {
139             match aggregate {
140                 &AggregateKind::Array(..) |
141                 &AggregateKind::Tuple => {}
142                 &AggregateKind::Adt(ref def, ..) => {
143                     match self.tcx.layout_scalar_valid_range(def.did) {
144                         (Bound::Unbounded, Bound::Unbounded) => {},
145                         _ => self.require_unsafe(
146                             "initializing type with `rustc_layout_scalar_valid_range` attr",
147                             "initializing a layout restricted type's field with a value outside \
148                             the valid range is undefined behavior",
149                             UnsafetyViolationKind::MinConstFn,
150                         ),
151                     }
152                 }
153                 &AggregateKind::Closure(def_id, _) |
154                 &AggregateKind::Generator(def_id, _, _) => {
155                     let UnsafetyCheckResult {
156                         violations, unsafe_blocks
157                     } = self.tcx.unsafety_check_result(def_id);
158                     self.register_violations(&violations, &unsafe_blocks);
159                 }
160             }
161         }
162         self.super_rvalue(rvalue, location);
163     }
164
165     fn visit_place(&mut self,
166                     place: &Place<'tcx>,
167                     context: PlaceContext<'tcx>,
168                     location: Location) {
169         match place {
170             &Place::Projection(box Projection {
171                 ref base, ref elem
172             }) => {
173                 if context.is_borrow() {
174                     if util::is_disaligned(self.tcx, self.mir, self.param_env, place) {
175                         let source_info = self.source_info;
176                         let lint_root =
177                             self.source_scope_local_data[source_info.scope].lint_root;
178                         self.register_violations(&[UnsafetyViolation {
179                             source_info,
180                             description: Symbol::intern("borrow of packed field").as_interned_str(),
181                             details:
182                                 Symbol::intern("fields of packed structs might be misaligned: \
183                                                 dereferencing a misaligned pointer or even just \
184                                                 creating a misaligned reference is undefined \
185                                                 behavior")
186                                     .as_interned_str(),
187                             kind: UnsafetyViolationKind::BorrowPacked(lint_root)
188                         }], &[]);
189                     }
190                 }
191                 let is_borrow_of_interior_mut = context.is_borrow() && !base
192                     .ty(self.mir, self.tcx)
193                     .to_ty(self.tcx)
194                     .is_freeze(self.tcx, self.param_env, self.source_info.span);
195                 // prevent
196                 // * `&mut x.field`
197                 // * `x.field = y;`
198                 // * `&x.field` if `field`'s type has interior mutability
199                 // because either of these would allow modifying the layout constrained field and
200                 // insert values that violate the layout constraints.
201                 if context.is_mutating_use() || is_borrow_of_interior_mut {
202                     self.check_mut_borrowing_layout_constrained_field(
203                         place, context.is_mutating_use(),
204                     );
205                 }
206                 let old_source_info = self.source_info;
207                 if let &Place::Local(local) = base {
208                     if self.mir.local_decls[local].internal {
209                         // Internal locals are used in the `move_val_init` desugaring.
210                         // We want to check unsafety against the source info of the
211                         // desugaring, rather than the source info of the RHS.
212                         self.source_info = self.mir.local_decls[local].source_info;
213                     }
214                 }
215                 let base_ty = base.ty(self.mir, self.tcx).to_ty(self.tcx);
216                 match base_ty.sty {
217                     ty::RawPtr(..) => {
218                         self.require_unsafe("dereference of raw pointer",
219                             "raw pointers may be NULL, dangling or unaligned; they can violate \
220                              aliasing rules and cause data races: all of these are undefined \
221                              behavior", UnsafetyViolationKind::General)
222                     }
223                     ty::Adt(adt, _) => {
224                         if adt.is_union() {
225                             if context == PlaceContext::MutatingUse(MutatingUseContext::Store) ||
226                                 context == PlaceContext::MutatingUse(MutatingUseContext::Drop) ||
227                                 context == PlaceContext::MutatingUse(
228                                     MutatingUseContext::AsmOutput
229                                 )
230                             {
231                                 let elem_ty = match elem {
232                                     &ProjectionElem::Field(_, ty) => ty,
233                                     _ => span_bug!(
234                                         self.source_info.span,
235                                         "non-field projection {:?} from union?",
236                                         place)
237                                 };
238                                 if elem_ty.moves_by_default(self.tcx, self.param_env,
239                                                             self.source_info.span) {
240                                     self.require_unsafe(
241                                         "assignment to non-`Copy` union field",
242                                         "the previous content of the field will be dropped, which \
243                                          causes undefined behavior if the field was not properly \
244                                          initialized", UnsafetyViolationKind::General)
245                                 } else {
246                                     // write to non-move union, safe
247                                 }
248                             } else {
249                                 self.require_unsafe("access to union field",
250                                     "the field may not be properly initialized: using \
251                                      uninitialized data will cause undefined behavior",
252                                      UnsafetyViolationKind::General)
253                             }
254                         }
255                     }
256                     _ => {}
257                 }
258                 self.source_info = old_source_info;
259             }
260             &Place::Local(..) => {
261                 // locals are safe
262             }
263             &Place::Promoted(_) => {
264                 bug!("unsafety checking should happen before promotion")
265             }
266             &Place::Static(box Static { def_id, ty: _ }) => {
267                 if self.tcx.is_static(def_id) == Some(hir::Mutability::MutMutable) {
268                     self.require_unsafe("use of mutable static",
269                         "mutable statics can be mutated by multiple threads: aliasing violations \
270                          or data races will cause undefined behavior",
271                          UnsafetyViolationKind::General);
272                 } else if self.tcx.is_foreign_item(def_id) {
273                     let source_info = self.source_info;
274                     let lint_root =
275                         self.source_scope_local_data[source_info.scope].lint_root;
276                     self.register_violations(&[UnsafetyViolation {
277                         source_info,
278                         description: Symbol::intern("use of extern static").as_interned_str(),
279                         details:
280                             Symbol::intern("extern statics are not controlled by the Rust type \
281                                             system: invalid data, aliasing violations or data \
282                                             races will cause undefined behavior")
283                                 .as_interned_str(),
284                         kind: UnsafetyViolationKind::ExternStatic(lint_root)
285                     }], &[]);
286                 }
287             }
288         };
289         self.super_place(place, context, location);
290     }
291 }
292
293 impl<'a, 'tcx> UnsafetyChecker<'a, 'tcx> {
294     fn require_unsafe(
295         &mut self,
296         description: &'static str,
297         details: &'static str,
298         kind: UnsafetyViolationKind,
299     ) {
300         let source_info = self.source_info;
301         self.register_violations(&[UnsafetyViolation {
302             source_info,
303             description: Symbol::intern(description).as_interned_str(),
304             details: Symbol::intern(details).as_interned_str(),
305             kind,
306         }], &[]);
307     }
308
309     fn register_violations(&mut self,
310                            violations: &[UnsafetyViolation],
311                            unsafe_blocks: &[(ast::NodeId, bool)]) {
312         let safety = self.source_scope_local_data[self.source_info.scope].safety;
313         let within_unsafe = match (safety, self.min_const_fn) {
314             // Erring on the safe side, pun intended
315             (Safety::BuiltinUnsafe, true) |
316             // mir building encodes const fn bodies as safe, even for `const unsafe fn`
317             (Safety::FnUnsafe, true) => bug!("const unsafe fn body treated as inherently unsafe"),
318             // `unsafe` blocks are required in safe code
319             (Safety::Safe, _) => {
320                 for violation in violations {
321                     let mut violation = violation.clone();
322                     if self.min_const_fn {
323                         // overwrite unsafety violation in const fn with a single hard error kind
324                         violation.kind = UnsafetyViolationKind::MinConstFn;
325                     } else if let UnsafetyViolationKind::MinConstFn = violation.kind {
326                         // outside of const fns we treat `MinConstFn` and `General` the same
327                         violation.kind = UnsafetyViolationKind::General;
328                     }
329                     if !self.violations.contains(&violation) {
330                         self.violations.push(violation)
331                     }
332                 }
333                 false
334             }
335             // regular `unsafe` function bodies allow unsafe without additional unsafe blocks
336             (Safety::BuiltinUnsafe, false) | (Safety::FnUnsafe, false) => true,
337             (Safety::ExplicitUnsafe(node_id), _) => {
338                 // mark unsafe block as used if there are any unsafe operations inside
339                 if !violations.is_empty() {
340                     self.used_unsafe.insert(node_id);
341                 }
342                 // only some unsafety is allowed in const fn
343                 if self.min_const_fn {
344                     for violation in violations {
345                         match violation.kind {
346                             // these are allowed
347                             UnsafetyViolationKind::MinConstFn
348                                 // if `#![feature(min_const_unsafe_fn)]` is active
349                                 if self.tcx.sess.features_untracked().min_const_unsafe_fn => {},
350                             _ => {
351                                 let mut violation = violation.clone();
352                                 // overwrite unsafety violation in const fn with a hard error
353                                 violation.kind = UnsafetyViolationKind::MinConstFn;
354                                 if !self.violations.contains(&violation) {
355                                     self.violations.push(violation)
356                                 }
357                             },
358                         }
359                     }
360                 }
361                 true
362             }
363         };
364         self.inherited_blocks.extend(unsafe_blocks.iter().map(|&(node_id, is_used)| {
365             (node_id, is_used && !within_unsafe)
366         }));
367     }
368     fn check_mut_borrowing_layout_constrained_field(
369         &mut self,
370         mut place: &Place<'tcx>,
371         is_mut_use: bool,
372     ) {
373         while let &Place::Projection(box Projection {
374             ref base, ref elem
375         }) = place {
376             match *elem {
377                 ProjectionElem::Field(..) => {
378                     let ty = base.ty(&self.mir.local_decls, self.tcx).to_ty(self.tcx);
379                     match ty.sty {
380                         ty::Adt(def, _) => match self.tcx.layout_scalar_valid_range(def.did) {
381                             (Bound::Unbounded, Bound::Unbounded) => {},
382                             _ => {
383                                 let (description, details) = if is_mut_use {
384                                     (
385                                         "mutation of layout constrained field",
386                                         "mutating layout constrained fields cannot statically be \
387                                         checked for valid values",
388                                     )
389                                 } else {
390                                     (
391                                         "borrow of layout constrained field with interior \
392                                         mutability",
393                                         "references to fields of layout constrained fields \
394                                         lose the constraints. Coupled with interior mutability, \
395                                         the field can be changed to invalid values",
396                                     )
397                                 };
398                                 let source_info = self.source_info;
399                                 self.register_violations(&[UnsafetyViolation {
400                                     source_info,
401                                     description: Symbol::intern(description).as_interned_str(),
402                                     details: Symbol::intern(details).as_interned_str(),
403                                     kind: UnsafetyViolationKind::MinConstFn,
404                                 }], &[]);
405                             }
406                         },
407                         _ => {}
408                     }
409                 }
410                 _ => {}
411             }
412             place = base;
413         }
414     }
415 }
416
417 pub(crate) fn provide(providers: &mut Providers) {
418     *providers = Providers {
419         unsafety_check_result,
420         unsafe_derive_on_repr_packed,
421         ..*providers
422     };
423 }
424
425 struct UnusedUnsafeVisitor<'a> {
426     used_unsafe: &'a FxHashSet<ast::NodeId>,
427     unsafe_blocks: &'a mut Vec<(ast::NodeId, bool)>,
428 }
429
430 impl<'a, 'tcx> hir::intravisit::Visitor<'tcx> for UnusedUnsafeVisitor<'a> {
431     fn nested_visit_map<'this>(&'this mut self) ->
432         hir::intravisit::NestedVisitorMap<'this, 'tcx>
433     {
434         hir::intravisit::NestedVisitorMap::None
435     }
436
437     fn visit_block(&mut self, block: &'tcx hir::Block) {
438         hir::intravisit::walk_block(self, block);
439
440         if let hir::UnsafeBlock(hir::UserProvided) = block.rules {
441             self.unsafe_blocks.push((block.id, self.used_unsafe.contains(&block.id)));
442         }
443     }
444 }
445
446 fn check_unused_unsafe<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>,
447                                  def_id: DefId,
448                                  used_unsafe: &FxHashSet<ast::NodeId>,
449                                  unsafe_blocks: &'a mut Vec<(ast::NodeId, bool)>)
450 {
451     let body_id =
452         tcx.hir.as_local_node_id(def_id).and_then(|node_id| {
453             tcx.hir.maybe_body_owned_by(node_id)
454         });
455
456     let body_id = match body_id {
457         Some(body) => body,
458         None => {
459             debug!("check_unused_unsafe({:?}) - no body found", def_id);
460             return
461         }
462     };
463     let body = tcx.hir.body(body_id);
464     debug!("check_unused_unsafe({:?}, body={:?}, used_unsafe={:?})",
465            def_id, body, used_unsafe);
466
467     let mut visitor =  UnusedUnsafeVisitor { used_unsafe, unsafe_blocks };
468     hir::intravisit::Visitor::visit_body(&mut visitor, body);
469 }
470
471 fn unsafety_check_result<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>, def_id: DefId)
472                                    -> UnsafetyCheckResult
473 {
474     debug!("unsafety_violations({:?})", def_id);
475
476     // NB: this borrow is valid because all the consumers of
477     // `mir_built` force this.
478     let mir = &tcx.mir_built(def_id).borrow();
479
480     let source_scope_local_data = match mir.source_scope_local_data {
481         ClearCrossCrate::Set(ref data) => data,
482         ClearCrossCrate::Clear => {
483             debug!("unsafety_violations: {:?} - remote, skipping", def_id);
484             return UnsafetyCheckResult {
485                 violations: Lrc::new([]),
486                 unsafe_blocks: Lrc::new([])
487             }
488         }
489     };
490
491     let param_env = tcx.param_env(def_id);
492     let mut checker = UnsafetyChecker::new(
493         tcx.is_const_fn(def_id) && tcx.is_min_const_fn(def_id),
494         mir, source_scope_local_data, tcx, param_env);
495     checker.visit_mir(mir);
496
497     check_unused_unsafe(tcx, def_id, &checker.used_unsafe, &mut checker.inherited_blocks);
498     UnsafetyCheckResult {
499         violations: checker.violations.into(),
500         unsafe_blocks: checker.inherited_blocks.into()
501     }
502 }
503
504 fn unsafe_derive_on_repr_packed<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>, def_id: DefId) {
505     let lint_node_id = match tcx.hir.as_local_node_id(def_id) {
506         Some(node_id) => node_id,
507         None => bug!("checking unsafety for non-local def id {:?}", def_id)
508     };
509
510     // FIXME: when we make this a hard error, this should have its
511     // own error code.
512     let message = if tcx.generics_of(def_id).own_counts().types != 0 {
513         "#[derive] can't be used on a #[repr(packed)] struct with \
514          type parameters (error E0133)".to_string()
515     } else {
516         "#[derive] can't be used on a #[repr(packed)] struct that \
517          does not derive Copy (error E0133)".to_string()
518     };
519     tcx.lint_node(SAFE_PACKED_BORROWS,
520                   lint_node_id,
521                   tcx.def_span(def_id),
522                   &message);
523 }
524
525 /// Return the NodeId for an enclosing scope that is also `unsafe`
526 fn is_enclosed(tcx: TyCtxt,
527                used_unsafe: &FxHashSet<ast::NodeId>,
528                id: ast::NodeId) -> Option<(String, ast::NodeId)> {
529     let parent_id = tcx.hir.get_parent_node(id);
530     if parent_id != id {
531         if used_unsafe.contains(&parent_id) {
532             Some(("block".to_string(), parent_id))
533         } else if let Some(Node::Item(&hir::Item {
534             node: hir::ItemKind::Fn(_, header, _, _),
535             ..
536         })) = tcx.hir.find(parent_id) {
537             match header.unsafety {
538                 hir::Unsafety::Unsafe => Some(("fn".to_string(), parent_id)),
539                 hir::Unsafety::Normal => None,
540             }
541         } else {
542             is_enclosed(tcx, used_unsafe, parent_id)
543         }
544     } else {
545         None
546     }
547 }
548
549 fn report_unused_unsafe(tcx: TyCtxt, used_unsafe: &FxHashSet<ast::NodeId>, id: ast::NodeId) {
550     let span = tcx.sess.source_map().def_span(tcx.hir.span(id));
551     let msg = "unnecessary `unsafe` block";
552     let mut db = tcx.struct_span_lint_node(UNUSED_UNSAFE, id, span, msg);
553     db.span_label(span, msg);
554     if let Some((kind, id)) = is_enclosed(tcx, used_unsafe, id) {
555         db.span_label(tcx.sess.source_map().def_span(tcx.hir.span(id)),
556                       format!("because it's nested under this `unsafe` {}", kind));
557     }
558     db.emit();
559 }
560
561 fn builtin_derive_def_id<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>, def_id: DefId) -> Option<DefId> {
562     debug!("builtin_derive_def_id({:?})", def_id);
563     if let Some(impl_def_id) = tcx.impl_of_method(def_id) {
564         if tcx.has_attr(impl_def_id, "automatically_derived") {
565             debug!("builtin_derive_def_id({:?}) - is {:?}", def_id, impl_def_id);
566             Some(impl_def_id)
567         } else {
568             debug!("builtin_derive_def_id({:?}) - not automatically derived", def_id);
569             None
570         }
571     } else {
572         debug!("builtin_derive_def_id({:?}) - not a method", def_id);
573         None
574     }
575 }
576
577 pub fn check_unsafety<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>, def_id: DefId) {
578     debug!("check_unsafety({:?})", def_id);
579
580     // closures are handled by their parent fn.
581     if tcx.is_closure(def_id) {
582         return;
583     }
584
585     let UnsafetyCheckResult {
586         violations,
587         unsafe_blocks
588     } = tcx.unsafety_check_result(def_id);
589
590     for &UnsafetyViolation {
591         source_info, description, details, kind
592     } in violations.iter() {
593         // Report an error.
594         match kind {
595             UnsafetyViolationKind::General => {
596                 struct_span_err!(
597                     tcx.sess, source_info.span, E0133,
598                     "{} is unsafe and requires unsafe function or block", description)
599                     .span_label(source_info.span, &description.as_str()[..])
600                     .note(&details.as_str()[..])
601                     .emit();
602             }
603             UnsafetyViolationKind::MinConstFn => {
604                 tcx.sess.struct_span_err(
605                     source_info.span,
606                     &format!("{} is unsafe and unsafe operations \
607                             are not allowed in const fn", description))
608                     .span_label(source_info.span, &description.as_str()[..])
609                     .note(&details.as_str()[..])
610                     .emit();
611             }
612             UnsafetyViolationKind::ExternStatic(lint_node_id) => {
613                 tcx.lint_node_note(SAFE_EXTERN_STATICS,
614                               lint_node_id,
615                               source_info.span,
616                               &format!("{} is unsafe and requires unsafe function or block \
617                                         (error E0133)", &description.as_str()[..]),
618                               &details.as_str()[..]);
619             }
620             UnsafetyViolationKind::BorrowPacked(lint_node_id) => {
621                 if let Some(impl_def_id) = builtin_derive_def_id(tcx, def_id) {
622                     tcx.unsafe_derive_on_repr_packed(impl_def_id);
623                 } else {
624                     tcx.lint_node_note(SAFE_PACKED_BORROWS,
625                                   lint_node_id,
626                                   source_info.span,
627                                   &format!("{} is unsafe and requires unsafe function or block \
628                                             (error E0133)", &description.as_str()[..]),
629                                   &details.as_str()[..]);
630                 }
631             }
632         }
633     }
634
635     let mut unsafe_blocks: Vec<_> = unsafe_blocks.into_iter().collect();
636     unsafe_blocks.sort();
637     let used_unsafe: FxHashSet<_> = unsafe_blocks.iter()
638         .flat_map(|&&(id, used)| if used { Some(id) } else { None })
639         .collect();
640     for &(block_id, is_used) in unsafe_blocks {
641         if !is_used {
642             report_unused_unsafe(tcx, &used_unsafe, block_id);
643         }
644     }
645 }