about summary refs log tree commit diff
diff options
context:
space:
mode:
authorMatthias Krüger <matthias.krueger@famsik.de>2024-05-08 17:03:09 +0200
committerGitHub <noreply@github.com>2024-05-08 17:03:09 +0200
commit9fce3dc685f66ccaa9d3b25c7ca9983c60d7b263 (patch)
tree387ea725d0ec83527eed84b4d304448e6f007acb
parente997508ecb3484a2ee1a62c89ce03353bc237e1d (diff)
parentcd6a0c8c77575056f95d79ae1f5c460794e1388f (diff)
downloadrust-9fce3dc685f66ccaa9d3b25c7ca9983c60d7b263.tar.gz
rust-9fce3dc685f66ccaa9d3b25c7ca9983c60d7b263.zip
Rollup merge of #124761 - Urgau:ref-casting_bigger_slice_index, r=jieyouxu
Fix insufficient logic when searching for the underlying allocation

This PR fixes the logic inside the `invalid_reference_casting` lint, when trying to lint on bigger memory layout casts.

More specifically when looking for the "underlying allocation" we were wrongly assuming that when we got `&mut slice[index]` that `slice[index]` was the allocation, but it's not.

Fixes https://github.com/rust-lang/rust/issues/124685
-rw-r--r--compiler/rustc_lint/src/reference_casting.rs7
-rw-r--r--tests/ui/lint/reference_casting.rs8
2 files changed, 15 insertions, 0 deletions
diff --git a/compiler/rustc_lint/src/reference_casting.rs b/compiler/rustc_lint/src/reference_casting.rs
index 9fed91f7262..63d55a73a98 100644
--- a/compiler/rustc_lint/src/reference_casting.rs
+++ b/compiler/rustc_lint/src/reference_casting.rs
@@ -199,6 +199,13 @@ fn is_cast_to_bigger_memory_layout<'tcx>(
     let e_alloc = cx.expr_or_init(e);
     let e_alloc =
         if let ExprKind::AddrOf(_, _, inner_expr) = e_alloc.kind { inner_expr } else { e_alloc };
+
+    // if the current expr looks like this `&mut expr[index]` then just looking
+    // at `expr[index]` won't give us the underlying allocation, so we just skip it
+    if let ExprKind::Index(..) = e_alloc.kind {
+        return None;
+    }
+
     let alloc_ty = cx.typeck_results().node_type(e_alloc.hir_id);
 
     // if we do not find it we bail out, as this may not be UB
diff --git a/tests/ui/lint/reference_casting.rs b/tests/ui/lint/reference_casting.rs
index d6897ab7b14..3d0c36ca118 100644
--- a/tests/ui/lint/reference_casting.rs
+++ b/tests/ui/lint/reference_casting.rs
@@ -247,6 +247,14 @@ unsafe fn bigger_layout() {
     unsafe fn from_ref(this: &i32) -> &i64 {
         &*(this as *const i32 as *const i64)
     }
+
+    // https://github.com/rust-lang/rust/issues/124685
+    unsafe fn slice_index(array: &mut [u8], offset: usize) {
+        let a1 = &mut array[offset];
+        let a2 = a1 as *mut u8;
+        let a3 = a2 as *mut u64;
+        unsafe { *a3 = 3 };
+    }
 }
 
 const RAW_PTR: *mut u8 = 1 as *mut u8;