diff --git a/compiler/rustc_codegen_ssa/src/codegen_attrs.rs b/compiler/rustc_codegen_ssa/src/codegen_attrs.rs index c28b0d644e675..b479b0376684b 100644 --- a/compiler/rustc_codegen_ssa/src/codegen_attrs.rs +++ b/compiler/rustc_codegen_ssa/src/codegen_attrs.rs @@ -327,6 +327,18 @@ fn codegen_fn_attrs(tcx: TyCtxt<'_>, did: LocalDefId) -> CodegenFnAttrs { } else { codegen_fn_attrs.linkage = linkage; } + if tcx.is_mutable_static(did.into()) { + let mut diag = tcx.dcx().struct_span_err( + attr.span, + "mutable statics are not allowed with `#[linkage]`", + ); + diag.note( + "making the static mutable would allow changing which symbol the \ + static references rather than make the target of the symbol \ + mutable", + ); + diag.emit(); + } } } sym::link_section => { diff --git a/tests/ui/issues/issue-33992.rs b/tests/ui/issues/issue-33992.rs index 177ff234bb291..495751436e127 100644 --- a/tests/ui/issues/issue-33992.rs +++ b/tests/ui/issues/issue-33992.rs @@ -5,9 +5,6 @@ #![feature(linkage)] -#[linkage = "common"] -pub static mut TEST1: u32 = 0u32; - #[linkage = "external"] pub static TEST2: bool = true; diff --git a/tests/ui/linkage-attr/linkage-attr-mutable-static.rs b/tests/ui/linkage-attr/linkage-attr-mutable-static.rs new file mode 100644 index 0000000000000..41df88b9de7c8 --- /dev/null +++ b/tests/ui/linkage-attr/linkage-attr-mutable-static.rs @@ -0,0 +1,15 @@ +//! The symbols are resolved by the linker. It doesn't make sense to change +//! them at runtime, so deny mutable statics with #[linkage]. + +#![feature(linkage)] + +fn main() { + extern "C" { + #[linkage = "weak"] //~ ERROR mutable statics are not allowed with #[linkage] + static mut ABC: *const u8; + } + + unsafe { + assert_eq!(ABC as usize, 0); + } +} diff --git a/tests/ui/linkage-attr/linkage-attr-mutable-static.stderr b/tests/ui/linkage-attr/linkage-attr-mutable-static.stderr new file mode 100644 index 0000000000000..55b9a6091e848 --- /dev/null +++ b/tests/ui/linkage-attr/linkage-attr-mutable-static.stderr @@ -0,0 +1,8 @@ +error: mutable statics are not allowed with #[linkage] + --> $DIR/linkage-attr-mutable-static.rs:8:9 + | +LL | #[linkage = "weak"] + | ^^^^^^^^^^^^^^^^^^^ + +error: aborting due to 1 previous error +