Skip to content

Commit 140c165

Browse files
committed
Auto merge of #3600 - xfix:cast-ref-to-mut, r=flip1995
cast_ref_to_mut lint I see this pattern way too often, and it's completely wrong. In fact, due to how common this incorrect pattern is, [the Rustonomicon specifically points this out](https://doc.rust-lang.org/nomicon/transmutes.html). > - Transmuting an & to &mut is UB > - Transmuting an & to &mut is always UB > - No you can't do it > - No you're not special This is my first lint.
2 parents dd94d3b + 27ea638 commit 140c165

File tree

6 files changed

+119
-1
lines changed

6 files changed

+119
-1
lines changed

CHANGELOG.md

+1
Original file line numberDiff line numberDiff line change
@@ -634,6 +634,7 @@ All notable changes to this project will be documented in this file.
634634
[`cast_possible_wrap`]: https://rust-lang.github.io/rust-clippy/master/index.html#cast_possible_wrap
635635
[`cast_precision_loss`]: https://rust-lang.github.io/rust-clippy/master/index.html#cast_precision_loss
636636
[`cast_ptr_alignment`]: https://rust-lang.github.io/rust-clippy/master/index.html#cast_ptr_alignment
637+
[`cast_ref_to_mut`]: https://rust-lang.github.io/rust-clippy/master/index.html#cast_ref_to_mut
637638
[`cast_sign_loss`]: https://rust-lang.github.io/rust-clippy/master/index.html#cast_sign_loss
638639
[`char_lit_as_u8`]: https://rust-lang.github.io/rust-clippy/master/index.html#char_lit_as_u8
639640
[`chars_last_cmp`]: https://rust-lang.github.io/rust-clippy/master/index.html#chars_last_cmp

README.md

+1-1
Original file line numberDiff line numberDiff line change
@@ -7,7 +7,7 @@
77

