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