Skip to content

Commit 11f090b

Browse files
authored
Unrolled build for rust-lang#118983
Rollup merge of rust-lang#118983 - Urgau:invalid_ref_casting-bigger-layout, r=oli-obk Warn on references casting to bigger memory layout This PR extends the [`invalid_reference_casting`](https://doc.rust-lang.org/rustc/lints/listing/deny-by-default.html#invalid-reference-casting) lint (*deny-by-default*) which currently lint on `&T -> &mut T` casting to also lint on `&(mut) A -> &(mut) B` where `size_of::<B>() > size_of::<A>()` (bigger memory layout requirement). The goal is to detect such cases: ```rust let u8_ref: &u8 = &0u8; let u64_ref: &u64 = unsafe { &*(u8_ref as *const u8 as *const u64) }; //~^ ERROR casting references to a bigger memory layout is undefined behavior let mat3 = Mat3 { a: Vec3(0i32, 0, 0), b: Vec3(0, 0, 0), c: Vec3(0, 0, 0) }; let mat3 = unsafe { &*(&mat3 as *const _ as *const [[i64; 3]; 3]) }; //~^ ERROR casting references to a bigger memory layout is undefined behavior ``` This is added to help people who write unsafe code, especially when people have matrix struct that they cast to simple array of arrays. EDIT: One caveat, due to the [`&Header`](rust-lang/unsafe-code-guidelines#256) uncertainty the lint only fires when it can find the underline allocation. ~~I have manually tested all the new expressions that warn against Miri, and they all report immediate UB.~~ r? ``@est31``
2 parents 74c3f5a + e08c9d1 commit 11f090b

File tree

10 files changed

+379
-30
lines changed

10 files changed

+379
-30
lines changed

compiler/rustc_lint/messages.ftl

+5
Original file line numberDiff line numberDiff line change
@@ -319,6 +319,11 @@ lint_invalid_nan_comparisons_lt_le_gt_ge = incorrect NaN comparison, NaN is not
319319
lint_invalid_reference_casting_assign_to_ref = assigning to `&T` is undefined behavior, consider using an `UnsafeCell`
320320
.label = casting happend here
321321
322+
lint_invalid_reference_casting_bigger_layout = casting references to a bigger memory layout than the backing allocation is undefined behavior, even if the reference is unused
323+
.label = casting happend here
324+
.alloc = backing allocation comes from here
325+
.layout = casting from `{$from_ty}` ({$from_size} bytes) to `{$to_ty}` ({$to_size} bytes)
326+
322327
lint_invalid_reference_casting_borrow_as_mut = casting `&T` to `&mut T` is undefined behavior, even if the reference is unused, consider instead using an `UnsafeCell`
323328
.label = casting happend here
324329

compiler/rustc_lint/src/lints.rs

