Only allow immutable statics with #[linkage]

This commit is contained in:
bjorn3 2024-05-12 14:22:12 +00:00
parent b71fa82d78
commit 531dae1cdf
4 changed files with 37 additions and 3 deletions

View File

@ -327,6 +327,18 @@ fn codegen_fn_attrs(tcx: TyCtxt<'_>, did: LocalDefId) -> CodegenFnAttrs {
} else { } else {
codegen_fn_attrs.linkage = linkage; 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 => { sym::link_section => {

View File

@ -5,9 +5,6 @@
#![feature(linkage)] #![feature(linkage)]
#[linkage = "common"]
pub static mut TEST1: u32 = 0u32;
#[linkage = "external"] #[linkage = "external"]
pub static TEST2: bool = true; pub static TEST2: bool = true;

View File

@ -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);
}
}

View File

@ -0,0 +1,10 @@
error: mutable statics are not allowed with `#[linkage]`
--> $DIR/linkage-attr-mutable-static.rs:8:9
|
LL | #[linkage = "weak"]
| ^^^^^^^^^^^^^^^^^^^
|
= note: making the static mutable would allow changing which symbol the static references rather than make the target of the symbol mutable
error: aborting due to 1 previous error