Skip to content

Commit

Permalink
Auto merge of #102513 - RalfJung:no-more-unaligned-reference, r=cjgil…
Browse files Browse the repository at this point in the history
…lot,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.
  • Loading branch information
bors committed Jan 31, 2023
2 parents 0ae4e8c + 01f66f5 commit 1c129d9
Show file tree
Hide file tree
Showing 2 changed files with 12 additions and 5 deletions.
13 changes: 10 additions & 3 deletions tests/fail/unaligned_pointers/reference_to_packed.rs
Original file line number Diff line number Diff line change
@@ -1,19 +1,26 @@
// This should fail even without validation/SB
//@compile-flags: -Zmiri-disable-validation -Zmiri-disable-stacked-borrows

#![allow(dead_code, unused_variables, unaligned_references)]
#![allow(dead_code, unused_variables)]

use std::{ptr, mem};

#[repr(packed)]
struct Foo {
x: i32,
y: i32,
}

unsafe fn raw_to_ref<'a, T>(x: *const T) -> &'a T {
mem::transmute(x)
}

fn main() {
// Try many times as this might work by chance.
for _ in 0..20 {
let foo = Foo { x: 42, y: 99 };
let p = &foo.x;
let i = *p; //~ERROR: alignment 4 is required
// There seem to be implicit reborrows, which make the error already appear here
let p: &i32 = unsafe { raw_to_ref(ptr::addr_of!(foo.x)) }; //~ERROR: alignment 4 is required
let i = *p;
}
}
4 changes: 2 additions & 2 deletions tests/fail/unaligned_pointers/reference_to_packed.stderr
Original file line number Diff line number Diff line change
@@ -1,8 +1,8 @@
error: Undefined Behavior: accessing memory with alignment ALIGN, but alignment ALIGN is required
--> $DIR/reference_to_packed.rs:LL:CC
|
LL | let i = *p;
| ^^ accessing memory with alignment ALIGN, but alignment ALIGN is required
LL | let p: &i32 = unsafe { raw_to_ref(ptr::addr_of!(foo.x)) };
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ accessing memory with alignment ALIGN, but alignment ALIGN is required
|
= help: this indicates a bug in the program: it performed an invalid operation, and caused Undefined Behavior
= help: see https://doc.rust-lang.org/nightly/reference/behavior-considered-undefined.html for further information
Expand Down

0 comments on commit 1c129d9

Please sign in to comment.