88
A collection of lints to catch common mistakes and improve your [Rust](https://github.com/rust-lang/rust) code.
99

10-
[There are 290 lints included in this crate!](https://rust-lang.github.io/rust-clippy/master/index.html)
10+
[There are 291 lints included in this crate!](https://rust-lang.github.io/rust-clippy/master/index.html)
1111

1212
We have a bunch of lint categories to allow you to choose how much Clippy is supposed to ~~annoy~~ help you:
1313

clippy_lints/src/lib.rs

+3
Original file line numberDiff line numberDiff line change
@@ -486,6 +486,7 @@ pub fn register_plugins(reg: &mut rustc_plugin::Registry<'_>, conf: &Conf) {
486486
reg.register_late_lint_pass(box ptr_offset_with_cast::Pass);
487487
reg.register_late_lint_pass(box redundant_clone::RedundantClone);
488488
reg.register_late_lint_pass(box slow_vector_initialization::Pass);
489+
reg.register_late_lint_pass(box types::RefToMut);
489490

490491
reg.register_lint_group("clippy::restriction", Some("clippy_restriction"), vec![
491492
arithmetic::FLOAT_ARITHMETIC,
@@ -758,6 +759,7 @@ pub fn register_plugins(reg: &mut rustc_plugin::Registry<'_>, conf: &Conf) {
758759
types::BOX_VEC,
759760
types::CAST_LOSSLESS,
760761
types::CAST_PTR_ALIGNMENT,
762+
types::CAST_REF_TO_MUT,
761763
types::CHAR_LIT_AS_U8,
762764
types::FN_TO_NUMERIC_CAST,
763765
types::FN_TO_NUMERIC_CAST_WITH_TRUNCATION,
@@ -989,6 +991,7 @@ pub fn register_plugins(reg: &mut rustc_plugin::Registry<'_>, conf: &Conf) {
989991
transmute::WRONG_TRANSMUTE,
990992
types::ABSURD_EXTREME_COMPARISONS,
991993
types::CAST_PTR_ALIGNMENT,
994+
types::CAST_REF_TO_MUT,
992995
types::UNIT_CMP,
993996
unicode::ZERO_WIDTH_SPACE,
994997
unused_io_amount::UNUSED_IO_AMOUNT,

clippy_lints/src/types.rs

+61
Original file line numberDiff line numberDiff line change
@@ -2240,3 +2240,64 @@ impl<'a, 'b, 'tcx: 'a + 'b> Visitor<'tcx> for ImplicitHasherConstructorVisitor<'
22402240
NestedVisitorMap::OnlyBodies(&self.cx.tcx.hir())
22412241
}
22422242
}
2243+
2244+
/// **What it does:** Checks for casts of `&T` to `&mut T` anywhere in the code.
2245+
///
2246+
/// **Why is this bad?** It’s basically guaranteed to be undefined behaviour.
2247+
/// `UnsafeCell` is the only way to obtain aliasable data that is considered
2248+
/// mutable.
2249+
///
2250+
/// **Known problems:** None.
2251+
///
2252+
/// **Example:**
2253+
/// ```rust
2254+
/// fn x(r: &i32) {
2255+
/// unsafe {
2256+
/// *(r as *const _ as *mut _) += 1;
2257+
/// }
2258+
/// }
2259+
/// ```
2260+
///
2261+
/// Instead consider using interior mutability types.
2262+
///
2263+
/// ```rust
2264+
/// fn x(r: &UnsafeCell<i32>) {
2265+
/// unsafe {
2266+
/// *r.get() += 1;
2267+
/// }
2268+
/// }
2269+
/// ```
2270+
declare_clippy_lint! {
2271+
pub CAST_REF_TO_MUT,
2272+
correctness,
2273+
"a cast of reference to a mutable pointer"
2274+
}
2275+
2276+
pub struct RefToMut;
2277+
2278+
impl LintPass for RefToMut {
2279+
fn get_lints(&self) -> LintArray {
2280+
lint_array!(CAST_REF_TO_MUT)
2281+
}
2282+
}
2283+
2284+
impl<'a, 'tcx> LateLintPass<'a, 'tcx> for RefToMut {
2285+
fn check_expr(&mut self, cx: &LateContext<'a, 'tcx>, expr: &'tcx Expr) {
2286+
if_chain! {
2287+
if let ExprKind::Unary(UnOp::UnDeref, e) = &expr.node;
2288+
if let ExprKind::Cast(e, t) = &e.node;
2289+
if let TyKind::Ptr(MutTy { mutbl: Mutability::MutMutable, .. }) = t.node;
2290+
if let ExprKind::Cast(e, t) = &e.node;
2291+
if let TyKind::Ptr(MutTy { mutbl: Mutability::MutImmutable, .. }) = t.node;
2292+
if let ty::Ref(..) = cx.tables.node_id_to_type(e.hir_id).sty;
2293+
then {
2294+
span_lint(
2295+
cx,
2296+
CAST_REF_TO_MUT,
2297+
expr.span,
2298+
"casting &T to &mut T may cause undefined behaviour, consider instead using an UnsafeCell",
2299+
);
2300+
}
2301+
}
2302+
}
2303+
}

tests/ui/cast_ref_to_mut.rs

+31
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,31 @@
1+
#![warn(clippy::cast_ref_to_mut)]
2+
#![allow(clippy::no_effect)]
3+
4+
extern "C" {
5+
// NB. Mutability can be easily incorrect in FFI calls, as
6+
// in C, the default are mutable pointers.
7+
fn ffi(c: *mut u8);
8+
fn int_ffi(c: *mut i32);
9+
}
10+
11+
fn main() {
12+
let s = String::from("Hello");
13+
let a = &s;
14+
unsafe {
15+
let num = &3i32;
16+
let mut_num = &mut 3i32;
17+
// Should be warned against
18+
(*(a as *const _ as *mut String)).push_str(" world");
19+
*(a as *const _ as *mut _) = String::from("Replaced");
20+
*(a as *const _ as *mut String) += " world";
21+
// Shouldn't be warned against
22+
println!("{}", *(num as *const _ as *const i16));
23+
println!("{}", *(mut_num as *mut _ as *mut i16));
24+
ffi(a.as_ptr() as *mut _);
25+
int_ffi(num as *const _ as *mut _);
26+
int_ffi(&3 as *const _ as *mut _);
27+
let mut value = 3;
28+
let value: *const i32 = &mut value;
29+
*(value as *const i16 as *mut i16) = 42;
30+
}
31+
}

tests/ui/cast_ref_to_mut.stderr

+22
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,22 @@
1+
error: casting &T to &mut T may cause undefined behaviour, consider instead using an UnsafeCell
2+
--> $DIR/cast_ref_to_mut.rs:18:9
3+
|
4+
LL | (*(a as *const _ as *mut String)).push_str(" world");
5+
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
6+
|
7+
= note: `-D clippy::cast-ref-to-mut` implied by `-D warnings`
8+
9+
error: casting &T to &mut T may cause undefined behaviour, consider instead using an UnsafeCell
10+
--> $DIR/cast_ref_to_mut.rs:19:9
11+
|
12+
LL | *(a as *const _ as *mut _) = String::from("Replaced");
13+
| ^^^^^^^^^^^^^^^^^^^^^^^^^^
14+
15+
error: casting &T to &mut T may cause undefined behaviour, consider instead using an UnsafeCell
16+
--> $DIR/cast_ref_to_mut.rs:20:9
17+
|
18+
LL | *(a as *const _ as *mut String) += " world";
19+
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
20+
21+
error: aborting due to 3 previous errors
22+

0 commit comments

Comments
 (0)