Skip to content

Commit 1c129d9

Browse files
committed
Auto merge of #102513 - RalfJung:no-more-unaligned-reference, r=cjgillot,scottmcm
make unaligned_reference a hard error The `unaligned_references` lint has been warn-by-default since Rust 1.53 (rust-lang/rust#82525) and deny-by-default with mention in cargo future-incompat reports since Rust 1.62 (rust-lang/rust#95372). Current nightly will become Rust 1.66, so (unless major surprises show up with crater) I think it is time we make this a hard error, and close this old soundness gap in the language. EDIT: Turns out this will only land for Rust 1.67, so there is another 6 weeks of time here for crates to adjust. Fixes rust-lang/rust#82523.
2 parents 0ae4e8c + 01f66f5 commit 1c129d9

File tree

2 files changed

+12
-5
lines changed

2 files changed

+12
-5
lines changed
Lines changed: 10 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,19 +1,26 @@
11
// This should fail even without validation/SB
22
//@compile-flags: -Zmiri-disable-validation -Zmiri-disable-stacked-borrows
33

4-
#![allow(dead_code, unused_variables, unaligned_references)]
4+
#![allow(dead_code, unused_variables)]
5+
6+
use std::{ptr, mem};
57

68
#[repr(packed)]
79
struct Foo {
810
x: i32,
911
y: i32,
1012
}
1113

14+
unsafe fn raw_to_ref<'a, T>(x: *const T) -> &'a T {
15+
mem::transmute(x)
16+
}
17+
1218
fn main() {
1319
// Try many times as this might work by chance.
1420
for _ in 0..20 {
1521
let foo = Foo { x: 42, y: 99 };
16-
let p = &foo.x;
17-
let i = *p; //~ERROR: alignment 4 is required
22+
// There seem to be implicit reborrows, which make the error already appear here
23+
let p: &i32 = unsafe { raw_to_ref(ptr::addr_of!(foo.x)) }; //~ERROR: alignment 4 is required
24+
let i = *p;
1825
}
1926
}

tests/fail/unaligned_pointers/reference_to_packed.stderr

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,8 @@
11
error: Undefined Behavior: accessing memory with alignment ALIGN, but alignment ALIGN is required
22
--> $DIR/reference_to_packed.rs:LL:CC
33
|
4-
LL | let i = *p;
5-
| ^^ accessing memory with alignment ALIGN, but alignment ALIGN is required
4+
LL | let p: &i32 = unsafe { raw_to_ref(ptr::addr_of!(foo.x)) };
5+
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ accessing memory with alignment ALIGN, but alignment ALIGN is required
66
|
77
= help: this indicates a bug in the program: it performed an invalid operation, and caused Undefined Behavior
88
= help: see https://doc.rust-lang.org/nightly/reference/behavior-considered-undefined.html for further information

0 commit comments

Comments
 (0)