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