1 use rustc::hir::intravisit;
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;
13 use rustc_span::symbol::{sym, Symbol};
17 use crate::const_eval::{is_const_fn, is_min_const_fn};
20 use rustc_error_codes::*;
22 pub struct UnsafetyChecker<'a, 'tcx> {
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> {
41 param_env: ty::ParamEnv<'tcx>,
45 assert!(const_context);
52 source_info: SourceInfo { span: body.span, scope: OUTERMOST_SOURCE_SCOPE },
55 used_unsafe: Default::default(),
56 inherited_blocks: vec![],
61 impl<'a, 'tcx> Visitor<'tcx> for UnsafetyChecker<'a, 'tcx> {
62 fn visit_terminator(&mut self, terminator: &Terminator<'tcx>, location: Location) {
63 self.source_info = terminator.source_info;
64 match terminator.kind {
65 TerminatorKind::Goto { .. }
66 | TerminatorKind::SwitchInt { .. }
67 | TerminatorKind::Drop { .. }
68 | TerminatorKind::Yield { .. }
69 | TerminatorKind::Assert { .. }
70 | TerminatorKind::DropAndReplace { .. }
71 | TerminatorKind::GeneratorDrop
72 | TerminatorKind::Resume
73 | TerminatorKind::Abort
74 | TerminatorKind::Return
75 | TerminatorKind::Unreachable
76 | TerminatorKind::FalseEdges { .. }
77 | TerminatorKind::FalseUnwind { .. } => {
78 // safe (at least as emitted during MIR construction)
81 TerminatorKind::Call { ref func, .. } => {
82 let func_ty = func.ty(self.body, self.tcx);
83 let sig = func_ty.fn_sig(self.tcx);
84 if let hir::Unsafety::Unsafe = sig.unsafety() {
86 "call to unsafe function",
87 "consult the function's documentation for information on how to avoid \
89 UnsafetyViolationKind::GeneralAndConstFn,
94 self.super_terminator(terminator, location);
97 fn visit_statement(&mut self, statement: &Statement<'tcx>, location: Location) {
98 self.source_info = statement.source_info;
99 match statement.kind {
100 StatementKind::Assign(..)
101 | StatementKind::FakeRead(..)
102 | StatementKind::SetDiscriminant { .. }
103 | StatementKind::StorageLive(..)
104 | StatementKind::StorageDead(..)
105 | StatementKind::Retag { .. }
106 | StatementKind::AscribeUserType(..)
107 | StatementKind::Nop => {
108 // safe (at least as emitted during MIR construction)
111 StatementKind::InlineAsm { .. } => self.require_unsafe(
112 "use of inline assembly",
113 "inline assembly is entirely unchecked and can cause undefined behavior",
114 UnsafetyViolationKind::General,
117 self.super_statement(statement, location);
120 fn visit_rvalue(&mut self, rvalue: &Rvalue<'tcx>, location: Location) {
122 Rvalue::Aggregate(box ref aggregate, _) => match aggregate {
123 &AggregateKind::Array(..) | &AggregateKind::Tuple => {}
124 &AggregateKind::Adt(ref def, ..) => {
125 match self.tcx.layout_scalar_valid_range(def.did) {
126 (Bound::Unbounded, Bound::Unbounded) => {}
127 _ => self.require_unsafe(
128 "initializing type with `rustc_layout_scalar_valid_range` attr",
129 "initializing a layout restricted type's field with a value \
130 outside the valid range is undefined behavior",
131 UnsafetyViolationKind::GeneralAndConstFn,
135 &AggregateKind::Closure(def_id, _) | &AggregateKind::Generator(def_id, _, _) => {
136 let UnsafetyCheckResult { violations, unsafe_blocks } =
137 self.tcx.unsafety_check_result(def_id);
138 self.register_violations(&violations, &unsafe_blocks);
141 // casting pointers to ints is unsafe in const fn because the const evaluator cannot
142 // possibly know what the result of various operations like `address / 2` would be
143 // pointers during const evaluation have no integral address, only an abstract one
144 Rvalue::Cast(CastKind::Misc, ref operand, cast_ty)
145 if self.const_context && self.tcx.features().const_raw_ptr_to_usize_cast =>
147 let operand_ty = operand.ty(self.body, self.tcx);
148 let cast_in = CastTy::from_ty(operand_ty).expect("bad input type for cast");
149 let cast_out = CastTy::from_ty(cast_ty).expect("bad output type for cast");
150 match (cast_in, cast_out) {
151 (CastTy::Ptr(_), CastTy::Int(_)) | (CastTy::FnPtr, CastTy::Int(_)) => {
152 self.register_violations(
153 &[UnsafetyViolation {
154 source_info: self.source_info,
155 description: Symbol::intern("cast of pointer to int"),
156 details: Symbol::intern(
157 "casting pointers to integers in constants",
159 kind: UnsafetyViolationKind::General,
167 // raw pointer and fn pointer operations are unsafe as it is not clear whether one
168 // pointer would be "less" or "equal" to another, because we cannot know where llvm
169 // or the linker will place various statics in memory. Without this information the
170 // result of a comparison of addresses would differ between runtime and compile-time.
171 Rvalue::BinaryOp(_, ref lhs, _)
172 if self.const_context && self.tcx.features().const_compare_raw_pointers =>
174 if let ty::RawPtr(_) | ty::FnPtr(..) = lhs.ty(self.body, self.tcx).kind {
175 self.register_violations(
176 &[UnsafetyViolation {
177 source_info: self.source_info,
178 description: Symbol::intern("pointer operation"),
179 details: Symbol::intern("operations on pointers in constants"),
180 kind: UnsafetyViolationKind::General,
188 self.super_rvalue(rvalue, location);
191 fn visit_place(&mut self, place: &Place<'tcx>, context: PlaceContext, _location: Location) {
193 PlaceBase::Local(..) => {
196 PlaceBase::Static(box Static { kind: StaticKind::Promoted(_, _), .. }) => {
197 bug!("unsafety checking should happen before promotion");
199 PlaceBase::Static(box Static { kind: StaticKind::Static, .. }) => {
200 bug!("StaticKind::Static should not exist");
204 for (i, elem) in place.projection.iter().enumerate() {
205 let proj_base = &place.projection[..i];
207 if context.is_borrow() {
208 if util::is_disaligned(self.tcx, self.body, self.param_env, place) {
209 let source_info = self.source_info;
210 let lint_root = self.body.source_scopes[source_info.scope]
213 .assert_crate_local()
215 self.register_violations(
216 &[UnsafetyViolation {
218 description: Symbol::intern("borrow of packed field"),
219 details: Symbol::intern(
220 "fields of packed structs might be misaligned: dereferencing a \
221 misaligned pointer or even just creating a misaligned reference \
222 is undefined behavior",
224 kind: UnsafetyViolationKind::BorrowPacked(lint_root),
230 let is_borrow_of_interior_mut = context.is_borrow()
231 && !Place::ty_from(&place.base, proj_base, self.body, self.tcx).ty.is_freeze(
234 self.source_info.span,
239 // * `&x.field` if `field`'s type has interior mutability
240 // because either of these would allow modifying the layout constrained field and
241 // insert values that violate the layout constraints.
242 if context.is_mutating_use() || is_borrow_of_interior_mut {
243 self.check_mut_borrowing_layout_constrained_field(place, context.is_mutating_use());
245 let old_source_info = self.source_info;
246 if let (PlaceBase::Local(local), []) = (&place.base, proj_base) {
247 let decl = &self.body.local_decls[*local];
249 // Internal locals are used in the `move_val_init` desugaring.
250 // We want to check unsafety against the source info of the
251 // desugaring, rather than the source info of the RHS.
252 self.source_info = self.body.local_decls[*local].source_info;
253 } else if let LocalInfo::StaticRef { def_id, .. } = decl.local_info {
254 if self.tcx.is_mutable_static(def_id) {
256 "use of mutable static",
257 "mutable statics can be mutated by multiple threads: aliasing \
258 violations or data races will cause undefined behavior",
259 UnsafetyViolationKind::General,
262 } else if self.tcx.is_foreign_item(def_id) {
264 "use of extern static",
265 "extern statics are not controlled by the Rust type system: \
266 invalid data, aliasing violations or data races will cause \
268 UnsafetyViolationKind::General,
274 let base_ty = Place::ty_from(&place.base, proj_base, self.body, self.tcx).ty;
276 ty::RawPtr(..) => self.require_unsafe(
277 "dereference of raw pointer",
278 "raw pointers may be NULL, dangling or unaligned; they can violate \
279 aliasing rules and cause data races: all of these are undefined \
281 UnsafetyViolationKind::General,
285 if context == PlaceContext::MutatingUse(MutatingUseContext::Store)
286 || context == PlaceContext::MutatingUse(MutatingUseContext::Drop)
287 || context == PlaceContext::MutatingUse(MutatingUseContext::AsmOutput)
289 let elem_ty = match elem {
290 ProjectionElem::Field(_, ty) => ty,
292 self.source_info.span,
293 "non-field projection {:?} from union?",
297 if !elem_ty.is_copy_modulo_regions(
300 self.source_info.span,
303 "assignment to non-`Copy` union field",
304 "the previous content of the field will be dropped, which \
305 causes undefined behavior if the field was not properly \
307 UnsafetyViolationKind::GeneralAndConstFn,
310 // write to non-move union, safe
314 "access to union field",
315 "the field may not be properly initialized: using \
316 uninitialized data will cause undefined behavior",
317 UnsafetyViolationKind::GeneralAndConstFn,
324 self.source_info = old_source_info;
329 impl<'a, 'tcx> UnsafetyChecker<'a, 'tcx> {
332 description: &'static str,
333 details: &'static str,
334 kind: UnsafetyViolationKind,
336 let source_info = self.source_info;
337 self.register_violations(
338 &[UnsafetyViolation {
340 description: Symbol::intern(description),
341 details: Symbol::intern(details),
348 fn register_violations(
350 violations: &[UnsafetyViolation],
351 unsafe_blocks: &[(hir::HirId, bool)],
353 let safety = self.body.source_scopes[self.source_info.scope]
356 .assert_crate_local()
358 let within_unsafe = match safety {
359 // `unsafe` blocks are required in safe code
361 for violation in violations {
362 let mut violation = violation.clone();
363 match violation.kind {
364 UnsafetyViolationKind::GeneralAndConstFn
365 | UnsafetyViolationKind::General => {}
366 UnsafetyViolationKind::BorrowPacked(_) => {
367 if self.min_const_fn {
368 // const fns don't need to be backwards compatible and can
369 // emit these violations as a hard error instead of a backwards
371 violation.kind = UnsafetyViolationKind::General;
375 if !self.violations.contains(&violation) {
376 self.violations.push(violation)
381 // `unsafe` function bodies allow unsafe without additional unsafe blocks
382 Safety::BuiltinUnsafe | Safety::FnUnsafe => true,
383 Safety::ExplicitUnsafe(hir_id) => {
384 // mark unsafe block as used if there are any unsafe operations inside
385 if !violations.is_empty() {
386 self.used_unsafe.insert(hir_id);
388 // only some unsafety is allowed in const fn
389 if self.min_const_fn {
390 for violation in violations {
391 match violation.kind {
392 // these unsafe things are stable in const fn
393 UnsafetyViolationKind::GeneralAndConstFn => {}
394 // these things are forbidden in const fns
395 UnsafetyViolationKind::General
396 | UnsafetyViolationKind::BorrowPacked(_) => {
397 let mut violation = violation.clone();
398 // const fns don't need to be backwards compatible and can
399 // emit these violations as a hard error instead of a backwards
401 violation.kind = UnsafetyViolationKind::General;
402 if !self.violations.contains(&violation) {
403 self.violations.push(violation)
412 self.inherited_blocks.extend(
413 unsafe_blocks.iter().map(|&(hir_id, is_used)| (hir_id, is_used && !within_unsafe)),
416 fn check_mut_borrowing_layout_constrained_field(
421 let mut cursor = place.projection.as_ref();
422 while let &[ref proj_base @ .., elem] = cursor {
426 ProjectionElem::Field(..) => {
428 Place::ty_from(&place.base, proj_base, &self.body.local_decls, self.tcx).ty;
430 ty::Adt(def, _) => match self.tcx.layout_scalar_valid_range(def.did) {
431 (Bound::Unbounded, Bound::Unbounded) => {}
433 let (description, details) = if is_mut_use {
435 "mutation of layout constrained field",
436 "mutating layout constrained fields cannot statically be \
437 checked for valid values",
441 "borrow of layout constrained field with interior \
443 "references to fields of layout constrained fields \
444 lose the constraints. Coupled with interior mutability, \
445 the field can be changed to invalid values",
448 let source_info = self.source_info;
449 self.register_violations(
450 &[UnsafetyViolation {
452 description: Symbol::intern(description),
453 details: Symbol::intern(details),
454 kind: UnsafetyViolationKind::GeneralAndConstFn,
469 pub(crate) fn provide(providers: &mut Providers<'_>) {
470 *providers = Providers { unsafety_check_result, unsafe_derive_on_repr_packed, ..*providers };
473 struct UnusedUnsafeVisitor<'a> {
474 used_unsafe: &'a FxHashSet<hir::HirId>,
475 unsafe_blocks: &'a mut Vec<(hir::HirId, bool)>,
478 impl<'a, 'tcx> intravisit::Visitor<'tcx> for UnusedUnsafeVisitor<'a> {
479 fn nested_visit_map<'this>(&'this mut self) -> intravisit::NestedVisitorMap<'this, 'tcx> {
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);