Skip to content

Writing to a static is somehow allowed while initializing that same staticΒ #142404

Open
@theemathas

Description

@theemathas

I tried this code:

#![allow(dead_code)]

struct Foo {
    x: i32,
    y: (),
}

static S: Foo = Foo {
    x: 0,
    y: unsafe {
        (&raw const S.x).cast_mut().write(1);  // Writing to an immutable static that's still being initialized!
    },
};

fn main() {
    println!("{}", S.x);
}

I expected to see this happen: An error of some sort, or Miri reports UB.

Instead, this happened: The program compiles and outputs 0. Miri does not detect UB.

Note that writing to a static while initializing a different static is not allowed. For example,

static mut S: i32 = 0;

static T: () = unsafe {
    (&raw mut S).write(1);
};

this produces the following error

error[E0080]: could not evaluate static initializer
    --> src/lib.rs:4:5
     |
4    |     (&raw mut S).write(1);
     |     ^^^^^^^^^^^^^^^^^^^^^ modifying a static's initial value from another static's initializer
     |
note: inside `std::ptr::mut_ptr::<impl *mut i32>::write`
    --> /playground/.rustup/toolchains/stable-x86_64-unknown-linux-gnu/lib/rustlib/src/rust/library/core/src/ptr/mut_ptr.rs:1507:18
     |
1507 |         unsafe { write(self, val) }
     |                  ^^^^^^^^^^^^^^^^
note: inside `std::ptr::write::<i32>`
    --> /playground/.rustup/toolchains/stable-x86_64-unknown-linux-gnu/lib/rustlib/src/rust/library/core/src/ptr/mod.rs:1580:9
     |
1580 |         intrinsics::write_via_move(dst, src)
     |         ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ the failure occurred here

For more information about this error, try `rustc --explain E0080`.
error: could not compile `playground` (lib) due to 1 previous error

Meta

Reproducible on the playground with 1.89.0-nightly (2025-06-11 e703dff8fe220b78195c)

@rustbot labels +A-const-eval

Metadata

Metadata

Assignees

No one assigned

    Labels

    A-const-evalArea: Constant evaluation, covers all const contexts (static, const fn, ...)C-bugCategory: This is a bug.I-lang-nominatedNominated for discussion during a lang team meeting.P-lang-drag-2Lang team prioritization drag level 2.https://rust-lang.zulipchat.com/#narrow/channel/410516-t-lang.

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions