rust/tests/ui/precondition-checks/read_volatile.rs
Matthias Krüger 6d7d366fd3
Rollup merge of #141260 - LuigiPiucco:volatile-null, r=RalfJung
Allow volatile access to non-Rust memory, including address 0

This PR relaxes the `ub_check` in the `read_volatile`/`write_volatile` pointer operations to allow passing null. This is needed to support processors which hard-code peripheral registers on address 0, like the AVR chip ATtiny1626. LLVM understands this as valid and handles it correctly, as tested in my [PR to add a note about it](6387c82255 (diff-81bbb96298c32fa901beb82ab3b97add27a410c01d577c1f8c01000ed2055826)) (rustc generates the same LLVM IR as expected there when this PR is applied, and consequently the same AVR assembly).

Follow-up and implementation of the discussions in:
- https://internals.rust-lang.org/t/pre-rfc-conditionally-supported-volatile-access-to-address-0/12881/7
- https://github.com/Rahix/avr-device/pull/185;
- [#t-lang > Adding the possibility of volatile access to address 0](https://rust-lang.zulipchat.com/#narrow/channel/213817-t-lang/topic/Adding.20the.20possibility.20of.20volatile.20access.20to.20address.200/with/513303502)
- https://discourse.llvm.org/t/rfc-volatile-access-to-non-dereferenceable-memory-may-be-well-defined/86303

r? ````@RalfJung````

Also fixes https://github.com/rust-lang/unsafe-code-guidelines/issues/29 (about as good as it'll get, null will likely never be a "normal" address in Rust)
2025-07-20 08:56:05 +02:00

16 lines
365 B
Rust

//@ run-crash
//@ compile-flags: -Copt-level=3 -Cdebug-assertions=no -Zub-checks=yes
//@ error-pattern: unsafe precondition(s) violated: ptr::read_volatile requires
//@ revisions: misaligned
use std::ptr;
fn main() {
let src = [0u16; 2];
let src = src.as_ptr();
unsafe {
#[cfg(misaligned)]
ptr::read_volatile(src.byte_add(1));
}
}