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;
10 use rustc_hir::def_id::DefId;
12 use rustc_span::symbol::{sym, Symbol};
18 use rustc_error_codes::*;
20 pub struct UnsafetyChecker<'a, 'tcx> {
24 violations: Vec<UnsafetyViolation>,
25 source_info: SourceInfo,
27 param_env: ty::ParamEnv<'tcx>,
28 /// Mark an `unsafe` block as used, so we don't lint it.
29 used_unsafe: FxHashSet<hir::HirId>,
30 inherited_blocks: Vec<(hir::HirId, bool)>,
33 impl<'a, 'tcx> UnsafetyChecker<'a, 'tcx> {
39 param_env: ty::ParamEnv<'tcx>,
43 assert!(const_context);
50 source_info: SourceInfo { span: body.span, scope: OUTERMOST_SOURCE_SCOPE },
53 used_unsafe: Default::default(),
54 inherited_blocks: vec![],
59 impl<'a, 'tcx> Visitor<'tcx> for UnsafetyChecker<'a, 'tcx> {
60 fn visit_terminator(&mut self, terminator: &Terminator<'tcx>, location: Location) {
61 self.source_info = terminator.source_info;
62 match terminator.kind {
63 TerminatorKind::Goto { .. }
64 | TerminatorKind::SwitchInt { .. }
65 | TerminatorKind::Drop { .. }
66 | TerminatorKind::Yield { .. }
67 | TerminatorKind::Assert { .. }
68 | TerminatorKind::DropAndReplace { .. }
69 | TerminatorKind::GeneratorDrop
70 | TerminatorKind::Resume
71 | TerminatorKind::Abort
72 | TerminatorKind::Return
73 | TerminatorKind::Unreachable
74 | TerminatorKind::FalseEdges { .. }
75 | TerminatorKind::FalseUnwind { .. } => {
76 // safe (at least as emitted during MIR construction)
79 TerminatorKind::Call { ref func, .. } => {
80 let func_ty = func.ty(self.body, self.tcx);
81 let sig = func_ty.fn_sig(self.tcx);
82 if let hir::Unsafety::Unsafe = sig.unsafety() {
84 "call to unsafe function",
85 "consult the function's documentation for information on how to avoid \
87 UnsafetyViolationKind::GeneralAndConstFn,
92 self.super_terminator(terminator, location);
95 fn visit_statement(&mut self, statement: &Statement<'tcx>, location: Location) {
96 self.source_info = statement.source_info;
97 match statement.kind {
98 StatementKind::Assign(..)
99 | StatementKind::FakeRead(..)
100 | StatementKind::SetDiscriminant { .. }
101 | StatementKind::StorageLive(..)
102 | StatementKind::StorageDead(..)
103 | StatementKind::Retag { .. }
104 | StatementKind::AscribeUserType(..)
105 | StatementKind::Nop => {
106 // safe (at least as emitted during MIR construction)
109 StatementKind::InlineAsm { .. } => self.require_unsafe(
110 "use of inline assembly",
111 "inline assembly is entirely unchecked and can cause undefined behavior",
112 UnsafetyViolationKind::General,
115 self.super_statement(statement, location);
118 fn visit_rvalue(&mut self, rvalue: &Rvalue<'tcx>, location: Location) {
120 Rvalue::Aggregate(box ref aggregate, _) => match aggregate {
121 &AggregateKind::Array(..) | &AggregateKind::Tuple => {}
122 &AggregateKind::Adt(ref def, ..) => {
123 match self.tcx.layout_scalar_valid_range(def.did) {
124 (Bound::Unbounded, Bound::Unbounded) => {}
125 _ => self.require_unsafe(
126 "initializing type with `rustc_layout_scalar_valid_range` attr",
127 "initializing a layout restricted type's field with a value \
128 outside the valid range is undefined behavior",
129 UnsafetyViolationKind::GeneralAndConstFn,
133 &AggregateKind::Closure(def_id, _) | &AggregateKind::Generator(def_id, _, _) => {
134 let UnsafetyCheckResult { violations, unsafe_blocks } =
135 self.tcx.unsafety_check_result(def_id);
136 self.register_violations(&violations, &unsafe_blocks);
139 // casting pointers to ints is unsafe in const fn because the const evaluator cannot
140 // possibly know what the result of various operations like `address / 2` would be
141 // pointers during const evaluation have no integral address, only an abstract one
142 Rvalue::Cast(CastKind::Misc, ref operand, cast_ty)
143 if self.const_context && self.tcx.features().const_raw_ptr_to_usize_cast =>
145 let operand_ty = operand.ty(self.body, self.tcx);
146 let cast_in = CastTy::from_ty(operand_ty).expect("bad input type for cast");
147 let cast_out = CastTy::from_ty(cast_ty).expect("bad output type for cast");
148 match (cast_in, cast_out) {
149 (CastTy::Ptr(_), CastTy::Int(_)) | (CastTy::FnPtr, CastTy::Int(_)) => {
150 self.register_violations(
151 &[UnsafetyViolation {
152 source_info: self.source_info,
153 description: Symbol::intern("cast of pointer to int"),
154 details: Symbol::intern(
155 "casting pointers to integers in constants",
157 kind: UnsafetyViolationKind::General,
165 // raw pointer and fn pointer operations are unsafe as it is not clear whether one
166 // pointer would be "less" or "equal" to another, because we cannot know where llvm
167 // or the linker will place various statics in memory. Without this information the
168 // result of a comparison of addresses would differ between runtime and compile-time.
169 Rvalue::BinaryOp(_, ref lhs, _)
170 if self.const_context && self.tcx.features().const_compare_raw_pointers =>
172 if let ty::RawPtr(_) | ty::FnPtr(..) = lhs.ty(self.body, self.tcx).kind {
173 self.register_violations(
174 &[UnsafetyViolation {
175 source_info: self.source_info,
176 description: Symbol::intern("pointer operation"),
177 details: Symbol::intern("operations on pointers in constants"),
178 kind: UnsafetyViolationKind::General,
186 self.super_rvalue(rvalue, location);
189 fn visit_place(&mut self, place: &Place<'tcx>, context: PlaceContext, _location: Location) {
191 PlaceBase::Local(..) => {
194 PlaceBase::Static(box Static { kind: StaticKind::Promoted(_, _), .. }) => {
195 bug!("unsafety checking should happen before promotion");
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 fn nested_visit_map<'this>(&'this mut self) -> intravisit::NestedVisitorMap<'this, 'tcx> {
478 intravisit::NestedVisitorMap::None
481 fn visit_block(&mut self, block: &'tcx hir::Block<'tcx>) {
482 intravisit::walk_block(self, block);
484 if let hir::BlockCheckMode::UnsafeBlock(hir::UnsafeSource::UserProvided) = block.rules {
485 self.unsafe_blocks.push((block.hir_id, self.used_unsafe.contains(&block.hir_id)));
490 fn check_unused_unsafe(
493 used_unsafe: &FxHashSet<hir::HirId>,
494 unsafe_blocks: &mut Vec<(hir::HirId, bool)>,
497 tcx.hir().as_local_hir_id(def_id).and_then(|hir_id| tcx.hir().maybe_body_owned_by(hir_id));
499 let body_id = match body_id {
502 debug!("check_unused_unsafe({:?}) - no body found", def_id);
506 let body = tcx.hir().body(body_id);
507 debug!("check_unused_unsafe({:?}, body={:?}, used_unsafe={:?})", def_id, body, used_unsafe);
509 let mut visitor = UnusedUnsafeVisitor { used_unsafe, unsafe_blocks };
510 intravisit::Visitor::visit_body(&mut visitor, body);
513 fn unsafety_check_result(tcx: TyCtxt<'_>, def_id: DefId) -> UnsafetyCheckResult {
514 debug!("unsafety_violations({:?})", def_id);
516 // N.B., this borrow is valid because all the consumers of
517 // `mir_built` force this.
518 let body = &tcx.mir_built(def_id).borrow();
520 let param_env = tcx.param_env(def_id);
522 let id = tcx.hir().as_local_hir_id(def_id).unwrap();
523 let (const_context, min_const_fn) = match tcx.hir().body_owner_kind(id) {
524 hir::BodyOwnerKind::Closure => (false, false),
525 hir::BodyOwnerKind::Fn => (tcx.is_const_fn(def_id), tcx.is_min_const_fn(def_id)),
526 hir::BodyOwnerKind::Const | hir::BodyOwnerKind::Static(_) => (true, false),
528 let mut checker = UnsafetyChecker::new(const_context, min_const_fn, body, tcx, param_env);
529 // mir_built ensures that body has a computed cache, so we don't (and can't) attempt to
530 // recompute it here.
531 let body = body.unwrap_read_only();
532 checker.visit_body(body);
534 check_unused_unsafe(tcx, def_id, &checker.used_unsafe, &mut checker.inherited_blocks);
535 UnsafetyCheckResult {
536 violations: checker.violations.into(),
537 unsafe_blocks: checker.inherited_blocks.into(),
541 fn unsafe_derive_on_repr_packed(tcx: TyCtxt<'_>, def_id: DefId) {
542 let lint_hir_id = tcx
544 .as_local_hir_id(def_id)
545 .unwrap_or_else(|| bug!("checking unsafety for non-local def id {:?}", def_id));
547 // FIXME: when we make this a hard error, this should have its
549 let message = if tcx.generics_of(def_id).own_requires_monomorphization() {
550 "`#[derive]` can't be used on a `#[repr(packed)]` struct with \
551 type or const parameters (error E0133)"
554 "`#[derive]` can't be used on a `#[repr(packed)]` struct that \
555 does not derive Copy (error E0133)"
558 tcx.lint_hir(SAFE_PACKED_BORROWS, lint_hir_id, tcx.def_span(def_id), &message);
561 /// Returns the `HirId` for an enclosing scope that is also `unsafe`.
564 used_unsafe: &FxHashSet<hir::HirId>,
566 ) -> Option<(String, hir::HirId)> {
567 let parent_id = tcx.hir().get_parent_node(id);
569 if used_unsafe.contains(&parent_id) {
570 Some(("block".to_string(), parent_id))
571 } else if let Some(Node::Item(&hir::Item {
572 kind: hir::ItemKind::Fn(ref sig, _, _), ..
573 })) = tcx.hir().find(parent_id)
575 match sig.header.unsafety {
576 hir::Unsafety::Unsafe => Some(("fn".to_string(), parent_id)),
577 hir::Unsafety::Normal => None,
580 is_enclosed(tcx, used_unsafe, parent_id)
587 fn report_unused_unsafe(tcx: TyCtxt<'_>, used_unsafe: &FxHashSet<hir::HirId>, id: hir::HirId) {
588 let span = tcx.sess.source_map().def_span(tcx.hir().span(id));
589 let msg = "unnecessary `unsafe` block";
590 let mut db = tcx.struct_span_lint_hir(UNUSED_UNSAFE, id, span, msg);
591 db.span_label(span, msg);
592 if let Some((kind, id)) = is_enclosed(tcx, used_unsafe, id) {
594 tcx.sess.source_map().def_span(tcx.hir().span(id)),
595 format!("because it's nested under this `unsafe` {}", kind),
601 fn builtin_derive_def_id(tcx: TyCtxt<'_>, def_id: DefId) -> Option<DefId> {
602 debug!("builtin_derive_def_id({:?})", def_id);
603 if let Some(impl_def_id) = tcx.impl_of_method(def_id) {
604 if tcx.has_attr(impl_def_id, sym::automatically_derived) {
605 debug!("builtin_derive_def_id({:?}) - is {:?}", def_id, impl_def_id);
608 debug!("builtin_derive_def_id({:?}) - not automatically derived", def_id);
612 debug!("builtin_derive_def_id({:?}) - not a method", def_id);
617 pub fn check_unsafety(tcx: TyCtxt<'_>, def_id: DefId) {
618 debug!("check_unsafety({:?})", def_id);
620 // closures are handled by their parent fn.
621 if tcx.is_closure(def_id) {
625 let UnsafetyCheckResult { violations, unsafe_blocks } = tcx.unsafety_check_result(def_id);
627 for &UnsafetyViolation { source_info, description, details, kind } in violations.iter() {
630 UnsafetyViolationKind::GeneralAndConstFn | UnsafetyViolationKind::General => {
635 "{} is unsafe and requires unsafe function or block",
638 .span_label(source_info.span, &*description.as_str())
639 .note(&details.as_str())
642 UnsafetyViolationKind::BorrowPacked(lint_hir_id) => {
643 if let Some(impl_def_id) = builtin_derive_def_id(tcx, def_id) {
644 tcx.unsafe_derive_on_repr_packed(impl_def_id);
651 "{} is unsafe and requires unsafe function or block \
662 let mut unsafe_blocks: Vec<_> = unsafe_blocks.into_iter().collect();
663 unsafe_blocks.sort_by_cached_key(|(hir_id, _)| tcx.hir().hir_to_node_id(*hir_id));
664 let used_unsafe: FxHashSet<_> =
665 unsafe_blocks.iter().flat_map(|&&(id, used)| used.then_some(id)).collect();
666 for &(block_id, is_used) in unsafe_blocks {
668 report_unused_unsafe(tcx, &used_unsafe, block_id);