Skip to content

Creating a raw pointer to an external static requires an unsafe block #74843

Open
@Nemo157

Description

@Nemo157

I tried this code (playground):

#![feature(raw_ref_op)]

extern {
    static FOO: u32;
}

mod foo {
    #[no_mangle]
    static FOO: u32 = 5;
}

fn main() {
    dbg!(core::ptr::addr_of!(FOO));
    dbg!(&raw const FOO);
}

I expected to see this happen: it compile and print the address of FOO twice.

Instead, this happened: compilation failed because accessing FOO requires an unsafe block

error[E0133]: use of extern static is unsafe and requires unsafe function or block
  --> src/main.rs:13:10
   |
13 |     dbg!(core::ptr::addr_of!(FOO));
   |          ^^^^^^^^^^^^^^^^^^^^^^^^ use of extern static
   |
   = note: extern statics are not controlled by the Rust type system: invalid data, aliasing violations or data races will cause undefined behavior
   = note: this error originates in the macro `core::ptr::addr_of` (in Nightly builds, run with -Z macro-backtrace for more info)

error[E0133]: use of extern static is unsafe and requires unsafe function or block
  --> src/main.rs:14:10
   |
14 |     dbg!(&raw const FOO);
   |          ^^^^^^^^^^^^^^ use of extern static
   |
   = note: extern statics are not controlled by the Rust type system: invalid data, aliasing violations or data races will cause undefined behavior

As far as I can tell none of the potential causes of UB can be caused by just creating a raw pointer to the static. This should be a safe operation, and only when attempting to use the pointer in the future should you need to prove validity of it.

Metadata

Metadata

Assignees

No one assigned

    Labels

    A-FFIArea: Foreign function interface (FFI)C-bugCategory: This is a bug.F-raw_ref_op`#![feature(raw_ref_op)]`T-compilerRelevant to the compiler team, which will review and decide on the PR/issue.

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions