2021-06-27 07:59:38 -05:00
|
|
|
use crate::build::ExprCategory;
|
2021-09-06 18:05:24 -05:00
|
|
|
use rustc_middle::thir::visit::{self, Visitor};
|
2021-03-14 14:10:22 -05:00
|
|
|
|
|
|
|
use rustc_errors::struct_span_err;
|
|
|
|
use rustc_hir as hir;
|
2021-06-27 07:59:38 -05:00
|
|
|
use rustc_middle::mir::BorrowKind;
|
2021-05-13 16:36:19 -05:00
|
|
|
use rustc_middle::thir::*;
|
2021-07-23 08:26:12 -05:00
|
|
|
use rustc_middle::ty::{self, ParamEnv, Ty, TyCtxt};
|
2021-03-14 14:10:22 -05:00
|
|
|
use rustc_session::lint::builtin::{UNSAFE_OP_IN_UNSAFE_FN, UNUSED_UNSAFE};
|
|
|
|
use rustc_session::lint::Level;
|
|
|
|
use rustc_span::def_id::{DefId, LocalDefId};
|
2021-05-14 16:52:34 -05:00
|
|
|
use rustc_span::symbol::Symbol;
|
2021-03-14 14:10:22 -05:00
|
|
|
use rustc_span::Span;
|
|
|
|
|
2022-04-24 07:08:23 -05:00
|
|
|
use std::borrow::Cow;
|
2021-05-15 08:26:28 -05:00
|
|
|
use std::ops::Bound;
|
|
|
|
|
2021-05-13 15:01:25 -05:00
|
|
|
struct UnsafetyVisitor<'a, 'tcx> {
|
2021-03-14 14:10:22 -05:00
|
|
|
tcx: TyCtxt<'tcx>,
|
2021-05-13 15:01:25 -05:00
|
|
|
thir: &'a Thir<'tcx>,
|
2021-03-14 14:10:22 -05:00
|
|
|
/// The `HirId` of the current scope, which would be the `HirId`
|
|
|
|
/// of the current HIR node, modulo adjustments. Used for lint levels.
|
|
|
|
hir_context: hir::HirId,
|
|
|
|
/// The current "safety context". This notably tracks whether we are in an
|
|
|
|
/// `unsafe` block, and whether it has been used.
|
|
|
|
safety_context: SafetyContext,
|
|
|
|
body_unsafety: BodyUnsafety,
|
2021-05-14 16:52:34 -05:00
|
|
|
/// The `#[target_feature]` attributes of the body. Used for checking
|
|
|
|
/// calls to functions with `#[target_feature]` (RFC 2396).
|
2022-05-04 04:18:37 -05:00
|
|
|
body_target_features: &'tcx [Symbol],
|
2021-07-23 08:26:12 -05:00
|
|
|
/// When inside the LHS of an assignment to a field, this is the type
|
|
|
|
/// of the LHS and the span of the assignment expression.
|
|
|
|
assignment_info: Option<(Ty<'tcx>, Span)>,
|
2021-05-13 09:42:25 -05:00
|
|
|
in_union_destructure: bool,
|
2021-06-27 07:59:38 -05:00
|
|
|
param_env: ParamEnv<'tcx>,
|
|
|
|
inside_adt: bool,
|
2021-03-14 14:10:22 -05:00
|
|
|
}
|
|
|
|
|
2021-05-13 15:01:25 -05:00
|
|
|
impl<'tcx> UnsafetyVisitor<'_, 'tcx> {
|
2021-04-29 20:54:22 -05:00
|
|
|
fn in_safety_context(&mut self, safety_context: SafetyContext, f: impl FnOnce(&mut Self)) {
|
2021-04-03 15:45:33 -05:00
|
|
|
if let (
|
|
|
|
SafetyContext::UnsafeBlock { span: enclosing_span, .. },
|
|
|
|
SafetyContext::UnsafeBlock { span: block_span, hir_id, .. },
|
|
|
|
) = (self.safety_context, safety_context)
|
|
|
|
{
|
|
|
|
self.warn_unused_unsafe(
|
|
|
|
hir_id,
|
|
|
|
block_span,
|
2021-05-24 05:54:26 -05:00
|
|
|
Some((self.tcx.sess.source_map().guess_head_span(enclosing_span), "block")),
|
2021-04-03 15:45:33 -05:00
|
|
|
);
|
|
|
|
f(self);
|
|
|
|
} else {
|
|
|
|
let prev_context = self.safety_context;
|
|
|
|
self.safety_context = safety_context;
|
|
|
|
|
|
|
|
f(self);
|
|
|
|
|
|
|
|
if let SafetyContext::UnsafeBlock { used: false, span, hir_id } = self.safety_context {
|
2021-05-24 05:54:26 -05:00
|
|
|
self.warn_unused_unsafe(
|
|
|
|
hir_id,
|
|
|
|
span,
|
|
|
|
if self.unsafe_op_in_unsafe_fn_allowed() {
|
|
|
|
self.body_unsafety.unsafe_fn_sig_span().map(|span| (span, "fn"))
|
|
|
|
} else {
|
|
|
|
None
|
|
|
|
},
|
|
|
|
);
|
2021-04-03 15:45:33 -05:00
|
|
|
}
|
|
|
|
self.safety_context = prev_context;
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2021-03-14 14:10:22 -05:00
|
|
|
fn requires_unsafe(&mut self, span: Span, kind: UnsafeOpKind) {
|
|
|
|
let unsafe_op_in_unsafe_fn_allowed = self.unsafe_op_in_unsafe_fn_allowed();
|
|
|
|
match self.safety_context {
|
2021-04-29 20:54:22 -05:00
|
|
|
SafetyContext::BuiltinUnsafeBlock => {}
|
2021-03-14 14:10:22 -05:00
|
|
|
SafetyContext::UnsafeBlock { ref mut used, .. } => {
|
2022-08-02 14:47:14 -05:00
|
|
|
// Mark this block as useful (even inside `unsafe fn`, where it is technically
|
|
|
|
// redundant -- but we want to eventually enable `unsafe_op_in_unsafe_fn` by
|
2022-08-02 17:57:22 -05:00
|
|
|
// default which will require those blocks:
|
|
|
|
// https://github.com/rust-lang/rust/issues/71668#issuecomment-1203075594).
|
2022-08-02 14:47:14 -05:00
|
|
|
*used = true;
|
2021-03-14 14:10:22 -05:00
|
|
|
}
|
|
|
|
SafetyContext::UnsafeFn if unsafe_op_in_unsafe_fn_allowed => {}
|
|
|
|
SafetyContext::UnsafeFn => {
|
2022-04-24 07:08:23 -05:00
|
|
|
let (description, note) = kind.description_and_note(self.tcx);
|
2021-03-14 14:10:22 -05:00
|
|
|
// unsafe_op_in_unsafe_fn is disallowed
|
2021-05-24 05:43:51 -05:00
|
|
|
self.tcx.struct_span_lint_hir(
|
|
|
|
UNSAFE_OP_IN_UNSAFE_FN,
|
|
|
|
self.hir_context,
|
2021-05-17 12:32:14 -05:00
|
|
|
span,
|
2022-09-16 02:01:02 -05:00
|
|
|
format!("{} is unsafe and requires unsafe block (error E0133)", description,),
|
|
|
|
|lint| lint.span_label(span, kind.simple_description()).note(note),
|
2021-05-17 12:32:14 -05:00
|
|
|
)
|
2021-03-14 14:10:22 -05:00
|
|
|
}
|
|
|
|
SafetyContext::Safe => {
|
2022-04-24 07:08:23 -05:00
|
|
|
let (description, note) = kind.description_and_note(self.tcx);
|
2021-05-17 12:32:14 -05:00
|
|
|
let fn_sugg = if unsafe_op_in_unsafe_fn_allowed { " function or" } else { "" };
|
|
|
|
struct_span_err!(
|
|
|
|
self.tcx.sess,
|
|
|
|
span,
|
|
|
|
E0133,
|
|
|
|
"{} is unsafe and requires unsafe{} block",
|
|
|
|
description,
|
|
|
|
fn_sugg,
|
|
|
|
)
|
2022-04-24 07:42:30 -05:00
|
|
|
.span_label(span, kind.simple_description())
|
2021-05-17 12:32:14 -05:00
|
|
|
.note(note)
|
|
|
|
.emit();
|
2021-03-14 14:10:22 -05:00
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
fn warn_unused_unsafe(
|
|
|
|
&self,
|
|
|
|
hir_id: hir::HirId,
|
|
|
|
block_span: Span,
|
2021-05-24 05:54:26 -05:00
|
|
|
enclosing_unsafe: Option<(Span, &'static str)>,
|
2021-03-14 14:10:22 -05:00
|
|
|
) {
|
|
|
|
let block_span = self.tcx.sess.source_map().guess_head_span(block_span);
|
2022-09-16 02:01:02 -05:00
|
|
|
let msg = "unnecessary `unsafe` block";
|
|
|
|
self.tcx.struct_span_lint_hir(UNUSED_UNSAFE, hir_id, block_span, msg, |lint| {
|
|
|
|
lint.span_label(block_span, msg);
|
2021-05-24 05:54:26 -05:00
|
|
|
if let Some((span, kind)) = enclosing_unsafe {
|
2022-09-16 02:01:02 -05:00
|
|
|
lint.span_label(span, format!("because it's nested under this `unsafe` {}", kind));
|
2021-03-14 14:10:22 -05:00
|
|
|
}
|
2022-09-16 02:01:02 -05:00
|
|
|
lint
|
2021-03-14 14:10:22 -05:00
|
|
|
});
|
|
|
|
}
|
|
|
|
|
|
|
|
/// Whether the `unsafe_op_in_unsafe_fn` lint is `allow`ed at the current HIR node.
|
|
|
|
fn unsafe_op_in_unsafe_fn_allowed(&self) -> bool {
|
|
|
|
self.tcx.lint_level_at_node(UNSAFE_OP_IN_UNSAFE_FN, self.hir_context).0 == Level::Allow
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2021-06-27 07:59:38 -05:00
|
|
|
// Searches for accesses to layout constrained fields.
|
|
|
|
struct LayoutConstrainedPlaceVisitor<'a, 'tcx> {
|
|
|
|
found: bool,
|
|
|
|
thir: &'a Thir<'tcx>,
|
|
|
|
tcx: TyCtxt<'tcx>,
|
|
|
|
}
|
|
|
|
|
|
|
|
impl<'a, 'tcx> LayoutConstrainedPlaceVisitor<'a, 'tcx> {
|
|
|
|
fn new(thir: &'a Thir<'tcx>, tcx: TyCtxt<'tcx>) -> Self {
|
|
|
|
Self { found: false, thir, tcx }
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
impl<'a, 'tcx> Visitor<'a, 'tcx> for LayoutConstrainedPlaceVisitor<'a, 'tcx> {
|
|
|
|
fn thir(&self) -> &'a Thir<'tcx> {
|
|
|
|
self.thir
|
|
|
|
}
|
|
|
|
|
|
|
|
fn visit_expr(&mut self, expr: &Expr<'tcx>) {
|
|
|
|
match expr.kind {
|
|
|
|
ExprKind::Field { lhs, .. } => {
|
|
|
|
if let ty::Adt(adt_def, _) = self.thir[lhs].ty.kind() {
|
|
|
|
if (Bound::Unbounded, Bound::Unbounded)
|
2022-03-04 14:28:41 -06:00
|
|
|
!= self.tcx.layout_scalar_valid_range(adt_def.did())
|
2021-06-27 07:59:38 -05:00
|
|
|
{
|
|
|
|
self.found = true;
|
|
|
|
}
|
|
|
|
}
|
|
|
|
visit::walk_expr(self, expr);
|
|
|
|
}
|
|
|
|
|
|
|
|
// Keep walking through the expression as long as we stay in the same
|
|
|
|
// place, i.e. the expression is a place expression and not a dereference
|
|
|
|
// (since dereferencing something leads us to a different place).
|
|
|
|
ExprKind::Deref { .. } => {}
|
|
|
|
ref kind if ExprCategory::of(kind).map_or(true, |cat| cat == ExprCategory::Place) => {
|
|
|
|
visit::walk_expr(self, expr);
|
|
|
|
}
|
|
|
|
|
|
|
|
_ => {}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2021-05-13 15:01:25 -05:00
|
|
|
impl<'a, 'tcx> Visitor<'a, 'tcx> for UnsafetyVisitor<'a, 'tcx> {
|
|
|
|
fn thir(&self) -> &'a Thir<'tcx> {
|
|
|
|
&self.thir
|
|
|
|
}
|
|
|
|
|
|
|
|
fn visit_block(&mut self, block: &Block) {
|
2021-04-29 20:54:22 -05:00
|
|
|
match block.safety_mode {
|
|
|
|
// compiler-generated unsafe code should not count towards the usefulness of
|
|
|
|
// an outer unsafe block
|
|
|
|
BlockSafety::BuiltinUnsafe => {
|
|
|
|
self.in_safety_context(SafetyContext::BuiltinUnsafeBlock, |this| {
|
|
|
|
visit::walk_block(this, block)
|
|
|
|
});
|
|
|
|
}
|
|
|
|
BlockSafety::ExplicitUnsafe(hir_id) => {
|
|
|
|
self.in_safety_context(
|
|
|
|
SafetyContext::UnsafeBlock { span: block.span, hir_id, used: false },
|
|
|
|
|this| visit::walk_block(this, block),
|
|
|
|
);
|
|
|
|
}
|
|
|
|
BlockSafety::Safe => {
|
|
|
|
visit::walk_block(self, block);
|
|
|
|
}
|
2021-03-14 14:10:22 -05:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2021-05-13 09:42:25 -05:00
|
|
|
fn visit_pat(&mut self, pat: &Pat<'tcx>) {
|
|
|
|
if self.in_union_destructure {
|
2022-08-24 21:25:44 -05:00
|
|
|
match pat.kind {
|
2021-05-13 09:42:25 -05:00
|
|
|
// binding to a variable allows getting stuff out of variable
|
2021-06-27 07:59:38 -05:00
|
|
|
PatKind::Binding { .. }
|
2021-05-13 09:42:25 -05:00
|
|
|
// match is conditional on having this value
|
2021-06-27 07:59:38 -05:00
|
|
|
| PatKind::Constant { .. }
|
|
|
|
| PatKind::Variant { .. }
|
|
|
|
| PatKind::Leaf { .. }
|
|
|
|
| PatKind::Deref { .. }
|
|
|
|
| PatKind::Range { .. }
|
|
|
|
| PatKind::Slice { .. }
|
|
|
|
| PatKind::Array { .. } => {
|
2021-05-13 09:42:25 -05:00
|
|
|
self.requires_unsafe(pat.span, AccessToUnionField);
|
2021-06-27 07:59:38 -05:00
|
|
|
return; // we can return here since this already requires unsafe
|
2021-05-13 09:42:25 -05:00
|
|
|
}
|
|
|
|
// wildcard doesn't take anything
|
2021-06-27 07:59:38 -05:00
|
|
|
PatKind::Wild |
|
2021-05-13 09:42:25 -05:00
|
|
|
// these just wrap other patterns
|
2021-06-27 07:59:38 -05:00
|
|
|
PatKind::Or { .. } |
|
|
|
|
PatKind::AscribeUserType { .. } => {}
|
2021-05-13 09:42:25 -05:00
|
|
|
}
|
|
|
|
};
|
|
|
|
|
2022-08-24 21:25:44 -05:00
|
|
|
match &pat.kind {
|
2021-06-27 07:59:38 -05:00
|
|
|
PatKind::Leaf { .. } => {
|
|
|
|
if let ty::Adt(adt_def, ..) = pat.ty.kind() {
|
|
|
|
if adt_def.is_union() {
|
|
|
|
let old_in_union_destructure =
|
|
|
|
std::mem::replace(&mut self.in_union_destructure, true);
|
|
|
|
visit::walk_pat(self, pat);
|
|
|
|
self.in_union_destructure = old_in_union_destructure;
|
|
|
|
} else if (Bound::Unbounded, Bound::Unbounded)
|
2022-03-04 14:28:41 -06:00
|
|
|
!= self.tcx.layout_scalar_valid_range(adt_def.did())
|
2021-06-27 07:59:38 -05:00
|
|
|
{
|
|
|
|
let old_inside_adt = std::mem::replace(&mut self.inside_adt, true);
|
|
|
|
visit::walk_pat(self, pat);
|
|
|
|
self.inside_adt = old_inside_adt;
|
|
|
|
} else {
|
2021-05-13 09:42:25 -05:00
|
|
|
visit::walk_pat(self, pat);
|
|
|
|
}
|
2021-06-27 07:59:38 -05:00
|
|
|
} else {
|
|
|
|
visit::walk_pat(self, pat);
|
2021-05-13 09:42:25 -05:00
|
|
|
}
|
|
|
|
}
|
2021-06-27 07:59:38 -05:00
|
|
|
PatKind::Binding { mode: BindingMode::ByRef(borrow_kind), ty, .. } => {
|
|
|
|
if self.inside_adt {
|
2021-11-18 10:21:21 -06:00
|
|
|
let ty::Ref(_, ty, _) = ty.kind() else {
|
2021-06-27 07:59:38 -05:00
|
|
|
span_bug!(
|
|
|
|
pat.span,
|
|
|
|
"BindingMode::ByRef in pattern, but found non-reference type {}",
|
|
|
|
ty
|
|
|
|
);
|
2021-11-18 10:21:21 -06:00
|
|
|
};
|
|
|
|
match borrow_kind {
|
|
|
|
BorrowKind::Shallow | BorrowKind::Shared | BorrowKind::Unique => {
|
2022-10-27 05:45:02 -05:00
|
|
|
if !ty.is_freeze(self.tcx, self.param_env) {
|
2021-11-18 10:21:21 -06:00
|
|
|
self.requires_unsafe(pat.span, BorrowOfLayoutConstrainedField);
|
|
|
|
}
|
|
|
|
}
|
|
|
|
BorrowKind::Mut { .. } => {
|
|
|
|
self.requires_unsafe(pat.span, MutationOfLayoutConstrainedField);
|
|
|
|
}
|
2021-06-27 07:59:38 -05:00
|
|
|
}
|
|
|
|
}
|
|
|
|
visit::walk_pat(self, pat);
|
|
|
|
}
|
|
|
|
PatKind::Deref { .. } => {
|
|
|
|
let old_inside_adt = std::mem::replace(&mut self.inside_adt, false);
|
|
|
|
visit::walk_pat(self, pat);
|
|
|
|
self.inside_adt = old_inside_adt;
|
|
|
|
}
|
|
|
|
_ => {
|
|
|
|
visit::walk_pat(self, pat);
|
|
|
|
}
|
2021-05-13 09:42:25 -05:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2021-05-13 15:01:25 -05:00
|
|
|
fn visit_expr(&mut self, expr: &Expr<'tcx>) {
|
2021-07-23 08:26:12 -05:00
|
|
|
// could we be in the LHS of an assignment to a field?
|
2021-05-13 09:42:25 -05:00
|
|
|
match expr.kind {
|
|
|
|
ExprKind::Field { .. }
|
|
|
|
| ExprKind::VarRef { .. }
|
|
|
|
| ExprKind::UpvarRef { .. }
|
|
|
|
| ExprKind::Scope { .. }
|
|
|
|
| ExprKind::Cast { .. } => {}
|
|
|
|
|
|
|
|
ExprKind::AddressOf { .. }
|
|
|
|
| ExprKind::Adt { .. }
|
|
|
|
| ExprKind::Array { .. }
|
|
|
|
| ExprKind::Binary { .. }
|
|
|
|
| ExprKind::Block { .. }
|
|
|
|
| ExprKind::Borrow { .. }
|
|
|
|
| ExprKind::Literal { .. }
|
2022-03-11 05:07:53 -06:00
|
|
|
| ExprKind::NamedConst { .. }
|
2022-03-23 02:47:11 -05:00
|
|
|
| ExprKind::NonHirLiteral { .. }
|
2022-07-03 10:17:23 -05:00
|
|
|
| ExprKind::ZstLiteral { .. }
|
2022-03-11 05:07:53 -06:00
|
|
|
| ExprKind::ConstParam { .. }
|
2021-05-13 09:42:25 -05:00
|
|
|
| ExprKind::ConstBlock { .. }
|
|
|
|
| ExprKind::Deref { .. }
|
|
|
|
| ExprKind::Index { .. }
|
|
|
|
| ExprKind::NeverToAny { .. }
|
|
|
|
| ExprKind::PlaceTypeAscription { .. }
|
|
|
|
| ExprKind::ValueTypeAscription { .. }
|
|
|
|
| ExprKind::Pointer { .. }
|
|
|
|
| ExprKind::Repeat { .. }
|
|
|
|
| ExprKind::StaticRef { .. }
|
|
|
|
| ExprKind::ThreadLocalRef { .. }
|
|
|
|
| ExprKind::Tuple { .. }
|
|
|
|
| ExprKind::Unary { .. }
|
|
|
|
| ExprKind::Call { .. }
|
|
|
|
| ExprKind::Assign { .. }
|
|
|
|
| ExprKind::AssignOp { .. }
|
|
|
|
| ExprKind::Break { .. }
|
|
|
|
| ExprKind::Closure { .. }
|
|
|
|
| ExprKind::Continue { .. }
|
|
|
|
| ExprKind::Return { .. }
|
|
|
|
| ExprKind::Yield { .. }
|
|
|
|
| ExprKind::Loop { .. }
|
2021-08-08 09:49:13 -05:00
|
|
|
| ExprKind::Let { .. }
|
2021-05-13 09:42:25 -05:00
|
|
|
| ExprKind::Match { .. }
|
|
|
|
| ExprKind::Box { .. }
|
|
|
|
| ExprKind::If { .. }
|
|
|
|
| ExprKind::InlineAsm { .. }
|
|
|
|
| ExprKind::LogicalOp { .. }
|
2021-07-23 08:26:12 -05:00
|
|
|
| ExprKind::Use { .. } => {
|
|
|
|
// We don't need to save the old value and restore it
|
|
|
|
// because all the place expressions can't have more
|
|
|
|
// than one child.
|
|
|
|
self.assignment_info = None;
|
|
|
|
}
|
2021-05-13 09:42:25 -05:00
|
|
|
};
|
2021-03-14 14:10:22 -05:00
|
|
|
match expr.kind {
|
2021-04-03 15:45:33 -05:00
|
|
|
ExprKind::Scope { value, lint_level: LintLevel::Explicit(hir_id), region_scope: _ } => {
|
2021-03-14 14:10:22 -05:00
|
|
|
let prev_id = self.hir_context;
|
|
|
|
self.hir_context = hir_id;
|
2021-05-13 15:01:25 -05:00
|
|
|
self.visit_expr(&self.thir[value]);
|
2021-03-14 14:10:22 -05:00
|
|
|
self.hir_context = prev_id;
|
2021-05-13 09:42:25 -05:00
|
|
|
return; // don't visit the whole expression
|
2021-03-14 14:10:22 -05:00
|
|
|
}
|
2021-04-03 15:45:33 -05:00
|
|
|
ExprKind::Call { fun, ty: _, args: _, from_hir_call: _, fn_span: _ } => {
|
2021-05-13 15:01:25 -05:00
|
|
|
if self.thir[fun].ty.fn_sig(self.tcx).unsafety() == hir::Unsafety::Unsafe {
|
2022-04-24 07:08:23 -05:00
|
|
|
let func_id = if let ty::FnDef(func_id, _) = self.thir[fun].ty.kind() {
|
|
|
|
Some(*func_id)
|
|
|
|
} else {
|
|
|
|
None
|
|
|
|
};
|
|
|
|
self.requires_unsafe(expr.span, CallToUnsafeFunction(func_id));
|
2021-05-14 16:52:34 -05:00
|
|
|
} else if let &ty::FnDef(func_did, _) = self.thir[fun].ty.kind() {
|
|
|
|
// If the called function has target features the calling function hasn't,
|
2021-05-06 09:50:40 -05:00
|
|
|
// the call requires `unsafe`. Don't check this on wasm
|
|
|
|
// targets, though. For more information on wasm see the
|
2022-09-29 04:33:30 -05:00
|
|
|
// is_like_wasm check in hir_analysis/src/collect.rs
|
2021-05-06 09:50:40 -05:00
|
|
|
if !self.tcx.sess.target.options.is_like_wasm
|
|
|
|
&& !self
|
|
|
|
.tcx
|
|
|
|
.codegen_fn_attrs(func_did)
|
|
|
|
.target_features
|
|
|
|
.iter()
|
|
|
|
.all(|feature| self.body_target_features.contains(feature))
|
2021-05-14 16:52:34 -05:00
|
|
|
{
|
2022-04-24 07:08:23 -05:00
|
|
|
self.requires_unsafe(expr.span, CallToFunctionWith(func_did));
|
2021-05-14 16:52:34 -05:00
|
|
|
}
|
2021-03-14 14:10:22 -05:00
|
|
|
}
|
|
|
|
}
|
2021-05-14 16:19:59 -05:00
|
|
|
ExprKind::Deref { arg } => {
|
2021-05-16 17:29:54 -05:00
|
|
|
if let ExprKind::StaticRef { def_id, .. } = self.thir[arg].kind {
|
|
|
|
if self.tcx.is_mutable_static(def_id) {
|
|
|
|
self.requires_unsafe(expr.span, UseOfMutableStatic);
|
|
|
|
} else if self.tcx.is_foreign_item(def_id) {
|
|
|
|
self.requires_unsafe(expr.span, UseOfExternStatic);
|
|
|
|
}
|
|
|
|
} else if self.thir[arg].ty.is_unsafe_ptr() {
|
2021-05-14 16:19:59 -05:00
|
|
|
self.requires_unsafe(expr.span, DerefOfRawPointer);
|
|
|
|
}
|
|
|
|
}
|
2022-01-11 18:00:00 -06:00
|
|
|
ExprKind::InlineAsm { .. } => {
|
2021-05-16 17:29:54 -05:00
|
|
|
self.requires_unsafe(expr.span, UseOfInlineAssembly);
|
|
|
|
}
|
2022-08-23 21:59:06 -05:00
|
|
|
ExprKind::Adt(box AdtExpr {
|
2021-05-15 08:26:28 -05:00
|
|
|
adt_def,
|
|
|
|
variant_index: _,
|
|
|
|
substs: _,
|
|
|
|
user_ty: _,
|
|
|
|
fields: _,
|
|
|
|
base: _,
|
2022-03-04 14:28:41 -06:00
|
|
|
}) => match self.tcx.layout_scalar_valid_range(adt_def.did()) {
|
2021-05-15 08:26:28 -05:00
|
|
|
(Bound::Unbounded, Bound::Unbounded) => {}
|
|
|
|
_ => self.requires_unsafe(expr.span, InitializingTypeWith),
|
|
|
|
},
|
2022-08-23 20:28:05 -05:00
|
|
|
ExprKind::Closure(box ClosureExpr {
|
2021-05-23 11:10:32 -05:00
|
|
|
closure_id,
|
|
|
|
substs: _,
|
|
|
|
upvars: _,
|
|
|
|
movability: _,
|
|
|
|
fake_reads: _,
|
2022-08-23 20:28:05 -05:00
|
|
|
}) => {
|
2021-05-23 11:10:32 -05:00
|
|
|
let closure_def = if let Some((did, const_param_id)) =
|
|
|
|
ty::WithOptConstParam::try_lookup(closure_id, self.tcx)
|
|
|
|
{
|
|
|
|
ty::WithOptConstParam { did, const_param_did: Some(const_param_id) }
|
|
|
|
} else {
|
|
|
|
ty::WithOptConstParam::unknown(closure_id)
|
|
|
|
};
|
2022-01-22 18:49:12 -06:00
|
|
|
let (closure_thir, expr) = self.tcx.thir_body(closure_def).unwrap_or_else(|_| {
|
|
|
|
(self.tcx.alloc_steal_thir(Thir::new()), ExprId::from_u32(0))
|
|
|
|
});
|
2021-05-23 11:10:32 -05:00
|
|
|
let closure_thir = &closure_thir.borrow();
|
|
|
|
let hir_context = self.tcx.hir().local_def_id_to_hir_id(closure_id);
|
|
|
|
let mut closure_visitor =
|
|
|
|
UnsafetyVisitor { thir: closure_thir, hir_context, ..*self };
|
|
|
|
closure_visitor.visit_expr(&closure_thir[expr]);
|
|
|
|
// Unsafe blocks can be used in closures, make sure to take it into account
|
|
|
|
self.safety_context = closure_visitor.safety_context;
|
|
|
|
}
|
2021-05-13 09:42:25 -05:00
|
|
|
ExprKind::Field { lhs, .. } => {
|
2021-07-23 08:26:12 -05:00
|
|
|
let lhs = &self.thir[lhs];
|
2022-02-28 18:12:52 -06:00
|
|
|
if let ty::Adt(adt_def, _) = lhs.ty.kind() && adt_def.is_union() {
|
|
|
|
if let Some((assigned_ty, assignment_span)) = self.assignment_info {
|
2022-07-17 12:56:12 -05:00
|
|
|
if assigned_ty.needs_drop(self.tcx, self.param_env) {
|
2022-06-30 07:40:06 -05:00
|
|
|
// This would be unsafe, but should be outright impossible since we reject such unions.
|
2022-07-17 12:56:12 -05:00
|
|
|
self.tcx.sess.delay_span_bug(assignment_span, format!("union fields that need dropping should be impossible: {assigned_ty}"));
|
2021-05-13 09:42:25 -05:00
|
|
|
}
|
2022-02-28 18:12:52 -06:00
|
|
|
} else {
|
|
|
|
self.requires_unsafe(expr.span, AccessToUnionField);
|
2021-05-13 09:42:25 -05:00
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
2021-06-27 07:59:38 -05:00
|
|
|
ExprKind::Assign { lhs, rhs } | ExprKind::AssignOp { lhs, rhs, .. } => {
|
2021-07-23 08:26:12 -05:00
|
|
|
let lhs = &self.thir[lhs];
|
2021-06-27 07:59:38 -05:00
|
|
|
// First, check whether we are mutating a layout constrained field
|
|
|
|
let mut visitor = LayoutConstrainedPlaceVisitor::new(self.thir, self.tcx);
|
2021-07-23 08:26:12 -05:00
|
|
|
visit::walk_expr(&mut visitor, lhs);
|
2021-06-27 07:59:38 -05:00
|
|
|
if visitor.found {
|
|
|
|
self.requires_unsafe(expr.span, MutationOfLayoutConstrainedField);
|
|
|
|
}
|
|
|
|
|
|
|
|
// Second, check for accesses to union fields
|
|
|
|
// don't have any special handling for AssignOp since it causes a read *and* write to lhs
|
|
|
|
if matches!(expr.kind, ExprKind::Assign { .. }) {
|
2021-07-23 08:26:12 -05:00
|
|
|
self.assignment_info = Some((lhs.ty, expr.span));
|
|
|
|
visit::walk_expr(self, lhs);
|
|
|
|
self.assignment_info = None;
|
2021-06-27 07:59:38 -05:00
|
|
|
visit::walk_expr(self, &self.thir()[rhs]);
|
|
|
|
return; // we have already visited everything by now
|
|
|
|
}
|
2021-05-13 09:42:25 -05:00
|
|
|
}
|
2021-08-02 19:00:18 -05:00
|
|
|
ExprKind::Borrow { borrow_kind, arg } => {
|
|
|
|
let mut visitor = LayoutConstrainedPlaceVisitor::new(self.thir, self.tcx);
|
|
|
|
visit::walk_expr(&mut visitor, expr);
|
|
|
|
if visitor.found {
|
|
|
|
match borrow_kind {
|
|
|
|
BorrowKind::Shallow | BorrowKind::Shared | BorrowKind::Unique
|
2022-10-27 05:45:02 -05:00
|
|
|
if !self.thir[arg].ty.is_freeze(self.tcx, self.param_env) =>
|
2021-08-02 19:00:18 -05:00
|
|
|
{
|
|
|
|
self.requires_unsafe(expr.span, BorrowOfLayoutConstrainedField)
|
2021-06-27 07:59:38 -05:00
|
|
|
}
|
2021-08-02 19:00:18 -05:00
|
|
|
BorrowKind::Mut { .. } => {
|
|
|
|
self.requires_unsafe(expr.span, MutationOfLayoutConstrainedField)
|
|
|
|
}
|
|
|
|
BorrowKind::Shallow | BorrowKind::Shared | BorrowKind::Unique => {}
|
2021-06-27 07:59:38 -05:00
|
|
|
}
|
|
|
|
}
|
2021-08-02 19:00:18 -05:00
|
|
|
}
|
2021-08-08 09:49:13 -05:00
|
|
|
ExprKind::Let { expr: expr_id, .. } => {
|
|
|
|
let let_expr = &self.thir[expr_id];
|
2022-02-28 18:12:52 -06:00
|
|
|
if let ty::Adt(adt_def, _) = let_expr.ty.kind() && adt_def.is_union() {
|
|
|
|
self.requires_unsafe(expr.span, AccessToUnionField);
|
2021-08-08 09:49:13 -05:00
|
|
|
}
|
|
|
|
}
|
2021-03-14 14:10:22 -05:00
|
|
|
_ => {}
|
|
|
|
}
|
|
|
|
visit::walk_expr(self, expr);
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
#[derive(Clone, Copy)]
|
|
|
|
enum SafetyContext {
|
|
|
|
Safe,
|
2021-04-29 20:54:22 -05:00
|
|
|
BuiltinUnsafeBlock,
|
2021-03-14 14:10:22 -05:00
|
|
|
UnsafeFn,
|
|
|
|
UnsafeBlock { span: Span, hir_id: hir::HirId, used: bool },
|
|
|
|
}
|
|
|
|
|
|
|
|
#[derive(Clone, Copy)]
|
|
|
|
enum BodyUnsafety {
|
|
|
|
/// The body is not unsafe.
|
|
|
|
Safe,
|
|
|
|
/// The body is an unsafe function. The span points to
|
|
|
|
/// the signature of the function.
|
|
|
|
Unsafe(Span),
|
|
|
|
}
|
|
|
|
|
|
|
|
impl BodyUnsafety {
|
|
|
|
/// Returns whether the body is unsafe.
|
|
|
|
fn is_unsafe(&self) -> bool {
|
|
|
|
matches!(self, BodyUnsafety::Unsafe(_))
|
|
|
|
}
|
|
|
|
|
|
|
|
/// If the body is unsafe, returns the `Span` of its signature.
|
|
|
|
fn unsafe_fn_sig_span(self) -> Option<Span> {
|
|
|
|
match self {
|
|
|
|
BodyUnsafety::Unsafe(span) => Some(span),
|
|
|
|
BodyUnsafety::Safe => None,
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
#[derive(Clone, Copy, PartialEq)]
|
|
|
|
enum UnsafeOpKind {
|
2022-04-24 07:08:23 -05:00
|
|
|
CallToUnsafeFunction(Option<DefId>),
|
2021-03-14 14:10:22 -05:00
|
|
|
UseOfInlineAssembly,
|
|
|
|
InitializingTypeWith,
|
|
|
|
UseOfMutableStatic,
|
|
|
|
UseOfExternStatic,
|
|
|
|
DerefOfRawPointer,
|
|
|
|
AccessToUnionField,
|
|
|
|
MutationOfLayoutConstrainedField,
|
|
|
|
BorrowOfLayoutConstrainedField,
|
2022-04-24 07:08:23 -05:00
|
|
|
CallToFunctionWith(DefId),
|
2021-03-14 14:10:22 -05:00
|
|
|
}
|
|
|
|
|
|
|
|
use UnsafeOpKind::*;
|
|
|
|
|
|
|
|
impl UnsafeOpKind {
|
2022-04-24 07:42:30 -05:00
|
|
|
pub fn simple_description(&self) -> &'static str {
|
|
|
|
match self {
|
|
|
|
CallToUnsafeFunction(..) => "call to unsafe function",
|
|
|
|
UseOfInlineAssembly => "use of inline assembly",
|
|
|
|
InitializingTypeWith => "initializing type with `rustc_layout_scalar_valid_range` attr",
|
|
|
|
UseOfMutableStatic => "use of mutable static",
|
|
|
|
UseOfExternStatic => "use of extern static",
|
|
|
|
DerefOfRawPointer => "dereference of raw pointer",
|
|
|
|
AccessToUnionField => "access to union field",
|
|
|
|
MutationOfLayoutConstrainedField => "mutation of layout constrained field",
|
|
|
|
BorrowOfLayoutConstrainedField => {
|
|
|
|
"borrow of layout constrained field with interior mutability"
|
|
|
|
}
|
|
|
|
CallToFunctionWith(..) => "call to function with `#[target_feature]`",
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2022-04-24 07:08:23 -05:00
|
|
|
pub fn description_and_note(&self, tcx: TyCtxt<'_>) -> (Cow<'static, str>, &'static str) {
|
2021-03-14 14:10:22 -05:00
|
|
|
match self {
|
2022-04-24 07:08:23 -05:00
|
|
|
CallToUnsafeFunction(did) => (
|
|
|
|
if let Some(did) = did {
|
|
|
|
Cow::from(format!("call to unsafe function `{}`", tcx.def_path_str(*did)))
|
|
|
|
} else {
|
2022-04-24 07:42:30 -05:00
|
|
|
Cow::Borrowed(self.simple_description())
|
2022-04-24 07:08:23 -05:00
|
|
|
},
|
2021-03-14 14:10:22 -05:00
|
|
|
"consult the function's documentation for information on how to avoid undefined \
|
|
|
|
behavior",
|
|
|
|
),
|
|
|
|
UseOfInlineAssembly => (
|
2022-04-24 07:42:30 -05:00
|
|
|
Cow::Borrowed(self.simple_description()),
|
2021-03-14 14:10:22 -05:00
|
|
|
"inline assembly is entirely unchecked and can cause undefined behavior",
|
|
|
|
),
|
|
|
|
InitializingTypeWith => (
|
2022-04-24 07:42:30 -05:00
|
|
|
Cow::Borrowed(self.simple_description()),
|
2021-03-14 14:10:22 -05:00
|
|
|
"initializing a layout restricted type's field with a value outside the valid \
|
|
|
|
range is undefined behavior",
|
|
|
|
),
|
|
|
|
UseOfMutableStatic => (
|
2022-04-24 07:42:30 -05:00
|
|
|
Cow::Borrowed(self.simple_description()),
|
2021-03-14 14:10:22 -05:00
|
|
|
"mutable statics can be mutated by multiple threads: aliasing violations or data \
|
|
|
|
races will cause undefined behavior",
|
|
|
|
),
|
|
|
|
UseOfExternStatic => (
|
2022-04-24 07:42:30 -05:00
|
|
|
Cow::Borrowed(self.simple_description()),
|
2021-03-14 14:10:22 -05:00
|
|
|
"extern statics are not controlled by the Rust type system: invalid data, \
|
|
|
|
aliasing violations or data races will cause undefined behavior",
|
|
|
|
),
|
|
|
|
DerefOfRawPointer => (
|
2022-04-24 07:42:30 -05:00
|
|
|
Cow::Borrowed(self.simple_description()),
|
2021-05-24 05:59:33 -05:00
|
|
|
"raw pointers may be null, dangling or unaligned; they can violate aliasing rules \
|
2021-03-14 14:10:22 -05:00
|
|
|
and cause data races: all of these are undefined behavior",
|
|
|
|
),
|
|
|
|
AccessToUnionField => (
|
2022-04-24 07:42:30 -05:00
|
|
|
Cow::Borrowed(self.simple_description()),
|
2021-03-14 14:10:22 -05:00
|
|
|
"the field may not be properly initialized: using uninitialized data will cause \
|
|
|
|
undefined behavior",
|
|
|
|
),
|
|
|
|
MutationOfLayoutConstrainedField => (
|
2022-04-24 07:42:30 -05:00
|
|
|
Cow::Borrowed(self.simple_description()),
|
2021-03-14 14:10:22 -05:00
|
|
|
"mutating layout constrained fields cannot statically be checked for valid values",
|
|
|
|
),
|
|
|
|
BorrowOfLayoutConstrainedField => (
|
2022-04-24 07:42:30 -05:00
|
|
|
Cow::Borrowed(self.simple_description()),
|
2021-03-14 14:10:22 -05:00
|
|
|
"references to fields of layout constrained fields lose the constraints. Coupled \
|
|
|
|
with interior mutability, the field can be changed to invalid values",
|
|
|
|
),
|
2022-04-24 07:08:23 -05:00
|
|
|
CallToFunctionWith(did) => (
|
|
|
|
Cow::from(format!(
|
|
|
|
"call to function `{}` with `#[target_feature]`",
|
|
|
|
tcx.def_path_str(*did)
|
|
|
|
)),
|
2021-03-14 14:10:22 -05:00
|
|
|
"can only be called if the required target features are available",
|
|
|
|
),
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2021-05-13 16:36:19 -05:00
|
|
|
pub fn check_unsafety<'tcx>(tcx: TyCtxt<'tcx>, def: ty::WithOptConstParam<LocalDefId>) {
|
2021-05-24 08:09:33 -05:00
|
|
|
// THIR unsafeck is gated under `-Z thir-unsafeck`
|
2022-07-06 07:44:47 -05:00
|
|
|
if !tcx.sess.opts.unstable_opts.thir_unsafeck {
|
2021-05-24 08:09:33 -05:00
|
|
|
return;
|
|
|
|
}
|
|
|
|
|
2021-06-08 10:19:16 -05:00
|
|
|
// Closures are handled by their owner, if it has a body
|
2021-05-23 11:10:32 -05:00
|
|
|
if tcx.is_closure(def.did.to_def_id()) {
|
2021-07-30 12:04:16 -05:00
|
|
|
let hir = tcx.hir();
|
|
|
|
let owner = hir.enclosing_body_owner(hir.local_def_id_to_hir_id(def.did));
|
2022-07-19 16:47:49 -05:00
|
|
|
tcx.ensure().thir_check_unsafety(owner);
|
2021-07-30 12:04:16 -05:00
|
|
|
return;
|
2021-05-23 11:10:32 -05:00
|
|
|
}
|
|
|
|
|
2022-05-09 10:47:02 -05:00
|
|
|
let Ok((thir, expr)) = tcx.thir_body(def) else {
|
|
|
|
return
|
2022-01-22 18:49:12 -06:00
|
|
|
};
|
2021-05-13 16:36:19 -05:00
|
|
|
let thir = &thir.borrow();
|
2022-03-14 20:00:08 -05:00
|
|
|
// If `thir` is empty, a type error occurred, skip this body.
|
2021-05-22 08:40:26 -05:00
|
|
|
if thir.exprs.is_empty() {
|
|
|
|
return;
|
|
|
|
}
|
|
|
|
|
2021-05-13 16:36:19 -05:00
|
|
|
let hir_id = tcx.hir().local_def_id_to_hir_id(def.did);
|
2021-03-14 14:10:22 -05:00
|
|
|
let body_unsafety = tcx.hir().fn_sig_by_hir_id(hir_id).map_or(BodyUnsafety::Safe, |fn_sig| {
|
|
|
|
if fn_sig.header.unsafety == hir::Unsafety::Unsafe {
|
|
|
|
BodyUnsafety::Unsafe(fn_sig.span)
|
|
|
|
} else {
|
|
|
|
BodyUnsafety::Safe
|
|
|
|
}
|
|
|
|
});
|
2022-05-09 10:47:02 -05:00
|
|
|
let body_target_features = &tcx.body_codegen_attrs(def.did.to_def_id()).target_features;
|
2021-03-14 14:10:22 -05:00
|
|
|
let safety_context =
|
|
|
|
if body_unsafety.is_unsafe() { SafetyContext::UnsafeFn } else { SafetyContext::Safe };
|
2021-05-14 16:52:34 -05:00
|
|
|
let mut visitor = UnsafetyVisitor {
|
|
|
|
tcx,
|
|
|
|
thir,
|
|
|
|
safety_context,
|
|
|
|
hir_context: hir_id,
|
|
|
|
body_unsafety,
|
|
|
|
body_target_features,
|
2021-07-23 08:26:12 -05:00
|
|
|
assignment_info: None,
|
2021-05-13 09:42:25 -05:00
|
|
|
in_union_destructure: false,
|
2021-06-27 07:59:38 -05:00
|
|
|
param_env: tcx.param_env(def.did),
|
|
|
|
inside_adt: false,
|
2021-05-14 16:52:34 -05:00
|
|
|
};
|
2021-05-13 15:01:25 -05:00
|
|
|
visitor.visit_expr(&thir[expr]);
|
2021-03-14 14:10:22 -05:00
|
|
|
}
|
|
|
|
|
2022-05-20 18:51:09 -05:00
|
|
|
pub(crate) fn thir_check_unsafety<'tcx>(tcx: TyCtxt<'tcx>, def_id: LocalDefId) {
|
2021-03-14 14:10:22 -05:00
|
|
|
if let Some(def) = ty::WithOptConstParam::try_lookup(def_id, tcx) {
|
|
|
|
tcx.thir_check_unsafety_for_const_arg(def)
|
|
|
|
} else {
|
2021-05-13 16:36:19 -05:00
|
|
|
check_unsafety(tcx, ty::WithOptConstParam::unknown(def_id))
|
2021-03-14 14:10:22 -05:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2022-05-20 18:51:09 -05:00
|
|
|
pub(crate) fn thir_check_unsafety_for_const_arg<'tcx>(
|
2021-03-14 14:10:22 -05:00
|
|
|
tcx: TyCtxt<'tcx>,
|
|
|
|
(did, param_did): (LocalDefId, DefId),
|
|
|
|
) {
|
2021-05-13 16:36:19 -05:00
|
|
|
check_unsafety(tcx, ty::WithOptConstParam { did, const_param_did: Some(param_did) })
|
2021-03-14 14:10:22 -05:00
|
|
|
}
|