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 use rustc_error_codes::*;
23 pub struct UnsafetyChecker<'a, 'tcx> {
27 violations: Vec<UnsafetyViolation>,
28 source_info: SourceInfo,
30 param_env: ty::ParamEnv<'tcx>,
31 /// Mark an `unsafe` block as used, so we don't lint it.
32 used_unsafe: FxHashSet<hir::HirId>,
33 inherited_blocks: Vec<(hir::HirId, bool)>,
36 impl<'a, 'tcx> UnsafetyChecker<'a, 'tcx> {
42 param_env: ty::ParamEnv<'tcx>,
46 assert!(const_context);
53 source_info: SourceInfo { span: body.span, scope: OUTERMOST_SOURCE_SCOPE },
56 used_unsafe: Default::default(),
57 inherited_blocks: vec![],
62 impl<'a, 'tcx> Visitor<'tcx> for UnsafetyChecker<'a, 'tcx> {
63 fn visit_terminator(&mut self, terminator: &Terminator<'tcx>, location: Location) {
64 self.source_info = terminator.source_info;
65 match terminator.kind {
66 TerminatorKind::Goto { .. }
67 | TerminatorKind::SwitchInt { .. }
68 | TerminatorKind::Drop { .. }
69 | TerminatorKind::Yield { .. }
70 | TerminatorKind::Assert { .. }
71 | TerminatorKind::DropAndReplace { .. }
72 | TerminatorKind::GeneratorDrop
73 | TerminatorKind::Resume
74 | TerminatorKind::Abort
75 | TerminatorKind::Return
76 | TerminatorKind::Unreachable
77 | TerminatorKind::FalseEdges { .. }
78 | TerminatorKind::FalseUnwind { .. } => {
79 // safe (at least as emitted during MIR construction)
82 TerminatorKind::Call { ref func, .. } => {
83 let func_ty = func.ty(self.body, self.tcx);
84 let sig = func_ty.fn_sig(self.tcx);
85 if let hir::Unsafety::Unsafe = sig.unsafety() {
87 "call to unsafe function",
88 "consult the function's documentation for information on how to avoid \
90 UnsafetyViolationKind::GeneralAndConstFn,
95 self.super_terminator(terminator, location);
98 fn visit_statement(&mut self, statement: &Statement<'tcx>, location: Location) {
99 self.source_info = statement.source_info;
100 match statement.kind {
101 StatementKind::Assign(..)
102 | StatementKind::FakeRead(..)
103 | StatementKind::SetDiscriminant { .. }
104 | StatementKind::StorageLive(..)
105 | StatementKind::StorageDead(..)
106 | StatementKind::Retag { .. }
107 | StatementKind::AscribeUserType(..)
108 | StatementKind::Nop => {
109 // safe (at least as emitted during MIR construction)
112 StatementKind::InlineAsm { .. } => self.require_unsafe(
113 "use of inline assembly",
114 "inline assembly is entirely unchecked and can cause undefined behavior",
115 UnsafetyViolationKind::General,
118 self.super_statement(statement, location);
121 fn visit_rvalue(&mut self, rvalue: &Rvalue<'tcx>, location: Location) {
123 Rvalue::Aggregate(box ref aggregate, _) => match aggregate {
124 &AggregateKind::Array(..) | &AggregateKind::Tuple => {}
125 &AggregateKind::Adt(ref def, ..) => {
126 match self.tcx.layout_scalar_valid_range(def.did) {
127 (Bound::Unbounded, Bound::Unbounded) => {}
128 _ => self.require_unsafe(
129 "initializing type with `rustc_layout_scalar_valid_range` attr",
130 "initializing a layout restricted type's field with a value \
131 outside the valid range is undefined behavior",
132 UnsafetyViolationKind::GeneralAndConstFn,
136 &AggregateKind::Closure(def_id, _) | &AggregateKind::Generator(def_id, _, _) => {
137 let UnsafetyCheckResult { violations, unsafe_blocks } =
138 self.tcx.unsafety_check_result(def_id);
139 self.register_violations(&violations, &unsafe_blocks);
142 // casting pointers to ints is unsafe in const fn because the const evaluator cannot
143 // possibly know what the result of various operations like `address / 2` would be
144 // pointers during const evaluation have no integral address, only an abstract one
145 Rvalue::Cast(CastKind::Misc, ref operand, cast_ty)
146 if self.const_context && self.tcx.features().const_raw_ptr_to_usize_cast =>
148 let operand_ty = operand.ty(self.body, self.tcx);
149 let cast_in = CastTy::from_ty(operand_ty).expect("bad input type for cast");
150 let cast_out = CastTy::from_ty(cast_ty).expect("bad output type for cast");
151 match (cast_in, cast_out) {
152 (CastTy::Ptr(_), CastTy::Int(_)) | (CastTy::FnPtr, CastTy::Int(_)) => {
153 self.register_violations(
154 &[UnsafetyViolation {
155 source_info: self.source_info,
156 description: Symbol::intern("cast of pointer to int"),
157 details: Symbol::intern(
158 "casting pointers to integers in constants",
160 kind: UnsafetyViolationKind::General,
168 // raw pointer and fn pointer operations are unsafe as it is not clear whether one
169 // pointer would be "less" or "equal" to another, because we cannot know where llvm
170 // or the linker will place various statics in memory. Without this information the
171 // result of a comparison of addresses would differ between runtime and compile-time.
172 Rvalue::BinaryOp(_, ref lhs, _)
173 if self.const_context && self.tcx.features().const_compare_raw_pointers =>
175 if let ty::RawPtr(_) | ty::FnPtr(..) = lhs.ty(self.body, self.tcx).kind {
176 self.register_violations(
177 &[UnsafetyViolation {
178 source_info: self.source_info,
179 description: Symbol::intern("pointer operation"),
180 details: Symbol::intern("operations on pointers in constants"),
181 kind: UnsafetyViolationKind::General,
189 self.super_rvalue(rvalue, location);
192 fn visit_place(&mut self, place: &Place<'tcx>, context: PlaceContext, _location: Location) {
194 PlaceBase::Local(..) => {
197 PlaceBase::Static(box Static { kind: StaticKind::Static, .. }) => {
198 bug!("StaticKind::Static should not exist");
202 for (i, elem) in place.projection.iter().enumerate() {
203 let proj_base = &place.projection[..i];
205 if context.is_borrow() {
206 if util::is_disaligned(self.tcx, self.body, self.param_env, place) {
207 let source_info = self.source_info;
208 let lint_root = self.body.source_scopes[source_info.scope]
211 .assert_crate_local()
213 self.register_violations(
214 &[UnsafetyViolation {
216 description: Symbol::intern("borrow of packed field"),
217 details: Symbol::intern(
218 "fields of packed structs might be misaligned: dereferencing a \
219 misaligned pointer or even just creating a misaligned reference \
220 is undefined behavior",
222 kind: UnsafetyViolationKind::BorrowPacked(lint_root),
228 let is_borrow_of_interior_mut = context.is_borrow()
229 && !Place::ty_from(&place.base, proj_base, self.body, self.tcx).ty.is_freeze(
232 self.source_info.span,
237 // * `&x.field` if `field`'s type has interior mutability
238 // because either of these would allow modifying the layout constrained field and
239 // insert values that violate the layout constraints.
240 if context.is_mutating_use() || is_borrow_of_interior_mut {
241 self.check_mut_borrowing_layout_constrained_field(place, context.is_mutating_use());
243 let old_source_info = self.source_info;
244 if let (PlaceBase::Local(local), []) = (&place.base, proj_base) {
245 let decl = &self.body.local_decls[*local];
247 // Internal locals are used in the `move_val_init` desugaring.
248 // We want to check unsafety against the source info of the
249 // desugaring, rather than the source info of the RHS.
250 self.source_info = self.body.local_decls[*local].source_info;
251 } else if let LocalInfo::StaticRef { def_id, .. } = decl.local_info {
252 if self.tcx.is_mutable_static(def_id) {
254 "use of mutable static",
255 "mutable statics can be mutated by multiple threads: aliasing \
256 violations or data races will cause undefined behavior",
257 UnsafetyViolationKind::General,
260 } else if self.tcx.is_foreign_item(def_id) {
262 "use of extern static",
263 "extern statics are not controlled by the Rust type system: \
264 invalid data, aliasing violations or data races will cause \
266 UnsafetyViolationKind::General,
272 let base_ty = Place::ty_from(&place.base, proj_base, self.body, self.tcx).ty;
274 ty::RawPtr(..) => self.require_unsafe(
275 "dereference of raw pointer",
276 "raw pointers may be NULL, dangling or unaligned; they can violate \
277 aliasing rules and cause data races: all of these are undefined \
279 UnsafetyViolationKind::General,
283 if context == PlaceContext::MutatingUse(MutatingUseContext::Store)
284 || context == PlaceContext::MutatingUse(MutatingUseContext::Drop)
285 || context == PlaceContext::MutatingUse(MutatingUseContext::AsmOutput)
287 let elem_ty = match elem {
288 ProjectionElem::Field(_, ty) => ty,
290 self.source_info.span,
291 "non-field projection {:?} from union?",
295 if !elem_ty.is_copy_modulo_regions(
298 self.source_info.span,
301 "assignment to non-`Copy` union field",
302 "the previous content of the field will be dropped, which \
303 causes undefined behavior if the field was not properly \
305 UnsafetyViolationKind::GeneralAndConstFn,
308 // write to non-move union, safe
312 "access to union field",
313 "the field may not be properly initialized: using \
314 uninitialized data will cause undefined behavior",
315 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(
336 &[UnsafetyViolation {
338 description: Symbol::intern(description),
339 details: Symbol::intern(details),
346 fn register_violations(
348 violations: &[UnsafetyViolation],
349 unsafe_blocks: &[(hir::HirId, bool)],
351 let safety = self.body.source_scopes[self.source_info.scope]
354 .assert_crate_local()
356 let within_unsafe = match safety {
357 // `unsafe` blocks are required in safe code
359 for violation in violations {
360 let mut violation = violation.clone();
361 match violation.kind {
362 UnsafetyViolationKind::GeneralAndConstFn
363 | UnsafetyViolationKind::General => {}
364 UnsafetyViolationKind::BorrowPacked(_) => {
365 if self.min_const_fn {
366 // const fns don't need to be backwards compatible and can
367 // emit these violations as a hard error instead of a backwards
369 violation.kind = UnsafetyViolationKind::General;
373 if !self.violations.contains(&violation) {
374 self.violations.push(violation)
379 // `unsafe` function bodies allow unsafe without additional unsafe blocks
380 Safety::BuiltinUnsafe | Safety::FnUnsafe => true,
381 Safety::ExplicitUnsafe(hir_id) => {
382 // mark unsafe block as used if there are any unsafe operations inside
383 if !violations.is_empty() {
384 self.used_unsafe.insert(hir_id);
386 // only some unsafety is allowed in const fn
387 if self.min_const_fn {
388 for violation in violations {
389 match violation.kind {
390 // these unsafe things are stable in const fn
391 UnsafetyViolationKind::GeneralAndConstFn => {}
392 // these things are forbidden in const fns
393 UnsafetyViolationKind::General
394 | UnsafetyViolationKind::BorrowPacked(_) => {
395 let mut violation = violation.clone();
396 // const fns don't need to be backwards compatible and can
397 // emit these violations as a hard error instead of a backwards
399 violation.kind = UnsafetyViolationKind::General;
400 if !self.violations.contains(&violation) {
401 self.violations.push(violation)
410 self.inherited_blocks.extend(
411 unsafe_blocks.iter().map(|&(hir_id, is_used)| (hir_id, is_used && !within_unsafe)),
414 fn check_mut_borrowing_layout_constrained_field(
419 let mut cursor = place.projection.as_ref();
420 while let &[ref proj_base @ .., elem] = cursor {
424 ProjectionElem::Field(..) => {
426 Place::ty_from(&place.base, proj_base, &self.body.local_decls, self.tcx).ty;
428 ty::Adt(def, _) => match self.tcx.layout_scalar_valid_range(def.did) {
429 (Bound::Unbounded, Bound::Unbounded) => {}
431 let (description, details) = if is_mut_use {
433 "mutation of layout constrained field",
434 "mutating layout constrained fields cannot statically be \
435 checked for valid values",
439 "borrow of layout constrained field with interior \
441 "references to fields of layout constrained fields \
442 lose the constraints. Coupled with interior mutability, \
443 the field can be changed to invalid values",
446 let source_info = self.source_info;
447 self.register_violations(
448 &[UnsafetyViolation {
450 description: Symbol::intern(description),
451 details: Symbol::intern(details),
452 kind: UnsafetyViolationKind::GeneralAndConstFn,
467 pub(crate) fn provide(providers: &mut Providers<'_>) {
468 *providers = Providers { unsafety_check_result, unsafe_derive_on_repr_packed, ..*providers };
471 struct UnusedUnsafeVisitor<'a> {
472 used_unsafe: &'a FxHashSet<hir::HirId>,
473 unsafe_blocks: &'a mut Vec<(hir::HirId, bool)>,
476 impl<'a, 'tcx> intravisit::Visitor<'tcx> for UnusedUnsafeVisitor<'a> {
477 type Map = Map<'tcx>;
479 fn nested_visit_map<'this>(&'this mut self) -> intravisit::NestedVisitorMap<'this, Self::Map> {
480 intravisit::NestedVisitorMap::None
483 fn visit_block(&mut self, block: &'tcx hir::Block<'tcx>) {
484 intravisit::walk_block(self, block);
486 if let hir::BlockCheckMode::UnsafeBlock(hir::UnsafeSource::UserProvided) = block.rules {
487 self.unsafe_blocks.push((block.hir_id, self.used_unsafe.contains(&block.hir_id)));
492 fn check_unused_unsafe(
495 used_unsafe: &FxHashSet<hir::HirId>,
496 unsafe_blocks: &mut Vec<(hir::HirId, bool)>,
499 tcx.hir().as_local_hir_id(def_id).and_then(|hir_id| tcx.hir().maybe_body_owned_by(hir_id));
501 let body_id = match body_id {
504 debug!("check_unused_unsafe({:?}) - no body found", def_id);
508 let body = tcx.hir().body(body_id);
509 debug!("check_unused_unsafe({:?}, body={:?}, used_unsafe={:?})", def_id, body, used_unsafe);
511 let mut visitor = UnusedUnsafeVisitor { used_unsafe, unsafe_blocks };
512 intravisit::Visitor::visit_body(&mut visitor, body);
515 fn unsafety_check_result(tcx: TyCtxt<'_>, def_id: DefId) -> UnsafetyCheckResult {
516 debug!("unsafety_violations({:?})", def_id);
518 // N.B., this borrow is valid because all the consumers of
519 // `mir_built` force this.
520 let body = &tcx.mir_built(def_id).borrow();
522 let param_env = tcx.param_env(def_id);
524 let id = tcx.hir().as_local_hir_id(def_id).unwrap();
525 let (const_context, min_const_fn) = match tcx.hir().body_owner_kind(id) {
526 hir::BodyOwnerKind::Closure => (false, false),
527 hir::BodyOwnerKind::Fn => (is_const_fn(tcx, def_id), is_min_const_fn(tcx, def_id)),
528 hir::BodyOwnerKind::Const | hir::BodyOwnerKind::Static(_) => (true, false),
530 let mut checker = UnsafetyChecker::new(const_context, min_const_fn, body, tcx, param_env);
531 // mir_built ensures that body has a computed cache, so we don't (and can't) attempt to
532 // recompute it here.
533 let body = body.unwrap_read_only();
534 checker.visit_body(body);
536 check_unused_unsafe(tcx, def_id, &checker.used_unsafe, &mut checker.inherited_blocks);
537 UnsafetyCheckResult {
538 violations: checker.violations.into(),
539 unsafe_blocks: checker.inherited_blocks.into(),
543 fn unsafe_derive_on_repr_packed(tcx: TyCtxt<'_>, def_id: DefId) {
544 let lint_hir_id = tcx
546 .as_local_hir_id(def_id)
547 .unwrap_or_else(|| bug!("checking unsafety for non-local def id {:?}", def_id));
549 // FIXME: when we make this a hard error, this should have its
551 let message = if tcx.generics_of(def_id).own_requires_monomorphization() {
552 "`#[derive]` can't be used on a `#[repr(packed)]` struct with \
553 type or const parameters (error E0133)"
556 "`#[derive]` can't be used on a `#[repr(packed)]` struct that \
557 does not derive Copy (error E0133)"
560 tcx.lint_hir(SAFE_PACKED_BORROWS, lint_hir_id, tcx.def_span(def_id), &message);
563 /// Returns the `HirId` for an enclosing scope that is also `unsafe`.
566 used_unsafe: &FxHashSet<hir::HirId>,
568 ) -> Option<(String, hir::HirId)> {
569 let parent_id = tcx.hir().get_parent_node(id);
571 if used_unsafe.contains(&parent_id) {
572 Some(("block".to_string(), parent_id))
573 } else if let Some(Node::Item(&hir::Item {
574 kind: hir::ItemKind::Fn(ref sig, _, _), ..
575 })) = tcx.hir().find(parent_id)
577 match sig.header.unsafety {
578 hir::Unsafety::Unsafe => Some(("fn".to_string(), parent_id)),
579 hir::Unsafety::Normal => None,
582 is_enclosed(tcx, used_unsafe, parent_id)
589 fn report_unused_unsafe(tcx: TyCtxt<'_>, used_unsafe: &FxHashSet<hir::HirId>, id: hir::HirId) {
590 let span = tcx.sess.source_map().def_span(tcx.hir().span(id));
591 let msg = "unnecessary `unsafe` block";
592 let mut db = tcx.struct_span_lint_hir(UNUSED_UNSAFE, id, span, msg);
593 db.span_label(span, msg);
594 if let Some((kind, id)) = is_enclosed(tcx, used_unsafe, id) {
596 tcx.sess.source_map().def_span(tcx.hir().span(id)),
597 format!("because it's nested under this `unsafe` {}", kind),
603 fn builtin_derive_def_id(tcx: TyCtxt<'_>, def_id: DefId) -> Option<DefId> {
604 debug!("builtin_derive_def_id({:?})", def_id);
605 if let Some(impl_def_id) = tcx.impl_of_method(def_id) {
606 if tcx.has_attr(impl_def_id, sym::automatically_derived) {
607 debug!("builtin_derive_def_id({:?}) - is {:?}", def_id, impl_def_id);
610 debug!("builtin_derive_def_id({:?}) - not automatically derived", def_id);
614 debug!("builtin_derive_def_id({:?}) - not a method", def_id);
619 pub fn check_unsafety(tcx: TyCtxt<'_>, def_id: DefId) {
620 debug!("check_unsafety({:?})", def_id);
622 // closures are handled by their parent fn.
623 if tcx.is_closure(def_id) {
627 let UnsafetyCheckResult { violations, unsafe_blocks } = tcx.unsafety_check_result(def_id);
629 for &UnsafetyViolation { source_info, description, details, kind } in violations.iter() {
632 UnsafetyViolationKind::GeneralAndConstFn | UnsafetyViolationKind::General => {
637 "{} is unsafe and requires unsafe function or block",
640 .span_label(source_info.span, &*description.as_str())
641 .note(&details.as_str())
644 UnsafetyViolationKind::BorrowPacked(lint_hir_id) => {
645 if let Some(impl_def_id) = builtin_derive_def_id(tcx, def_id) {
646 tcx.unsafe_derive_on_repr_packed(impl_def_id);
653 "{} is unsafe and requires unsafe function or block \
664 let mut unsafe_blocks: Vec<_> = unsafe_blocks.into_iter().collect();
665 unsafe_blocks.sort_by_cached_key(|(hir_id, _)| tcx.hir().hir_to_node_id(*hir_id));
666 let used_unsafe: FxHashSet<_> =
667 unsafe_blocks.iter().flat_map(|&&(id, used)| used.then_some(id)).collect();
668 for &(block_id, is_used) in unsafe_blocks {
670 report_unused_unsafe(tcx, &used_unsafe, block_id);