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