1
Fork 0

Rollup merge of #118909 - Urgau:cleanup-improvement-invalid_ref_casting, r=est31

Some cleanup and improvement for invalid ref casting impl

This PR makes some cleanups and improvements to the `invalid_reference_casting` implementation in preparation for linting on new patterns, while reusing most of the logic.

r? `@est31` (feel free to re-assign)
This commit is contained in:
Guillaume Gomez 2023-12-15 11:51:24 +01:00 committed by GitHub
commit 25216b65f4
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
3 changed files with 114 additions and 63 deletions

View file

@ -37,59 +37,73 @@ declare_lint_pass!(InvalidReferenceCasting => [INVALID_REFERENCE_CASTING]);
impl<'tcx> LateLintPass<'tcx> for InvalidReferenceCasting { impl<'tcx> LateLintPass<'tcx> for InvalidReferenceCasting {
fn check_expr(&mut self, cx: &LateContext<'tcx>, expr: &'tcx Expr<'tcx>) { fn check_expr(&mut self, cx: &LateContext<'tcx>, expr: &'tcx Expr<'tcx>) {
let Some((is_assignment, e)) = is_operation_we_care_about(cx, expr) else { if let Some((e, pat)) = borrow_or_assign(cx, expr) {
return; if matches!(pat, PatternKind::Borrow { mutbl: Mutability::Mut } | PatternKind::Assign) {
}; let init = cx.expr_or_init(e);
let init = cx.expr_or_init(e); let Some(ty_has_interior_mutability) = is_cast_from_ref_to_mut_ptr(cx, init) else {
return;
};
let orig_cast = if init.span != e.span { Some(init.span) } else { None };
let ty_has_interior_mutability = ty_has_interior_mutability.then_some(());
let Some(ty_has_interior_mutability) = is_cast_from_const_to_mut(cx, init) else { cx.emit_spanned_lint(
return; INVALID_REFERENCE_CASTING,
}; expr.span,
let orig_cast = if init.span != e.span { Some(init.span) } else { None }; if pat == PatternKind::Assign {
let ty_has_interior_mutability = ty_has_interior_mutability.then_some(()); InvalidReferenceCastingDiag::AssignToRef {
orig_cast,
cx.emit_spanned_lint( ty_has_interior_mutability,
INVALID_REFERENCE_CASTING, }
expr.span, } else {
if is_assignment { InvalidReferenceCastingDiag::BorrowAsMut {
InvalidReferenceCastingDiag::AssignToRef { orig_cast, ty_has_interior_mutability } orig_cast,
} else { ty_has_interior_mutability,
InvalidReferenceCastingDiag::BorrowAsMut { orig_cast, ty_has_interior_mutability } }
}, },
); );
}
}
} }
} }
fn is_operation_we_care_about<'tcx>( #[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum PatternKind {
Borrow { mutbl: Mutability },
Assign,
}
fn borrow_or_assign<'tcx>(
cx: &LateContext<'tcx>, cx: &LateContext<'tcx>,
e: &'tcx Expr<'tcx>, e: &'tcx Expr<'tcx>,
) -> Option<(bool, &'tcx Expr<'tcx>)> { ) -> Option<(&'tcx Expr<'tcx>, PatternKind)> {
fn deref_assign_or_addr_of<'tcx>(expr: &'tcx Expr<'tcx>) -> Option<(bool, &'tcx Expr<'tcx>)> { fn deref_assign_or_addr_of<'tcx>(
// &mut <expr> expr: &'tcx Expr<'tcx>,
let inner = if let ExprKind::AddrOf(_, Mutability::Mut, expr) = expr.kind { ) -> Option<(&'tcx Expr<'tcx>, PatternKind)> {
expr // &(mut) <expr>
let (inner, pat) = if let ExprKind::AddrOf(_, mutbl, expr) = expr.kind {
(expr, PatternKind::Borrow { mutbl })
// <expr> = ... // <expr> = ...
} else if let ExprKind::Assign(expr, _, _) = expr.kind { } else if let ExprKind::Assign(expr, _, _) = expr.kind {
expr (expr, PatternKind::Assign)
// <expr> += ... // <expr> += ...
} else if let ExprKind::AssignOp(_, expr, _) = expr.kind { } else if let ExprKind::AssignOp(_, expr, _) = expr.kind {
expr (expr, PatternKind::Assign)
} else { } else {
return None; return None;
}; };
if let ExprKind::Unary(UnOp::Deref, e) = &inner.kind { // *<inner>
Some((!matches!(expr.kind, ExprKind::AddrOf(..)), e)) let ExprKind::Unary(UnOp::Deref, e) = &inner.kind else {
} else { return None;
None };
} Some((e, pat))
} }
fn ptr_write<'tcx>( fn ptr_write<'tcx>(
cx: &LateContext<'tcx>, cx: &LateContext<'tcx>,
e: &'tcx Expr<'tcx>, e: &'tcx Expr<'tcx>,
) -> Option<(bool, &'tcx Expr<'tcx>)> { ) -> Option<(&'tcx Expr<'tcx>, PatternKind)> {
if let ExprKind::Call(path, [arg_ptr, _arg_val]) = e.kind if let ExprKind::Call(path, [arg_ptr, _arg_val]) = e.kind
&& let ExprKind::Path(ref qpath) = path.kind && let ExprKind::Path(ref qpath) = path.kind
&& let Some(def_id) = cx.qpath_res(qpath, path.hir_id).opt_def_id() && let Some(def_id) = cx.qpath_res(qpath, path.hir_id).opt_def_id()
@ -98,7 +112,7 @@ fn is_operation_we_care_about<'tcx>(
Some(sym::ptr_write | sym::ptr_write_volatile | sym::ptr_write_unaligned) Some(sym::ptr_write | sym::ptr_write_volatile | sym::ptr_write_unaligned)
) )
{ {
Some((true, arg_ptr)) Some((arg_ptr, PatternKind::Assign))
} else { } else {
None None
} }
@ -107,13 +121,10 @@ fn is_operation_we_care_about<'tcx>(
deref_assign_or_addr_of(e).or_else(|| ptr_write(cx, e)) deref_assign_or_addr_of(e).or_else(|| ptr_write(cx, e))
} }
fn is_cast_from_const_to_mut<'tcx>( fn is_cast_from_ref_to_mut_ptr<'tcx>(
cx: &LateContext<'tcx>, cx: &LateContext<'tcx>,
orig_expr: &'tcx Expr<'tcx>, orig_expr: &'tcx Expr<'tcx>,
) -> Option<bool> { ) -> Option<bool> {
let mut need_check_freeze = false;
let mut e = orig_expr;
let end_ty = cx.typeck_results().node_type(orig_expr.hir_id); let end_ty = cx.typeck_results().node_type(orig_expr.hir_id);
// Bail out early if the end type is **not** a mutable pointer. // Bail out early if the end type is **not** a mutable pointer.
@ -121,6 +132,28 @@ fn is_cast_from_const_to_mut<'tcx>(
return None; return None;
} }
let (e, need_check_freeze) = peel_casts(cx, orig_expr);
let start_ty = cx.typeck_results().node_type(e.hir_id);
if let ty::Ref(_, inner_ty, Mutability::Not) = start_ty.kind() {
// If an UnsafeCell method is involved, we need to additionally check the
// inner type for the presence of the Freeze trait (ie does NOT contain
// an UnsafeCell), since in that case we would incorrectly lint on valid casts.
//
// Except on the presence of non concrete skeleton types (ie generics)
// since there is no way to make it safe for arbitrary types.
let inner_ty_has_interior_mutability =
!inner_ty.is_freeze(cx.tcx, cx.param_env) && inner_ty.has_concrete_skeleton();
(!need_check_freeze || !inner_ty_has_interior_mutability)
.then_some(inner_ty_has_interior_mutability)
} else {
None
}
}
fn peel_casts<'tcx>(cx: &LateContext<'tcx>, mut e: &'tcx Expr<'tcx>) -> (&'tcx Expr<'tcx>, bool) {
let mut gone_trough_unsafe_cell_raw_get = false;
loop { loop {
e = e.peel_blocks(); e = e.peel_blocks();
// <expr> as ... // <expr> as ...
@ -145,27 +178,18 @@ fn is_cast_from_const_to_mut<'tcx>(
) )
{ {
if cx.tcx.is_diagnostic_item(sym::unsafe_cell_raw_get, def_id) { if cx.tcx.is_diagnostic_item(sym::unsafe_cell_raw_get, def_id) {
need_check_freeze = true; gone_trough_unsafe_cell_raw_get = true;
} }
arg arg
} else { } else {
break; let init = cx.expr_or_init(e);
if init.hir_id != e.hir_id {
init
} else {
break;
}
}; };
} }
let start_ty = cx.typeck_results().node_type(e.hir_id); (e, gone_trough_unsafe_cell_raw_get)
if let ty::Ref(_, inner_ty, Mutability::Not) = start_ty.kind() {
// If an UnsafeCell method is involved we need to additionally check the
// inner type for the presence of the Freeze trait (ie does NOT contain
// an UnsafeCell), since in that case we would incorrectly lint on valid casts.
//
// We also consider non concrete skeleton types (ie generics)
// to be an issue since there is no way to make it safe for abitrary types.
let inner_ty_has_interior_mutability =
!inner_ty.is_freeze(cx.tcx, cx.param_env) && inner_ty.has_concrete_skeleton();
(!need_check_freeze || !inner_ty_has_interior_mutability)
.then_some(inner_ty_has_interior_mutability)
} else {
None
}
} }

