1 use rustc_data_structures::fx::FxHashSet;
2 use rustc_data_structures::indexed_vec::IndexVec;
3 use rustc_data_structures::sync::Lrc;
5 use rustc::ty::query::Providers;
6 use rustc::ty::{self, TyCtxt};
7 use rustc::ty::cast::CastTy;
10 use rustc::hir::def_id::DefId;
11 use rustc::lint::builtin::{SAFE_EXTERN_STATICS, SAFE_PACKED_BORROWS, UNUSED_UNSAFE};
13 use rustc::mir::visit::{PlaceContext, Visitor, MutatingUseContext};
15 use syntax::symbol::{InternedString, sym};
21 pub struct UnsafetyChecker<'a, 'tcx> {
25 source_scope_local_data: &'a IndexVec<SourceScope, SourceScopeLocalData>,
26 violations: Vec<UnsafetyViolation>,
27 source_info: SourceInfo,
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)>,
35 impl<'a, 'tcx> UnsafetyChecker<'a, 'tcx> {
40 source_scope_local_data: &'a IndexVec<SourceScope, SourceScopeLocalData>,
42 param_env: ty::ParamEnv<'tcx>,
46 assert!(const_context);
52 source_scope_local_data,
54 source_info: SourceInfo {
56 scope: OUTERMOST_SOURCE_SCOPE
60 used_unsafe: Default::default(),
61 inherited_blocks: vec![],
66 impl<'a, 'tcx> Visitor<'tcx> for UnsafetyChecker<'a, 'tcx> {
67 fn visit_terminator(&mut self,
68 terminator: &Terminator<'tcx>,
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)
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)
99 self.super_terminator(terminator, location);
102 fn visit_statement(&mut self,
103 statement: &Statement<'tcx>,
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)
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)
125 self.super_statement(statement, location);
128 fn visit_rvalue(&mut self,
129 rvalue: &Rvalue<'tcx>,
133 Rvalue::Aggregate(box ref 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,
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);
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,
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).kind {
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,
196 self.super_rvalue(rvalue, location);
199 fn visit_place(&mut self,
201 context: PlaceContext,
202 _location: Location) {
204 PlaceBase::Local(..) => {
207 PlaceBase::Static(box Static { kind: StaticKind::Promoted(_, _), .. }) => {
208 bug!("unsafety checking should happen before promotion")
210 PlaceBase::Static(box Static { kind: StaticKind::Static, def_id, .. }) => {
211 if self.tcx.is_mutable_static(def_id) {
212 self.require_unsafe("use of mutable static",
213 "mutable statics can be mutated by multiple threads: aliasing \
214 violations or data races will cause undefined behavior",
215 UnsafetyViolationKind::General);
216 } else if self.tcx.is_foreign_item(def_id) {
217 let source_info = self.source_info;
219 self.source_scope_local_data[source_info.scope].lint_root;
220 self.register_violations(&[UnsafetyViolation {
222 description: InternedString::intern("use of extern static"),
223 details: InternedString::intern(
224 "extern statics are not controlled by the Rust type system: \
225 invalid data, aliasing violations or data races will cause \
226 undefined behavior"),
227 kind: UnsafetyViolationKind::ExternStatic(lint_root)
233 for (i, elem) in place.projection.iter().enumerate() {
234 let proj_base = &place.projection[..i];
236 if context.is_borrow() {
237 if util::is_disaligned(self.tcx, self.body, self.param_env, place) {
238 let source_info = self.source_info;
240 self.source_scope_local_data[source_info.scope].lint_root;
241 self.register_violations(&[UnsafetyViolation {
243 description: InternedString::intern("borrow of packed field"),
244 details: InternedString::intern(
245 "fields of packed structs might be misaligned: dereferencing a \
246 misaligned pointer or even just creating a misaligned reference \
247 is undefined behavior"),
248 kind: UnsafetyViolationKind::BorrowPacked(lint_root)
252 let is_borrow_of_interior_mut = context.is_borrow() &&
253 !Place::ty_from(&place.base, proj_base, self.body, self.tcx)
255 .is_freeze(self.tcx, self.param_env, self.source_info.span);
259 // * `&x.field` if `field`'s type has interior mutability
260 // because either of these would allow modifying the layout constrained field and
261 // insert values that violate the layout constraints.
262 if context.is_mutating_use() || is_borrow_of_interior_mut {
263 self.check_mut_borrowing_layout_constrained_field(
264 place, context.is_mutating_use(),
267 let old_source_info = self.source_info;
268 if let (PlaceBase::Local(local), []) = (&place.base, proj_base) {
269 if self.body.local_decls[*local].internal {
270 // Internal locals are used in the `move_val_init` desugaring.
271 // We want to check unsafety against the source info of the
272 // desugaring, rather than the source info of the RHS.
273 self.source_info = self.body.local_decls[*local].source_info;
276 let base_ty = Place::ty_from(&place.base, proj_base, self.body, self.tcx).ty;
279 self.require_unsafe("dereference of raw pointer",
280 "raw pointers may be NULL, dangling or unaligned; they can violate \
281 aliasing rules and cause data races: all of these are undefined \
282 behavior", UnsafetyViolationKind::General)
286 if context == PlaceContext::MutatingUse(MutatingUseContext::Store) ||
287 context == PlaceContext::MutatingUse(MutatingUseContext::Drop) ||
288 context == PlaceContext::MutatingUse(
289 MutatingUseContext::AsmOutput
292 let elem_ty = match elem {
293 ProjectionElem::Field(_, ty) => ty,
295 self.source_info.span,
296 "non-field projection {:?} from union?",
299 if !elem_ty.is_copy_modulo_regions(
302 self.source_info.span,
305 "assignment to non-`Copy` union field",
306 "the previous content of the field will be dropped, which \
307 causes undefined behavior if the field was not properly \
308 initialized", UnsafetyViolationKind::GeneralAndConstFn)
310 // write to non-move union, safe
313 self.require_unsafe("access to union field",
314 "the field may not be properly initialized: using \
315 uninitialized data will cause undefined behavior",
316 UnsafetyViolationKind::GeneralAndConstFn)
322 self.source_info = old_source_info;
327 impl<'a, 'tcx> UnsafetyChecker<'a, 'tcx> {
330 description: &'static str,
331 details: &'static str,
332 kind: UnsafetyViolationKind,
334 let source_info = self.source_info;
335 self.register_violations(&[UnsafetyViolation {
337 description: InternedString::intern(description),
338 details: InternedString::intern(details),
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
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
360 violation.kind = UnsafetyViolationKind::General;
363 if !self.violations.contains(&violation) {
364 self.violations.push(violation)
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);
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
390 violation.kind = UnsafetyViolationKind::General;
391 if !self.violations.contains(&violation) {
392 self.violations.push(violation)
401 self.inherited_blocks.extend(unsafe_blocks.iter().map(|&(hir_id, is_used)| {
402 (hir_id, is_used && !within_unsafe)
405 fn check_mut_borrowing_layout_constrained_field(
410 let mut cursor = &*place.projection;
411 while let [proj_base @ .., elem] = cursor {
415 ProjectionElem::Field(..) => {
417 Place::ty_from(&place.base, proj_base, &self.body.local_decls, self.tcx)
420 ty::Adt(def, _) => match self.tcx.layout_scalar_valid_range(def.did) {
421 (Bound::Unbounded, Bound::Unbounded) => {},
423 let (description, details) = if is_mut_use {
425 "mutation of layout constrained field",
426 "mutating layout constrained fields cannot statically be \
427 checked for valid values",
431 "borrow of layout constrained field with interior \
433 "references to fields of layout constrained fields \
434 lose the constraints. Coupled with interior mutability, \
435 the field can be changed to invalid values",
438 let source_info = self.source_info;
439 self.register_violations(&[UnsafetyViolation {
441 description: InternedString::intern(description),
442 details: InternedString::intern(details),
443 kind: UnsafetyViolationKind::GeneralAndConstFn,
456 pub(crate) fn provide(providers: &mut Providers<'_>) {
457 *providers = Providers {
458 unsafety_check_result,
459 unsafe_derive_on_repr_packed,
464 struct UnusedUnsafeVisitor<'a> {
465 used_unsafe: &'a FxHashSet<hir::HirId>,
466 unsafe_blocks: &'a mut Vec<(hir::HirId, bool)>,
469 impl<'a, 'tcx> hir::intravisit::Visitor<'tcx> for UnusedUnsafeVisitor<'a> {
470 fn nested_visit_map<'this>(&'this mut self) ->
471 hir::intravisit::NestedVisitorMap<'this, 'tcx>
473 hir::intravisit::NestedVisitorMap::None
476 fn visit_block(&mut self, block: &'tcx hir::Block) {
477 hir::intravisit::walk_block(self, block);
479 if let hir::UnsafeBlock(hir::UserProvided) = block.rules {
480 self.unsafe_blocks.push((block.hir_id, self.used_unsafe.contains(&block.hir_id)));
485 fn check_unused_unsafe(
488 used_unsafe: &FxHashSet<hir::HirId>,
489 unsafe_blocks: &mut Vec<(hir::HirId, bool)>,
492 tcx.hir().as_local_hir_id(def_id).and_then(|hir_id| {
493 tcx.hir().maybe_body_owned_by(hir_id)
496 let body_id = match body_id {
499 debug!("check_unused_unsafe({:?}) - no body found", def_id);
503 let body = tcx.hir().body(body_id);
504 debug!("check_unused_unsafe({:?}, body={:?}, used_unsafe={:?})",
505 def_id, body, used_unsafe);
507 let mut visitor = UnusedUnsafeVisitor { used_unsafe, unsafe_blocks };
508 hir::intravisit::Visitor::visit_body(&mut visitor, body);
511 fn unsafety_check_result(tcx: TyCtxt<'_>, def_id: DefId) -> UnsafetyCheckResult {
512 debug!("unsafety_violations({:?})", def_id);
514 // N.B., this borrow is valid because all the consumers of
515 // `mir_built` force this.
516 let body = &tcx.mir_built(def_id).borrow();
518 let source_scope_local_data = match body.source_scope_local_data {
519 ClearCrossCrate::Set(ref data) => data,
520 ClearCrossCrate::Clear => {
521 debug!("unsafety_violations: {:?} - remote, skipping", def_id);
522 return UnsafetyCheckResult {
523 violations: Lrc::new([]),
524 unsafe_blocks: Lrc::new([])
529 let param_env = tcx.param_env(def_id);
531 let id = tcx.hir().as_local_hir_id(def_id).unwrap();
532 let (const_context, min_const_fn) = match tcx.hir().body_owner_kind(id) {
533 hir::BodyOwnerKind::Closure => (false, false),
534 hir::BodyOwnerKind::Fn => (tcx.is_const_fn(def_id), tcx.is_min_const_fn(def_id)),
535 hir::BodyOwnerKind::Const |
536 hir::BodyOwnerKind::Static(_) => (true, false),
538 let mut checker = UnsafetyChecker::new(
539 const_context, min_const_fn,
540 body, source_scope_local_data, tcx, param_env);
541 checker.visit_body(body);
543 check_unused_unsafe(tcx, def_id, &checker.used_unsafe, &mut checker.inherited_blocks);
544 UnsafetyCheckResult {
545 violations: checker.violations.into(),
546 unsafe_blocks: checker.inherited_blocks.into()
550 fn unsafe_derive_on_repr_packed(tcx: TyCtxt<'_>, def_id: DefId) {
551 let lint_hir_id = tcx.hir().as_local_hir_id(def_id).unwrap_or_else(||
552 bug!("checking unsafety for non-local def id {:?}", def_id));
554 // FIXME: when we make this a hard error, this should have its
556 let message = if tcx.generics_of(def_id).own_requires_monomorphization() {
557 "`#[derive]` can't be used on a `#[repr(packed)]` struct with \
558 type or const parameters (error E0133)".to_string()
560 "`#[derive]` can't be used on a `#[repr(packed)]` struct that \
561 does not derive Copy (error E0133)".to_string()
563 tcx.lint_hir(SAFE_PACKED_BORROWS,
565 tcx.def_span(def_id),
569 /// Returns the `HirId` for an enclosing scope that is also `unsafe`.
572 used_unsafe: &FxHashSet<hir::HirId>,
574 ) -> Option<(String, hir::HirId)> {
575 let parent_id = tcx.hir().get_parent_node(id);
577 if used_unsafe.contains(&parent_id) {
578 Some(("block".to_string(), parent_id))
579 } else if let Some(Node::Item(&hir::Item {
580 node: hir::ItemKind::Fn(_, header, _, _),
582 })) = tcx.hir().find(parent_id) {
583 match header.unsafety {
584 hir::Unsafety::Unsafe => Some(("fn".to_string(), parent_id)),
585 hir::Unsafety::Normal => None,
588 is_enclosed(tcx, used_unsafe, parent_id)
595 fn report_unused_unsafe(tcx: TyCtxt<'_>, used_unsafe: &FxHashSet<hir::HirId>, id: hir::HirId) {
596 let span = tcx.sess.source_map().def_span(tcx.hir().span(id));
597 let msg = "unnecessary `unsafe` block";
598 let mut db = tcx.struct_span_lint_hir(UNUSED_UNSAFE, id, span, msg);
599 db.span_label(span, msg);
600 if let Some((kind, id)) = is_enclosed(tcx, used_unsafe, id) {
601 db.span_label(tcx.sess.source_map().def_span(tcx.hir().span(id)),
602 format!("because it's nested under this `unsafe` {}", kind));
607 fn builtin_derive_def_id(tcx: TyCtxt<'_>, def_id: DefId) -> Option<DefId> {
608 debug!("builtin_derive_def_id({:?})", def_id);
609 if let Some(impl_def_id) = tcx.impl_of_method(def_id) {
610 if tcx.has_attr(impl_def_id, sym::automatically_derived) {
611 debug!("builtin_derive_def_id({:?}) - is {:?}", def_id, impl_def_id);
614 debug!("builtin_derive_def_id({:?}) - not automatically derived", def_id);
618 debug!("builtin_derive_def_id({:?}) - not a method", def_id);
623 pub fn check_unsafety(tcx: TyCtxt<'_>, def_id: DefId) {
624 debug!("check_unsafety({:?})", def_id);
626 // closures are handled by their parent fn.
627 if tcx.is_closure(def_id) {
631 let UnsafetyCheckResult {
634 } = tcx.unsafety_check_result(def_id);
636 for &UnsafetyViolation {
637 source_info, description, details, kind
638 } in violations.iter() {
641 UnsafetyViolationKind::GeneralAndConstFn |
642 UnsafetyViolationKind::General => {
644 tcx.sess, source_info.span, E0133,
645 "{} is unsafe and requires unsafe function or block", description)
646 .span_label(source_info.span, &description.as_str()[..])
647 .note(&details.as_str()[..])
650 UnsafetyViolationKind::ExternStatic(lint_hir_id) => {
651 tcx.lint_node_note(SAFE_EXTERN_STATICS,
654 &format!("{} is unsafe and requires unsafe function or block \
655 (error E0133)", &description.as_str()[..]),
656 &details.as_str()[..]);
658 UnsafetyViolationKind::BorrowPacked(lint_hir_id) => {
659 if let Some(impl_def_id) = builtin_derive_def_id(tcx, def_id) {
660 tcx.unsafe_derive_on_repr_packed(impl_def_id);
662 tcx.lint_node_note(SAFE_PACKED_BORROWS,
665 &format!("{} is unsafe and requires unsafe function or block \
666 (error E0133)", &description.as_str()[..]),
667 &details.as_str()[..]);
673 let mut unsafe_blocks: Vec<_> = unsafe_blocks.into_iter().collect();
674 unsafe_blocks.sort_by_cached_key(|(hir_id, _)| tcx.hir().hir_to_node_id(*hir_id));
675 let used_unsafe: FxHashSet<_> = unsafe_blocks.iter()
676 .flat_map(|&&(id, used)| if used { Some(id) } else { None })
678 for &(block_id, is_used) in unsafe_blocks {
680 report_unused_unsafe(tcx, &used_unsafe, block_id);