Skip to content

Commit

Permalink
Rollup merge of #125046 - bjorn3:no_mutable_static_linkage, r=cjgillot
Browse files Browse the repository at this point in the history
Only allow immutable statics with #[linkage]
  • Loading branch information
workingjubilee committed May 26, 2024
2 parents 866630d + 531dae1 commit 5860d43
Show file tree
Hide file tree
Showing 4 changed files with 37 additions and 3 deletions.
12 changes: 12 additions & 0 deletions compiler/rustc_codegen_ssa/src/codegen_attrs.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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 => {
Expand Down
3 changes: 0 additions & 3 deletions tests/ui/issues/issue-33992.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,9 +5,6 @@

#![feature(linkage)]

#[linkage = "common"]
pub static mut TEST1: u32 = 0u32;

#[linkage = "external"]
pub static TEST2: bool = true;

Expand Down
15 changes: 15 additions & 0 deletions tests/ui/linkage-attr/linkage-attr-mutable-static.rs
Original file line number Diff line number Diff line change
@@ -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);
}
}
10 changes: 10 additions & 0 deletions tests/ui/linkage-attr/linkage-attr-mutable-static.stderr
Original file line number Diff line number Diff line change
@@ -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

0 comments on commit 5860d43

Please sign in to comment.