Skip to content

Commit 5860d43

Browse files
Rollup merge of #125046 - bjorn3:no_mutable_static_linkage, r=cjgillot
Only allow immutable statics with #[linkage]
2 parents 866630d + 531dae1 commit 5860d43

File tree

4 files changed

+37
-3
lines changed

4 files changed

+37
-3
lines changed

compiler/rustc_codegen_ssa/src/codegen_attrs.rs

+12
Original file line numberDiff line numberDiff line change
@@ -327,6 +327,18 @@ fn codegen_fn_attrs(tcx: TyCtxt<'_>, did: LocalDefId) -> CodegenFnAttrs {
327327
} else {
328328
codegen_fn_attrs.linkage = linkage;
329329
}
330+
if tcx.is_mutable_static(did.into()) {
331+
let mut diag = tcx.dcx().struct_span_err(
332+
attr.span,
333+
"mutable statics are not allowed with `#[linkage]`",
334+
);
335+
diag.note(
336+
"making the static mutable would allow changing which symbol the \
337+
static references rather than make the target of the symbol \
338+
mutable",
339+
);
340+
diag.emit();
341+
}
330342
}
331343
}
332344
sym::link_section => {

tests/ui/issues/issue-33992.rs

-3
Original file line numberDiff line numberDiff line change
@@ -5,9 +5,6 @@
55

66
#![feature(linkage)]
77

8-
#[linkage = "common"]
9-
pub static mut TEST1: u32 = 0u32;
10-
118
#[linkage = "external"]
129
pub static TEST2: bool = true;
1310

Original file line numberDiff line numberDiff line change
@@ -0,0 +1,15 @@
1+
//! The symbols are resolved by the linker. It doesn't make sense to change
2+
//! them at runtime, so deny mutable statics with #[linkage].
3+
4+
#![feature(linkage)]
5+
6+
fn main() {
7+
extern "C" {
8+
#[linkage = "weak"] //~ ERROR mutable statics are not allowed with `#[linkage]`
9+
static mut ABC: *const u8;
10+
}
11+
12+
unsafe {
13+
assert_eq!(ABC as usize, 0);
14+
}
15+
}
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,10 @@
1+
error: mutable statics are not allowed with `#[linkage]`
2+
--> $DIR/linkage-attr-mutable-static.rs:8:9
3+
|
4+
LL | #[linkage = "weak"]
5+
| ^^^^^^^^^^^^^^^^^^^
6+
|
7+
= note: making the static mutable would allow changing which symbol the static references rather than make the target of the symbol mutable
8+
9+
error: aborting due to 1 previous error
10+

0 commit comments

Comments
 (0)