rust/tests/ui/static/raw-ref-extern-static.rs
Jubilee Young 3fdd8d5ef3 compiler: treat &raw (const|mut) UNSAFE_STATIC implied deref as safe
The implied deref to statics introduced by HIR->THIR lowering is only
used to create place expressions, it lacks unsafe semantics.
It is also confusing, as there is no visible `*ident` in the source.
For both classes of "unsafe static" (extern static and static mut)
allow this operation.

We lack a clear story around `thread_local! { static mut }`, which
is actually its own category of item that reuses the static syntax but
has its own rules. It's possible they should be similarly included, but
in the absence of a good reason one way or another, we do not bless it.
2024-07-22 14:54:36 -07:00

27 lines
980 B
Rust

//@ check-pass
#![feature(raw_ref_op)]
use std::ptr;
// see https://github.com/rust-lang/rust/issues/125833
// notionally, taking the address of an extern static is a safe operation,
// as we only point at it instead of generating a true reference to it
// it may potentially induce linker errors, but the safety of that is not about taking addresses!
// any safety obligation of the extern static's correctness in declaration is on the extern itself,
// see RFC 3484 for more on that: https://rust-lang.github.io/rfcs/3484-unsafe-extern-blocks.html
extern "C" {
static THERE: u8;
static mut SOMEWHERE: u8;
}
fn main() {
let ptr2there = ptr::addr_of!(THERE);
let ptr2somewhere = ptr::addr_of!(SOMEWHERE);
let ptr2somewhere = ptr::addr_of_mut!(SOMEWHERE);
// testing both addr_of and the expression it directly expands to
let raw2there = &raw const THERE;
let raw2somewhere = &raw const SOMEWHERE;
let raw2somewhere = &raw mut SOMEWHERE;
}