+13-1
Original file line numberDiff line numberDiff line change
@@ -716,7 +716,7 @@ pub enum InvalidFromUtf8Diag {
716716

717717
// reference_casting.rs
718718
#[derive(LintDiagnostic)]
719-
pub enum InvalidReferenceCastingDiag {
719+
pub enum InvalidReferenceCastingDiag<'tcx> {
720720
#[diag(lint_invalid_reference_casting_borrow_as_mut)]
721721
#[note(lint_invalid_reference_casting_note_book)]
722722
BorrowAsMut {
@@ -733,6 +733,18 @@ pub enum InvalidReferenceCastingDiag {
733733
#[note(lint_invalid_reference_casting_note_ty_has_interior_mutability)]
734734
ty_has_interior_mutability: Option<()>,
735735
},
736+
#[diag(lint_invalid_reference_casting_bigger_layout)]
737+
#[note(lint_layout)]
738+
BiggerLayout {
739+
#[label]
740+
orig_cast: Option<Span>,
741+
#[label(lint_alloc)]
742+
alloc: Span,
743+
from_ty: Ty<'tcx>,
744+
from_size: u64,
745+
to_ty: Ty<'tcx>,
746+
to_size: u64,
747+
},
736748
}
737749

738750
// hidden_unicode_codepoints.rs

compiler/rustc_lint/src/reference_casting.rs

+76-8
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
use rustc_ast::Mutability;
22
use rustc_hir::{Expr, ExprKind, UnOp};
3-
use rustc_middle::ty::{self, TypeAndMut};
3+
use rustc_middle::ty::layout::LayoutOf as _;
4+
use rustc_middle::ty::{self, layout::TyAndLayout, TypeAndMut};
45
use rustc_span::sym;
56

67
use crate::{lints::InvalidReferenceCastingDiag, LateContext, LateLintPass, LintContext};
@@ -38,13 +39,19 @@ declare_lint_pass!(InvalidReferenceCasting => [INVALID_REFERENCE_CASTING]);
3839
impl<'tcx> LateLintPass<'tcx> for InvalidReferenceCasting {
3940
fn check_expr(&mut self, cx: &LateContext<'tcx>, expr: &'tcx Expr<'tcx>) {
4041
if let Some((e, pat)) = borrow_or_assign(cx, expr) {
41-
if matches!(pat, PatternKind::Borrow { mutbl: Mutability::Mut } | PatternKind::Assign) {
42-
let init = cx.expr_or_init(e);
42+
let init = cx.expr_or_init(e);
43+
let orig_cast = if init.span != e.span { Some(init.span) } else { None };
44+
45+
// small cache to avoid recomputing needlesly computing peel_casts of init
46+
let mut peel_casts = {
47+
let mut peel_casts_cache = None;
48+
move || *peel_casts_cache.get_or_insert_with(|| peel_casts(cx, init))
49+
};
4350

44-
let Some(ty_has_interior_mutability) = is_cast_from_ref_to_mut_ptr(cx, init) else {
45-
return;
46-
};
47-
let orig_cast = if init.span != e.span { Some(init.span) } else { None };
51+
if matches!(pat, PatternKind::Borrow { mutbl: Mutability::Mut } | PatternKind::Assign)
52+
&& let Some(ty_has_interior_mutability) =
53+
is_cast_from_ref_to_mut_ptr(cx, init, &mut peel_casts)
54+
{
4855
let ty_has_interior_mutability = ty_has_interior_mutability.then_some(());
4956

5057
cx.emit_span_lint(
@@ -63,6 +70,23 @@ impl<'tcx> LateLintPass<'tcx> for InvalidReferenceCasting {
6370
},
6471
);
6572
}
73+
74+
if let Some((from_ty_layout, to_ty_layout, e_alloc)) =
75+
is_cast_to_bigger_memory_layout(cx, init, &mut peel_casts)
76+
{
77+
cx.emit_span_lint(
78+
INVALID_REFERENCE_CASTING,
79+
expr.span,
80+
InvalidReferenceCastingDiag::BiggerLayout {
81+
orig_cast,
82+
alloc: e_alloc.span,
83+
from_ty: from_ty_layout.ty,
84+
from_size: from_ty_layout.layout.size().bytes(),
85+
to_ty: to_ty_layout.ty,
86+
to_size: to_ty_layout.layout.size().bytes(),
87+
},
88+
);
89+
}
6690
}
6791
}
6892
}
@@ -124,6 +148,7 @@ fn borrow_or_assign<'tcx>(
124148
fn is_cast_from_ref_to_mut_ptr<'tcx>(
125149
cx: &LateContext<'tcx>,
126150
orig_expr: &'tcx Expr<'tcx>,
151+
mut peel_casts: impl FnMut() -> (&'tcx Expr<'tcx>, bool),
127152
) -> Option<bool> {
128153
let end_ty = cx.typeck_results().node_type(orig_expr.hir_id);
129154

@@ -132,7 +157,7 @@ fn is_cast_from_ref_to_mut_ptr<'tcx>(
132157
return None;
133158
}
134159

135-
let (e, need_check_freeze) = peel_casts(cx, orig_expr);
160+
let (e, need_check_freeze) = peel_casts();
136161

137162
let start_ty = cx.typeck_results().node_type(e.hir_id);
138163
if let ty::Ref(_, inner_ty, Mutability::Not) = start_ty.kind() {
@@ -151,6 +176,49 @@ fn is_cast_from_ref_to_mut_ptr<'tcx>(
151176
}
152177
}
153178

179+
fn is_cast_to_bigger_memory_layout<'tcx>(
180+
cx: &LateContext<'tcx>,
181+
orig_expr: &'tcx Expr<'tcx>,
182+
mut peel_casts: impl FnMut() -> (&'tcx Expr<'tcx>, bool),
183+
) -> Option<(TyAndLayout<'tcx>, TyAndLayout<'tcx>, Expr<'tcx>)> {
184+
let end_ty = cx.typeck_results().node_type(orig_expr.hir_id);
185+
186+
let ty::RawPtr(TypeAndMut { ty: inner_end_ty, mutbl: _ }) = end_ty.kind() else {
187+
return None;
188+
};
189+
190+
let (e, _) = peel_casts();
191+
let start_ty = cx.typeck_results().node_type(e.hir_id);
192+
193+
let ty::Ref(_, inner_start_ty, _) = start_ty.kind() else {
194+
return None;
195+
};
196+
197+
// try to find the underlying allocation
198+
let e_alloc = cx.expr_or_init(e);
199+
let e_alloc =
200+
if let ExprKind::AddrOf(_, _, inner_expr) = e_alloc.kind { inner_expr } else { e_alloc };
201+
let alloc_ty = cx.typeck_results().node_type(e_alloc.hir_id);
202+
203+
// if we do not find it we bail out, as this may not be UB
204+
// see https://github.com/rust-lang/unsafe-code-guidelines/issues/256
205+
if alloc_ty.is_any_ptr() {
206+
return None;
207+
}
208+
209+
let from_layout = cx.layout_of(*inner_start_ty).ok()?;
210+
let alloc_layout = cx.layout_of(alloc_ty).ok()?;
211+
let to_layout = cx.layout_of(*inner_end_ty).ok()?;
212+
213+
if to_layout.layout.size() > from_layout.layout.size()
214+
&& to_layout.layout.size() > alloc_layout.layout.size()
215+
{
216+
Some((from_layout, to_layout, *e_alloc))
217+
} else {
218+
None
219+
}
220+
}
221+
154222
fn peel_casts<'tcx>(cx: &LateContext<'tcx>, mut e: &'tcx Expr<'tcx>) -> (&'tcx Expr<'tcx>, bool) {
155223
let mut gone_trough_unsafe_cell_raw_get = false;
156224

src/tools/clippy/tests/ui/transmute_ptr_to_ptr.fixed

+3-3
Original file line numberDiff line numberDiff line change
@@ -35,16 +35,16 @@ fn transmute_ptr_to_ptr() {
3535
// ref-ref transmutes; bad
3636
let _: &f32 = &*(&1u32 as *const u32 as *const f32);
3737
//~^ ERROR: transmute from a reference to a reference
38-
let _: &f64 = &*(&1f32 as *const f32 as *const f64);
38+
let _: &f32 = &*(&1f64 as *const f64 as *const f32);
3939
//~^ ERROR: transmute from a reference to a reference
4040
//:^ this test is here because both f32 and f64 are the same TypeVariant, but they are not
4141
// the same type
4242
let _: &mut f32 = &mut *(&mut 1u32 as *mut u32 as *mut f32);
4343
//~^ ERROR: transmute from a reference to a reference
4444
let _: &GenericParam<f32> = &*(&GenericParam { t: 1u32 } as *const GenericParam<u32> as *const GenericParam<f32>);
4545
//~^ ERROR: transmute from a reference to a reference
46-
let u8_ref: &u8 = &0u8;
47-
let u64_ref: &u64 = unsafe { &*(u8_ref as *const u8 as *const u64) };
46+
let u64_ref: &u64 = &0u64;
47+
let u8_ref: &u8 = unsafe { &*(u64_ref as *const u64 as *const u8) };
4848
//~^ ERROR: transmute from a reference to a reference
4949
}
5050

src/tools/clippy/tests/ui/transmute_ptr_to_ptr.rs

+3-3
Original file line numberDiff line numberDiff line change
@@ -35,16 +35,16 @@ fn transmute_ptr_to_ptr() {
3535
// ref-ref transmutes; bad
3636
let _: &f32 = std::mem::transmute(&1u32);
3737
//~^ ERROR: transmute from a reference to a reference
38-
let _: &f64 = std::mem::transmute(&1f32);
38+
let _: &f32 = std::mem::transmute(&1f64);
3939
//~^ ERROR: transmute from a reference to a reference
4040
//:^ this test is here because both f32 and f64 are the same TypeVariant, but they are not
4141
// the same type
4242
let _: &mut f32 = std::mem::transmute(&mut 1u32);
4343
//~^ ERROR: transmute from a reference to a reference
4444
let _: &GenericParam<f32> = std::mem::transmute(&GenericParam { t: 1u32 });
4545
//~^ ERROR: transmute from a reference to a reference
46-
let u8_ref: &u8 = &0u8;
47-
let u64_ref: &u64 = unsafe { std::mem::transmute(u8_ref) };
46+
let u64_ref: &u64 = &0u64;
47+
let u8_ref: &u8 = unsafe { std::mem::transmute(u64_ref) };
4848
//~^ ERROR: transmute from a reference to a reference
4949
}
5050

src/tools/clippy/tests/ui/transmute_ptr_to_ptr.stderr

+5-5
Original file line numberDiff line numberDiff line change
@@ -22,8 +22,8 @@ LL | let _: &f32 = std::mem::transmute(&1u32);
2222
error: transmute from a reference to a reference
2323
--> $DIR/transmute_ptr_to_ptr.rs:38:23
2424
|
25-
LL | let _: &f64 = std::mem::transmute(&1f32);
26-
| ^^^^^^^^^^^^^^^^^^^^^^^^^^ help: try: `&*(&1f32 as *const f32 as *const f64)`
25+
LL | let _: &f32 = std::mem::transmute(&1f64);
26+
| ^^^^^^^^^^^^^^^^^^^^^^^^^^ help: try: `&*(&1f64 as *const f64 as *const f32)`
2727

2828
error: transmute from a reference to a reference
2929
--> $DIR/transmute_ptr_to_ptr.rs:42:27
@@ -38,10 +38,10 @@ LL | let _: &GenericParam<f32> = std::mem::transmute(&GenericParam { t:
3838
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ help: try: `&*(&GenericParam { t: 1u32 } as *const GenericParam<u32> as *const GenericParam<f32>)`
3939

4040
error: transmute from a reference to a reference
41-
--> $DIR/transmute_ptr_to_ptr.rs:47:38
41+
--> $DIR/transmute_ptr_to_ptr.rs:47:36
4242
|
43-
LL | let u64_ref: &u64 = unsafe { std::mem::transmute(u8_ref) };
44-
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^ help: try: `&*(u8_ref as *const u8 as *const u64)`
43+
LL | let u8_ref: &u8 = unsafe { std::mem::transmute(u64_ref) };
44+
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^^ help: try: `&*(u64_ref as *const u64 as *const u8)`
4545

4646
error: aborting due to 7 previous errors
4747

src/tools/miri/tests/fail/unaligned_pointers/unaligned_ref_addr_of.rs

+2
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,8 @@
11
// This should fail even without Stacked Borrows.
22
//@compile-flags: -Zmiri-disable-stacked-borrows -Cdebug-assertions=no
33

4+
#![allow(invalid_reference_casting)] // for u16 -> u32
5+
46
fn main() {
57
// Try many times as this might work by chance.
68
for _ in 0..20 {

tests/ui/cast/cast-rfc0401.rs

+6-6
Original file line numberDiff line numberDiff line change
@@ -81,14 +81,14 @@ fn main()
8181
assert_eq!(u as *const u16, p as *const u16);
8282

8383
// ptr-ptr-cast (Length vtables)
84-
let mut l : [u8; 2] = [0,1];
85-
let w: *mut [u16; 2] = &mut l as *mut [u8; 2] as *mut _;
86-
let w: *mut [u16] = unsafe {&mut *w};
87-
let w_u8 : *const [u8] = w as *const [u8];
88-
assert_eq!(unsafe{&*w_u8}, &l);
84+
let mut l : [u16; 2] = [0,1];
85+
let w: *mut [u8; 2] = &mut l as *mut [u16; 2] as *mut _;
86+
let w: *mut [u8] = unsafe {&mut *w};
87+
let w_u16 : *const [u16] = w as *const [u16];
88+
assert_eq!(unsafe{&*w_u16}, &l);
8989

9090
let s: *mut str = w as *mut str;
91-
let l_via_str = unsafe{&*(s as *const [u8])};
91+
let l_via_str = unsafe{&*(s as *const [u16])};
9292
assert_eq!(&l, l_via_str);
9393

9494
// ptr-ptr-cast (Length vtables, check length is preserved)

tests/ui/lint/reference_casting.rs

+104-1
Original file line numberDiff line numberDiff line change
@@ -30,7 +30,7 @@ unsafe fn ref_to_mut() {
3030
//~^ ERROR casting `&T` to `&mut T` is undefined behavior
3131
let _num = &mut *(num as *const i32).cast::<i32>().cast_mut().cast_const().cast_mut();
3232
//~^ ERROR casting `&T` to `&mut T` is undefined behavior
33-
let _num = &mut *(std::ptr::from_ref(static_u8()) as *mut i32);
33+
let _num = &mut *(std::ptr::from_ref(static_u8()) as *mut i8);
3434
//~^ ERROR casting `&T` to `&mut T` is undefined behavior
3535
let _num = &mut *std::mem::transmute::<_, *mut i32>(num);
3636
//~^ ERROR casting `&T` to `&mut T` is undefined behavior
@@ -141,6 +141,109 @@ unsafe fn assign_to_ref() {
141141
}
142142
}
143143

144+
#[repr(align(16))]
145+
struct I64(i64);
146+
147+
#[repr(C)]
148+
struct Mat3<T> {
149+
a: Vec3<T>,
150+
b: Vec3<T>,
151+
c: Vec3<T>,
152+
}
153+
154+
#[repr(C)]
155+
struct Vec3<T>(T, T, T);
156+
157+
unsafe fn bigger_layout() {
158+
{
159+
let num = &mut 3i32;
160+
161+
let _num = &*(num as *const i32 as *const i64);
162+
//~^ ERROR casting references to a bigger memory layout
163+
let _num = &mut *(num as *mut i32 as *mut i64);
164+
//~^ ERROR casting references to a bigger memory layout
165+
let _num = &mut *(num as *mut i32 as *mut I64);
166+
//~^ ERROR casting references to a bigger memory layout
167+
std::ptr::write(num as *mut i32 as *mut i64, 2);
168+
//~^ ERROR casting references to a bigger memory layout
169+
170+
let _num = &mut *(num as *mut i32);
171+
}
172+
173+
{
174+
let num = &mut [0i32; 3];
175+
176+
let _num = &mut *(num as *mut _ as *mut [i64; 2]);
177+
//~^ ERROR casting references to a bigger memory layout
178+
std::ptr::write_unaligned(num as *mut _ as *mut [i32; 4], [0, 0, 1, 1]);
179+
//~^ ERROR casting references to a bigger memory layout
180+
181+
let _num = &mut *(num as *mut _ as *mut [u32; 3]);
182+
let _num = &mut *(num as *mut _ as *mut [u32; 2]);
183+
}
184+
185+
{
186+
let num = &mut [0i32; 3] as &mut [i32];
187+
188+
let _num = &mut *(num as *mut _ as *mut i128);
189+
//~^ ERROR casting references to a bigger memory layout
190+
let _num = &mut *(num as *mut _ as *mut [i64; 4]);
191+
//~^ ERROR casting references to a bigger memory layout
192+
193+
let _num = &mut *(num as *mut _ as *mut [u32]);
194+
let _num = &mut *(num as *mut _ as *mut [i16]);
195+
}
196+
197+
{
198+
let mat3 = Mat3 { a: Vec3(0i32, 0, 0), b: Vec3(0, 0, 0), c: Vec3(0, 0, 0) };
199+
200+
let _num = &mut *(&mat3 as *const _ as *mut [[i64; 3]; 3]);
201+
//~^ ERROR casting `&T` to `&mut T`
202+
//~^^ ERROR casting references to a bigger memory layout
203+
let _num = &*(&mat3 as *const _ as *mut [[i64; 3]; 3]);
204+
//~^ ERROR casting references to a bigger memory layout
205+
206+
let _num = &*(&mat3 as *const _ as *mut [[i32; 3]; 3]);
207+
}
208+
209+
{
210+
let mut l: [u8; 2] = [0,1];
211+
let w: *mut [u16; 2] = &mut l as *mut [u8; 2] as *mut _;
212+
let w: *mut [u16] = unsafe {&mut *w};
213+
//~^ ERROR casting references to a bigger memory layout
214+
}
215+
216+
{
217+
fn foo() -> [i32; 1] { todo!() }
218+
219+
let num = foo();
220+
let _num = &*(&num as *const i32 as *const i64);
221+
//~^ ERROR casting references to a bigger memory layout
222+
let _num = &*(&foo() as *const i32 as *const i64);
223+
//~^ ERROR casting references to a bigger memory layout
224+
}
225+
226+
{
227+
fn bar(_a: &[i32; 2]) -> &[i32; 1] { todo!() }
228+
229+
let num = bar(&[0, 0]);
230+
let _num = &*(num as *const i32 as *const i64);
231+
let _num = &*(bar(&[0, 0]) as *const i32 as *const i64);
232+
}
233+
234+
{
235+
fn foi<T>() -> T { todo!() }
236+
237+
let num = foi::<i32>();
238+
let _num = &*(&num as *const i32 as *const i64);
239+
//~^ ERROR casting references to a bigger memory layout
240+
}
241+
242+
unsafe fn from_ref(this: &i32) -> &i64 {
243+
&*(this as *const i32 as *const i64)
244+
}
245+
}
246+
144247
const RAW_PTR: *mut u8 = 1 as *mut u8;
145248
unsafe fn no_warn() {
146249
let num = &3i32;

0 commit comments

Comments
 (0)