Skip to content

Commit a6498ec

Browse files
committed
Lint on reference casting to bigger layout
1 parent 4d1bd0d commit a6498ec

File tree

6 files changed

+351
-14
lines changed

6 files changed

+351
-14
lines changed

compiler/rustc_lint/messages.ftl

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -316,6 +316,11 @@ lint_invalid_nan_comparisons_lt_le_gt_ge = incorrect NaN comparison, NaN is not
316316
lint_invalid_reference_casting_assign_to_ref = assigning to `&T` is undefined behavior, consider using an `UnsafeCell`
317317
.label = casting happend here
318318
319+
lint_invalid_reference_casting_bigger_layout = casting references to a bigger memory layout is undefined behavior, even if the reference is unused
320+
.label = casting happend here
321+
.alloc = baking allocation comes from here
322+
.layout = casting from `{$from_ty}` ({$from_size} bytes) to `{$to_ty}` ({$to_size} bytes)
323+
319324
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`
320325
.label = casting happend here
321326

compiler/rustc_lint/src/lints.rs

Lines changed: 13 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -752,7 +752,7 @@ pub enum InvalidFromUtf8Diag {
752752

753753
// reference_casting.rs
754754
#[derive(LintDiagnostic)]
755-
pub enum InvalidReferenceCastingDiag {
755+
pub enum InvalidReferenceCastingDiag<'tcx> {
756756
#[diag(lint_invalid_reference_casting_borrow_as_mut)]
757757
#[note(lint_invalid_reference_casting_note_book)]
758758
BorrowAsMut {
@@ -769,6 +769,18 @@ pub enum InvalidReferenceCastingDiag {
769769
#[note(lint_invalid_reference_casting_note_ty_has_interior_mutability)]
770770
ty_has_interior_mutability: Option<()>,
771771
},
772+
#[diag(lint_invalid_reference_casting_bigger_layout)]
773+
#[note(lint_layout)]
774+
BiggerLayout {
775+
#[label]
776+
orig_cast: Option<Span>,
777+
#[label(lint_alloc)]
778+
alloc: Span,
779+
from_ty: Ty<'tcx>,
780+
from_size: u64,
781+
to_ty: Ty<'tcx>,
782+
to_size: u64,
783+
},
772784
}
773785

774786
// hidden_unicode_codepoints.rs

compiler/rustc_lint/src/reference_casting.rs

Lines changed: 65 additions & 7 deletions
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,12 @@ 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 };
4344

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 };
45+
if matches!(pat, PatternKind::Borrow { mutbl: Mutability::Mut } | PatternKind::Assign)
46+
&& let Some(ty_has_interior_mutability) = is_cast_from_ref_to_mut_ptr(cx, init)
47+
{
4848
let ty_has_interior_mutability = ty_has_interior_mutability.then_some(());
4949

5050
cx.emit_spanned_lint(
@@ -63,6 +63,23 @@ impl<'tcx> LateLintPass<'tcx> for InvalidReferenceCasting {
6363
},
6464
);
6565
}
66+
67+
if let Some((from_ty_layout, to_ty_layout, e_alloc)) =
68+
is_cast_to_bigger_memory_layout(cx, init)
69+
{
70+
cx.emit_spanned_lint(
71+
INVALID_REFERENCE_CASTING,
72+
expr.span,
73+
InvalidReferenceCastingDiag::BiggerLayout {
74+
orig_cast,
75+
alloc: e_alloc.span,
76+
from_ty: from_ty_layout.ty,
77+
from_size: from_ty_layout.layout.size().bytes(),
78+
to_ty: to_ty_layout.ty,
79+
to_size: to_ty_layout.layout.size().bytes(),
80+
},
81+
);
82+
}
6683
}
6784
}
6885
}
@@ -151,6 +168,47 @@ fn is_cast_from_ref_to_mut_ptr<'tcx>(
151168
}
152169
}
153170

171+
fn is_cast_to_bigger_memory_layout<'tcx>(
172+
cx: &LateContext<'tcx>,
173+
orig_expr: &'tcx Expr<'tcx>,
174+
) -> Option<(TyAndLayout<'tcx>, TyAndLayout<'tcx>, Expr<'tcx>)> {
175+
let end_ty = cx.typeck_results().node_type(orig_expr.hir_id);
176+
177+
let ty::RawPtr(TypeAndMut { ty: inner_end_ty, mutbl: _ }) = end_ty.kind() else {
178+
return None;
179+
};
180+
181+
let (e, _) = peel_casts(cx, orig_expr);
182+
let start_ty = cx.typeck_results().node_type(e.hir_id);
183+
184+
let ty::Ref(_, inner_start_ty, _) = start_ty.kind() else {
185+
return None;
186+
};
187+
188+
// try to find the underline allocation
189+
let e_alloc = cx.expr_or_init(e);
190+
let e_alloc =
191+
if let ExprKind::AddrOf(_, _, inner_expr) = e_alloc.kind { inner_expr } else { e_alloc };
192+
193+
// if we do not find it we bail out, as this may not be UB
194+
// see https://github.com/rust-lang/unsafe-code-guidelines/issues/256
195+
if cx.typeck_results().node_type(e_alloc.hir_id).is_any_ptr() {
196+
return None;
197+
}
198+
199+
let (Ok(from_layout), Ok(to_layout)) =
200+
(cx.layout_of(*inner_start_ty), cx.layout_of(*inner_end_ty))
201+
else {
202+
return None;
203+
};
204+
205+
if to_layout.layout.size() > from_layout.layout.size() {
206+
Some((from_layout, to_layout, *e_alloc))
207+
} else {
208+
None
209+
}
210+
}
211+
154212
fn peel_casts<'tcx>(cx: &LateContext<'tcx>, mut e: &'tcx Expr<'tcx>) -> (&'tcx Expr<'tcx>, bool) {
155213
let mut gone_trough_unsafe_cell_raw_get = false;
156214

tests/ui/cast/cast-rfc0401.rs

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -82,8 +82,8 @@ fn main()
8282

8383
// ptr-ptr-cast (Length vtables)
8484
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};
85+
let w: *mut [i8; 2] = &mut l as *mut [u8; 2] as *mut _;
86+
let w: *mut [i8] = unsafe {&mut *w};
8787
let w_u8 : *const [u8] = w as *const [u8];
8888
assert_eq!(unsafe{&*w_u8}, &l);
8989

tests/ui/lint/reference_casting.rs

Lines changed: 104 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -32,7 +32,7 @@ unsafe fn ref_to_mut() {
3232
//~^ ERROR casting `&T` to `&mut T` is undefined behavior
3333
let _num = &mut *(num as *const i32).cast::<i32>().cast_mut().cast_const().cast_mut();
3434
//~^ ERROR casting `&T` to `&mut T` is undefined behavior
35-
let _num = &mut *(std::ptr::from_ref(static_u8()) as *mut i32);
35+
let _num = &mut *(std::ptr::from_ref(static_u8()) as *mut i8);
3636
//~^ ERROR casting `&T` to `&mut T` is undefined behavior
3737
let _num = &mut *std::mem::transmute::<_, *mut i32>(num);
3838
//~^ ERROR casting `&T` to `&mut T` is undefined behavior
@@ -143,6 +143,109 @@ unsafe fn assign_to_ref() {
143143
}
144144
}
145145

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

0 commit comments

Comments
 (0)