mirror of
https://github.com/rust-lang/rust.git
synced 2025-10-02 10:18:25 +00:00

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)
16 lines
385 B
Rust
16 lines
385 B
Rust
//@ run-crash
|
|
//@ compile-flags: -Copt-level=3 -Cdebug-assertions=no -Zub-checks=yes
|
|
//@ error-pattern: unsafe precondition(s) violated: ptr::write_volatile requires
|
|
//@ revisions: misaligned
|
|
|
|
use std::ptr;
|
|
|
|
fn main() {
|
|
let mut dst = [0u16; 2];
|
|
let mut dst = dst.as_mut_ptr();
|
|
unsafe {
|
|
#[cfg(misaligned)]
|
|
ptr::write_volatile(dst.byte_add(1), 1u16);
|
|
}
|
|
}
|