View file

@ -113,6 +113,13 @@ unsafe fn assign_to_ref() {
*((&std::cell::UnsafeCell::new(0)) as *const _ as *mut i32) = 5; *((&std::cell::UnsafeCell::new(0)) as *const _ as *mut i32) = 5;
//~^ ERROR assigning to `&T` is undefined behavior //~^ ERROR assigning to `&T` is undefined behavior
let value = num as *const i32 as *mut i32;
*value = 1;
//~^ ERROR assigning to `&T` is undefined behavior
let value = num as *const i32;
let value = value as *mut i32;
*value = 1;
//~^ ERROR assigning to `&T` is undefined behavior
let value = num as *const i32 as *mut i32; let value = num as *const i32 as *mut i32;
*value = 1; *value = 1;
//~^ ERROR assigning to `&T` is undefined behavior //~^ ERROR assigning to `&T` is undefined behavior

View file

@ -286,7 +286,27 @@ LL | *value = 1;
= note: for more information, visit <https://doc.rust-lang.org/book/ch15-05-interior-mutability.html> = note: for more information, visit <https://doc.rust-lang.org/book/ch15-05-interior-mutability.html>
error: assigning to `&T` is undefined behavior, consider using an `UnsafeCell` error: assigning to `&T` is undefined behavior, consider using an `UnsafeCell`
--> $DIR/reference_casting.rs:120:5 --> $DIR/reference_casting.rs:121:5
|
LL | let value = value as *mut i32;
| ----------------- casting happend here
LL | *value = 1;
| ^^^^^^^^^^
|
= note: for more information, visit <https://doc.rust-lang.org/book/ch15-05-interior-mutability.html>
error: assigning to `&T` is undefined behavior, consider using an `UnsafeCell`
--> $DIR/reference_casting.rs:124:5
|
LL | let value = num as *const i32 as *mut i32;
| ----------------------------- casting happend here
LL | *value = 1;
| ^^^^^^^^^^
|
= note: for more information, visit <https://doc.rust-lang.org/book/ch15-05-interior-mutability.html>
error: assigning to `&T` is undefined behavior, consider using an `UnsafeCell`
--> $DIR/reference_casting.rs:127:5
| |
LL | let value = num as *const i32 as *mut i32; LL | let value = num as *const i32 as *mut i32;
| ----------------------------- casting happend here | ----------------------------- casting happend here
@ -297,7 +317,7 @@ LL | *value_rebind = 1;
= note: for more information, visit <https://doc.rust-lang.org/book/ch15-05-interior-mutability.html> = note: for more information, visit <https://doc.rust-lang.org/book/ch15-05-interior-mutability.html>
error: assigning to `&T` is undefined behavior, consider using an `UnsafeCell` error: assigning to `&T` is undefined behavior, consider using an `UnsafeCell`
--> $DIR/reference_casting.rs:122:5 --> $DIR/reference_casting.rs:129:5
| |
LL | *(num as *const i32).cast::<i32>().cast_mut() = 2; LL | *(num as *const i32).cast::<i32>().cast_mut() = 2;
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
@ -305,7 +325,7 @@ LL | *(num as *const i32).cast::<i32>().cast_mut() = 2;
= note: for more information, visit <https://doc.rust-lang.org/book/ch15-05-interior-mutability.html> = note: for more information, visit <https://doc.rust-lang.org/book/ch15-05-interior-mutability.html>
error: assigning to `&T` is undefined behavior, consider using an `UnsafeCell` error: assigning to `&T` is undefined behavior, consider using an `UnsafeCell`
--> $DIR/reference_casting.rs:124:5 --> $DIR/reference_casting.rs:131:5
| |
LL | *(num as *const _ as usize as *mut i32) = 2; LL | *(num as *const _ as usize as *mut i32) = 2;
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
@ -313,7 +333,7 @@ LL | *(num as *const _ as usize as *mut i32) = 2;
= note: for more information, visit <https://doc.rust-lang.org/book/ch15-05-interior-mutability.html> = note: for more information, visit <https://doc.rust-lang.org/book/ch15-05-interior-mutability.html>
error: assigning to `&T` is undefined behavior, consider using an `UnsafeCell` error: assigning to `&T` is undefined behavior, consider using an `UnsafeCell`
--> $DIR/reference_casting.rs:126:5 --> $DIR/reference_casting.rs:133:5
| |
LL | let value = num as *const i32 as *mut i32; LL | let value = num as *const i32 as *mut i32;
| ----------------------------- casting happend here | ----------------------------- casting happend here
@ -324,7 +344,7 @@ LL | std::ptr::write(value, 2);
= note: for more information, visit <https://doc.rust-lang.org/book/ch15-05-interior-mutability.html> = note: for more information, visit <https://doc.rust-lang.org/book/ch15-05-interior-mutability.html>
error: assigning to `&T` is undefined behavior, consider using an `UnsafeCell` error: assigning to `&T` is undefined behavior, consider using an `UnsafeCell`
--> $DIR/reference_casting.rs:128:5 --> $DIR/reference_casting.rs:135:5
| |
LL | let value = num as *const i32 as *mut i32; LL | let value = num as *const i32 as *mut i32;
| ----------------------------- casting happend here | ----------------------------- casting happend here
@ -335,7 +355,7 @@ LL | std::ptr::write_unaligned(value, 2);
= note: for more information, visit <https://doc.rust-lang.org/book/ch15-05-interior-mutability.html> = note: for more information, visit <https://doc.rust-lang.org/book/ch15-05-interior-mutability.html>
error: assigning to `&T` is undefined behavior, consider using an `UnsafeCell` error: assigning to `&T` is undefined behavior, consider using an `UnsafeCell`
--> $DIR/reference_casting.rs:130:5 --> $DIR/reference_casting.rs:137:5
| |
LL | let value = num as *const i32 as *mut i32; LL | let value = num as *const i32 as *mut i32;
| ----------------------------- casting happend here | ----------------------------- casting happend here
@ -346,12 +366,12 @@ LL | std::ptr::write_volatile(value, 2);
= note: for more information, visit <https://doc.rust-lang.org/book/ch15-05-interior-mutability.html> = note: for more information, visit <https://doc.rust-lang.org/book/ch15-05-interior-mutability.html>
error: assigning to `&T` is undefined behavior, consider using an `UnsafeCell` error: assigning to `&T` is undefined behavior, consider using an `UnsafeCell`
--> $DIR/reference_casting.rs:134:9 --> $DIR/reference_casting.rs:141:9
| |
LL | *(this as *const _ as *mut _) = a; LL | *(this as *const _ as *mut _) = a;
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
| |
= note: for more information, visit <https://doc.rust-lang.org/book/ch15-05-interior-mutability.html> = note: for more information, visit <https://doc.rust-lang.org/book/ch15-05-interior-mutability.html>
error: aborting due to 40 previous errors error: aborting due to 42 previous errors