1 use rustc::hir::map::Map;
2 use rustc::lint::builtin::{SAFE_PACKED_BORROWS, UNUSED_UNSAFE};
3 use rustc::mir::visit::{MutatingUseContext, PlaceContext, Visitor};
5 use rustc::ty::cast::CastTy;
6 use rustc::ty::query::Providers;
7 use rustc::ty::{self, TyCtxt};
8 use rustc_data_structures::fx::FxHashSet;
9 use rustc_errors::struct_span_err;
11 use rustc_hir::def_id::DefId;
12 use rustc_hir::intravisit;
14 use rustc_span::symbol::{sym, Symbol};
18 use crate::const_eval::{is_const_fn, is_min_const_fn};
21 pub struct UnsafetyChecker<'a, 'tcx> {
25 violations: Vec<UnsafetyViolation>,
26 source_info: SourceInfo,
28 param_env: ty::ParamEnv<'tcx>,
29 /// Mark an `unsafe` block as used, so we don't lint it.
30 used_unsafe: FxHashSet<hir::HirId>,
31 inherited_blocks: Vec<(hir::HirId, bool)>,
34 impl<'a, 'tcx> UnsafetyChecker<'a, 'tcx> {
40 param_env: ty::ParamEnv<'tcx>,
44 assert!(const_context);
51 source_info: SourceInfo { span: body.span, scope: OUTERMOST_SOURCE_SCOPE },
54 used_unsafe: Default::default(),
55 inherited_blocks: vec![],
60 impl<'a, 'tcx> Visitor<'tcx> for UnsafetyChecker<'a, 'tcx> {
61 fn visit_terminator(&mut self, terminator: &Terminator<'tcx>, location: Location) {
62 self.source_info = terminator.source_info;
63 match terminator.kind {
64 TerminatorKind::Goto { .. }
65 | TerminatorKind::SwitchInt { .. }
66 | TerminatorKind::Drop { .. }
67 | TerminatorKind::Yield { .. }
68 | TerminatorKind::Assert { .. }
69 | TerminatorKind::DropAndReplace { .. }
70 | TerminatorKind::GeneratorDrop
71 | TerminatorKind::Resume
72 | TerminatorKind::Abort
73 | TerminatorKind::Return
74 | TerminatorKind::Unreachable
75 | TerminatorKind::FalseEdges { .. }
76 | TerminatorKind::FalseUnwind { .. } => {
77 // safe (at least as emitted during MIR construction)
80 TerminatorKind::Call { ref func, .. } => {
81 let func_ty = func.ty(self.body, self.tcx);
82 let sig = func_ty.fn_sig(self.tcx);
83 if let hir::Unsafety::Unsafe = sig.unsafety() {
85 "call to unsafe function",
86 "consult the function's documentation for information on how to avoid \
88 UnsafetyViolationKind::GeneralAndConstFn,
93 self.super_terminator(terminator, location);
96 fn visit_statement(&mut self, statement: &Statement<'tcx>, location: Location) {
97 self.source_info = statement.source_info;
98 match statement.kind {
99 StatementKind::Assign(..)
100 | StatementKind::FakeRead(..)
101 | StatementKind::SetDiscriminant { .. }
102 | StatementKind::StorageLive(..)
103 | StatementKind::StorageDead(..)
104 | StatementKind::Retag { .. }
105 | StatementKind::AscribeUserType(..)
106 | StatementKind::Nop => {
107 // safe (at least as emitted during MIR construction)
110 StatementKind::InlineAsm { .. } => self.require_unsafe(
111 "use of inline assembly",
112 "inline assembly is entirely unchecked and can cause undefined behavior",
113 UnsafetyViolationKind::General,
116 self.super_statement(statement, location);
119 fn visit_rvalue(&mut self, rvalue: &Rvalue<'tcx>, location: Location) {
121 Rvalue::Aggregate(box ref aggregate, _) => match aggregate {
122 &AggregateKind::Array(..) | &AggregateKind::Tuple => {}
123 &AggregateKind::Adt(ref def, ..) => {
124 match self.tcx.layout_scalar_valid_range(def.did) {
125 (Bound::Unbounded, Bound::Unbounded) => {}
126 _ => self.require_unsafe(
127 "initializing type with `rustc_layout_scalar_valid_range` attr",
128 "initializing a layout restricted type's field with a value \
129 outside the valid range is undefined behavior",
130 UnsafetyViolationKind::GeneralAndConstFn,
134 &AggregateKind::Closure(def_id, _) | &AggregateKind::Generator(def_id, _, _) => {
135 let UnsafetyCheckResult { violations, unsafe_blocks } =
136 self.tcx.unsafety_check_result(def_id);
137 self.register_violations(&violations, &unsafe_blocks);
140 // casting pointers to ints is unsafe in const fn because the const evaluator cannot
141 // possibly know what the result of various operations like `address / 2` would be
142 // pointers during const evaluation have no integral address, only an abstract one
143 Rvalue::Cast(CastKind::Misc, ref operand, cast_ty)
144 if self.const_context && self.tcx.features().const_raw_ptr_to_usize_cast =>
146 let operand_ty = operand.ty(self.body, self.tcx);
147 let cast_in = CastTy::from_ty(operand_ty).expect("bad input type for cast");
148 let cast_out = CastTy::from_ty(cast_ty).expect("bad output type for cast");
149 match (cast_in, cast_out) {
150 (CastTy::Ptr(_), CastTy::Int(_)) | (CastTy::FnPtr, CastTy::Int(_)) => {
151 self.register_violations(
152 &[UnsafetyViolation {
153 source_info: self.source_info,
154 description: Symbol::intern("cast of pointer to int"),
155 details: Symbol::intern(
156 "casting pointers to integers in constants",
158 kind: UnsafetyViolationKind::General,
166 // raw pointer and fn pointer operations are unsafe as it is not clear whether one
167 // pointer would be "less" or "equal" to another, because we cannot know where llvm
168 // or the linker will place various statics in memory. Without this information the
169 // result of a comparison of addresses would differ between runtime and compile-time.
170 Rvalue::BinaryOp(_, ref lhs, _)
171 if self.const_context && self.tcx.features().const_compare_raw_pointers =>
173 if let ty::RawPtr(_) | ty::FnPtr(..) = lhs.ty(self.body, self.tcx).kind {
174 self.register_violations(
175 &[UnsafetyViolation {
176 source_info: self.source_info,
177 description: Symbol::intern("pointer operation"),
178 details: Symbol::intern("operations on pointers in constants"),
179 kind: UnsafetyViolationKind::General,
187 self.super_rvalue(rvalue, location);
190 fn visit_place(&mut self, place: &Place<'tcx>, context: PlaceContext, _location: Location) {
191 for (i, elem) in place.projection.iter().enumerate() {
192 let proj_base = &place.projection[..i];
194 if context.is_borrow() {
195 if util::is_disaligned(self.tcx, self.body, self.param_env, place) {
196 let source_info = self.source_info;
197 let lint_root = self.body.source_scopes[source_info.scope]
200 .assert_crate_local()
202 self.register_violations(
203 &[UnsafetyViolation {
205 description: Symbol::intern("borrow of packed field"),
206 details: Symbol::intern(
207 "fields of packed structs might be misaligned: dereferencing a \
208 misaligned pointer or even just creating a misaligned reference \
209 is undefined behavior",
211 kind: UnsafetyViolationKind::BorrowPacked(lint_root),
217 let is_borrow_of_interior_mut = context.is_borrow()
218 && !Place::ty_from(&place.local, proj_base, self.body, self.tcx).ty.is_freeze(
221 self.source_info.span,
226 // * `&x.field` if `field`'s type has interior mutability
227 // because either of these would allow modifying the layout constrained field and
228 // insert values that violate the layout constraints.
229 if context.is_mutating_use() || is_borrow_of_interior_mut {
230 self.check_mut_borrowing_layout_constrained_field(place, context.is_mutating_use());
232 let old_source_info = self.source_info;
233 if let (local, []) = (&place.local, proj_base) {
234 let decl = &self.body.local_decls[*local];
236 // Internal locals are used in the `move_val_init` desugaring.
237 // We want to check unsafety against the source info of the
238 // desugaring, rather than the source info of the RHS.
239 self.source_info = self.body.local_decls[*local].source_info;
240 } else if let LocalInfo::StaticRef { def_id, .. } = decl.local_info {
241 if self.tcx.is_mutable_static(def_id) {
243 "use of mutable static",
244 "mutable statics can be mutated by multiple threads: aliasing \
245 violations or data races will cause undefined behavior",
246 UnsafetyViolationKind::General,
249 } else if self.tcx.is_foreign_item(def_id) {
251 "use of extern static",
252 "extern statics are not controlled by the Rust type system: \
253 invalid data, aliasing violations or data races will cause \
255 UnsafetyViolationKind::General,
261 let base_ty = Place::ty_from(&place.local, proj_base, self.body, self.tcx).ty;
263 ty::RawPtr(..) => self.require_unsafe(
264 "dereference of raw pointer",
265 "raw pointers may be NULL, dangling or unaligned; they can violate \
266 aliasing rules and cause data races: all of these are undefined \
268 UnsafetyViolationKind::General,
272 if context == PlaceContext::MutatingUse(MutatingUseContext::Store)
273 || context == PlaceContext::MutatingUse(MutatingUseContext::Drop)
274 || context == PlaceContext::MutatingUse(MutatingUseContext::AsmOutput)
276 let elem_ty = match elem {
277 ProjectionElem::Field(_, ty) => ty,
279 self.source_info.span,
280 "non-field projection {:?} from union?",
284 if !elem_ty.is_copy_modulo_regions(
287 self.source_info.span,
290 "assignment to non-`Copy` union field",
291 "the previous content of the field will be dropped, which \
292 causes undefined behavior if the field was not properly \
294 UnsafetyViolationKind::GeneralAndConstFn,
297 // write to non-move union, safe
301 "access to union field",
302 "the field may not be properly initialized: using \
303 uninitialized data will cause undefined behavior",
304 UnsafetyViolationKind::GeneralAndConstFn,
311 self.source_info = old_source_info;
316 impl<'a, 'tcx> UnsafetyChecker<'a, 'tcx> {
319 description: &'static str,
320 details: &'static str,
321 kind: UnsafetyViolationKind,
323 let source_info = self.source_info;
324 self.register_violations(
325 &[UnsafetyViolation {
327 description: Symbol::intern(description),
328 details: Symbol::intern(details),
335 fn register_violations(
337 violations: &[UnsafetyViolation],
338 unsafe_blocks: &[(hir::HirId, bool)],
340 let safety = self.body.source_scopes[self.source_info.scope]
343 .assert_crate_local()
345 let within_unsafe = match safety {
346 // `unsafe` blocks are required in safe code
348 for violation in violations {
349 let mut violation = violation.clone();
350 match violation.kind {
351 UnsafetyViolationKind::GeneralAndConstFn
352 | UnsafetyViolationKind::General => {}
353 UnsafetyViolationKind::BorrowPacked(_) => {
354 if self.min_const_fn {
355 // const fns don't need to be backwards compatible and can
356 // emit these violations as a hard error instead of a backwards
358 violation.kind = UnsafetyViolationKind::General;
362 if !self.violations.contains(&violation) {
363 self.violations.push(violation)
368 // `unsafe` function bodies allow unsafe without additional unsafe blocks
369 Safety::BuiltinUnsafe | Safety::FnUnsafe => true,
370 Safety::ExplicitUnsafe(hir_id) => {
371 // mark unsafe block as used if there are any unsafe operations inside
372 if !violations.is_empty() {
373 self.used_unsafe.insert(hir_id);
375 // only some unsafety is allowed in const fn
376 if self.min_const_fn {
377 for violation in violations {
378 match violation.kind {
379 // these unsafe things are stable in const fn
380 UnsafetyViolationKind::GeneralAndConstFn => {}
381 // these things are forbidden in const fns
382 UnsafetyViolationKind::General
383 | UnsafetyViolationKind::BorrowPacked(_) => {
384 let mut violation = violation.clone();
385 // const fns don't need to be backwards compatible and can
386 // emit these violations as a hard error instead of a backwards
388 violation.kind = UnsafetyViolationKind::General;
389 if !self.violations.contains(&violation) {
390 self.violations.push(violation)
399 self.inherited_blocks.extend(
400 unsafe_blocks.iter().map(|&(hir_id, is_used)| (hir_id, is_used && !within_unsafe)),
403 fn check_mut_borrowing_layout_constrained_field(
408 let mut cursor = place.projection.as_ref();
409 while let &[ref proj_base @ .., elem] = cursor {
413 ProjectionElem::Field(..) => {
415 Place::ty_from(&place.local, proj_base, &self.body.local_decls, self.tcx)
418 ty::Adt(def, _) => match self.tcx.layout_scalar_valid_range(def.did) {
419 (Bound::Unbounded, Bound::Unbounded) => {}
421 let (description, details) = if is_mut_use {
423 "mutation of layout constrained field",
424 "mutating layout constrained fields cannot statically be \
425 checked for valid values",
429 "borrow of layout constrained field with interior \
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",
436 let source_info = self.source_info;
437 self.register_violations(
438 &[UnsafetyViolation {
440 description: Symbol::intern(description),
441 details: Symbol::intern(details),
442 kind: UnsafetyViolationKind::GeneralAndConstFn,
457 pub(crate) fn provide(providers: &mut Providers<'_>) {
458 *providers = Providers { unsafety_check_result, unsafe_derive_on_repr_packed, ..*providers };
461 struct UnusedUnsafeVisitor<'a> {
462 used_unsafe: &'a FxHashSet<hir::HirId>,
463 unsafe_blocks: &'a mut Vec<(hir::HirId, bool)>,
466 impl<'a, 'tcx> intravisit::Visitor<'tcx> for UnusedUnsafeVisitor<'a> {
467 type Map = Map<'tcx>;
469 fn nested_visit_map<'this>(&'this mut self) -> intravisit::NestedVisitorMap<'this, Self::Map> {
470 intravisit::NestedVisitorMap::None
473 fn visit_block(&mut self, block: &'tcx hir::Block<'tcx>) {
474 intravisit::walk_block(self, block);
476 if let hir::BlockCheckMode::UnsafeBlock(hir::UnsafeSource::UserProvided) = block.rules {
477 self.unsafe_blocks.push((block.hir_id, self.used_unsafe.contains(&block.hir_id)));
482 fn check_unused_unsafe(
485 used_unsafe: &FxHashSet<hir::HirId>,
486 unsafe_blocks: &mut Vec<(hir::HirId, bool)>,
489 tcx.hir().as_local_hir_id(def_id).and_then(|hir_id| tcx.hir().maybe_body_owned_by(hir_id));
491 let body_id = match body_id {
494 debug!("check_unused_unsafe({:?}) - no body found", def_id);
498 let body = tcx.hir().body(body_id);
499 debug!("check_unused_unsafe({:?}, body={:?}, used_unsafe={:?})", def_id, body, used_unsafe);
501 let mut visitor = UnusedUnsafeVisitor { used_unsafe, unsafe_blocks };
502 intravisit::Visitor::visit_body(&mut visitor, body);
505 fn unsafety_check_result(tcx: TyCtxt<'_>, def_id: DefId) -> UnsafetyCheckResult {
506 debug!("unsafety_violations({:?})", def_id);
508 // N.B., this borrow is valid because all the consumers of
509 // `mir_built` force this.
510 let body = &tcx.mir_built(def_id).borrow();
512 let param_env = tcx.param_env(def_id);
514 let id = tcx.hir().as_local_hir_id(def_id).unwrap();
515 let (const_context, min_const_fn) = match tcx.hir().body_owner_kind(id) {
516 hir::BodyOwnerKind::Closure => (false, false),
517 hir::BodyOwnerKind::Fn => (is_const_fn(tcx, def_id), is_min_const_fn(tcx, def_id)),
518 hir::BodyOwnerKind::Const | hir::BodyOwnerKind::Static(_) => (true, false),
520 let mut checker = UnsafetyChecker::new(const_context, min_const_fn, body, tcx, param_env);
521 // mir_built ensures that body has a computed cache, so we don't (and can't) attempt to
522 // recompute it here.
523 let body = body.unwrap_read_only();
524 checker.visit_body(body);
526 check_unused_unsafe(tcx, def_id, &checker.used_unsafe, &mut checker.inherited_blocks);
527 UnsafetyCheckResult {
528 violations: checker.violations.into(),
529 unsafe_blocks: checker.inherited_blocks.into(),
533 fn unsafe_derive_on_repr_packed(tcx: TyCtxt<'_>, def_id: DefId) {
534 let lint_hir_id = tcx
536 .as_local_hir_id(def_id)
537 .unwrap_or_else(|| bug!("checking unsafety for non-local def id {:?}", def_id));
539 // FIXME: when we make this a hard error, this should have its
541 let message = if tcx.generics_of(def_id).own_requires_monomorphization() {
542 "`#[derive]` can't be used on a `#[repr(packed)]` struct with \
543 type or const parameters (error E0133)"
546 "`#[derive]` can't be used on a `#[repr(packed)]` struct that \
547 does not derive Copy (error E0133)"
550 tcx.lint_hir(SAFE_PACKED_BORROWS, lint_hir_id, tcx.def_span(def_id), &message);
553 /// Returns the `HirId` for an enclosing scope that is also `unsafe`.
556 used_unsafe: &FxHashSet<hir::HirId>,
558 ) -> Option<(String, hir::HirId)> {
559 let parent_id = tcx.hir().get_parent_node(id);
561 if used_unsafe.contains(&parent_id) {
562 Some(("block".to_string(), parent_id))
563 } else if let Some(Node::Item(&hir::Item {
564 kind: hir::ItemKind::Fn(ref sig, _, _), ..
565 })) = tcx.hir().find(parent_id)
567 match sig.header.unsafety {
568 hir::Unsafety::Unsafe => Some(("fn".to_string(), parent_id)),
569 hir::Unsafety::Normal => None,
572 is_enclosed(tcx, used_unsafe, parent_id)
579 fn report_unused_unsafe(tcx: TyCtxt<'_>, used_unsafe: &FxHashSet<hir::HirId>, id: hir::HirId) {
580 let span = tcx.sess.source_map().def_span(tcx.hir().span(id));
581 let msg = "unnecessary `unsafe` block";
582 let mut db = tcx.struct_span_lint_hir(UNUSED_UNSAFE, id, span, msg);
583 db.span_label(span, msg);
584 if let Some((kind, id)) = is_enclosed(tcx, used_unsafe, id) {
586 tcx.sess.source_map().def_span(tcx.hir().span(id)),
587 format!("because it's nested under this `unsafe` {}", kind),
593 fn builtin_derive_def_id(tcx: TyCtxt<'_>, def_id: DefId) -> Option<DefId> {
594 debug!("builtin_derive_def_id({:?})", def_id);
595 if let Some(impl_def_id) = tcx.impl_of_method(def_id) {
596 if tcx.has_attr(impl_def_id, sym::automatically_derived) {
597 debug!("builtin_derive_def_id({:?}) - is {:?}", def_id, impl_def_id);
600 debug!("builtin_derive_def_id({:?}) - not automatically derived", def_id);
604 debug!("builtin_derive_def_id({:?}) - not a method", def_id);
609 pub fn check_unsafety(tcx: TyCtxt<'_>, def_id: DefId) {
610 debug!("check_unsafety({:?})", def_id);
612 // closures are handled by their parent fn.
613 if tcx.is_closure(def_id) {
617 let UnsafetyCheckResult { violations, unsafe_blocks } = tcx.unsafety_check_result(def_id);
619 for &UnsafetyViolation { source_info, description, details, kind } in violations.iter() {
622 UnsafetyViolationKind::GeneralAndConstFn | UnsafetyViolationKind::General => {
627 "{} is unsafe and requires unsafe function or block",
630 .span_label(source_info.span, &*description.as_str())
631 .note(&details.as_str())
634 UnsafetyViolationKind::BorrowPacked(lint_hir_id) => {
635 if let Some(impl_def_id) = builtin_derive_def_id(tcx, def_id) {
636 tcx.unsafe_derive_on_repr_packed(impl_def_id);
638 tcx.struct_span_lint_hir(
643 "{} is unsafe and requires unsafe function or block (error E0133)",
647 .note(&details.as_str())
654 let mut unsafe_blocks: Vec<_> = unsafe_blocks.into_iter().collect();
655 unsafe_blocks.sort_by_cached_key(|(hir_id, _)| tcx.hir().hir_to_node_id(*hir_id));
656 let used_unsafe: FxHashSet<_> =
657 unsafe_blocks.iter().flat_map(|&&(id, used)| used.then_some(id)).collect();
658 for &(block_id, is_used) in unsafe_blocks {
660 report_unused_unsafe(tcx, &used_unsafe, block_id);