Closed
Description
The following code was tried:
use core::mem::ManuallyDrop;
use core::fmt::Debug;
#[repr(packed)]
struct Unaligned<T: ? Sized>(ManuallyDrop<T>);
fn main(){
let ref local = Unaligned(ManuallyDrop::new([3, 5, 8u64]));
let foo: &Unaligned<dyn Debug> = &*local;
println!("{:?}", &*foo.0);
}
I expected to see this happen: An error (or at least lint) which tells me the reference created in &*foo.0
is unsound. This is correctly issued if no intermediate coercion statement is added.
error[[E0793]](https://doc.rust-lang.org/stable/error_codes/E0793.html): reference to packed field is unaligned
--> src/main.rs:10:24
|
10 | println!("{:?}", &*local.0);
| ^^^^^^^
|
= note: packed structs are only aligned by one byte, and many modern architectures penalize unaligned field accesses
= note: creating a misaligned reference is undefined behavior (even if that reference is never dereferenced)
= help: copy the field contents to a local variable, or replace the reference with a raw pointer and use `read_unaligned`/`write_unaligned` (loads and stores via `*p` must be properly aligned even when using raw pointers)
For more information about this error, try `rustc --explain E0793`.
warning: `playground` (bin "playground") generated 1 warning
Instead, this happened: The code compiles and appears to run.
Miri can diagnose the UB.
error: Undefined Behavior: constructing invalid value: encountered an unaligned reference (required 8 byte alignment but found 4)
--> src/main.rs:10:24
|
10 | println!("{:?}", &*foo.0);
| ^^^^^ constructing invalid value: encountered an unaligned reference (required 8 byte alignment but found 4)
|
= 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
= note: BACKTRACE:
= note: inside `main` at src/main.rs:10:24: 10:29
note: some details are omitted, run with `MIRIFLAGS=-Zmiri-backtrace=full` for a verbose backtrace
Meta
rustc --version --verbose
:
rustc 1.68.0 (2c8cc3432 2023-03-06)
binary: rustc
commit-hash: 2c8cc343237b8f7d5a3c3703e3a87f2eb2c54a74
commit-date: 2023-03-06
host: x86_64-unknown-linux-gnu
release: 1.68.0
LLVM version: 15.0.6
Also affects 1.72, nightly, and prior versions.