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