Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
40 changes: 38 additions & 2 deletions compiler/rustc_attr_parsing/src/attributes/link_attrs.rs
Original file line number Diff line number Diff line change
Expand Up @@ -14,8 +14,9 @@ use crate::attributes::cfg::parse_cfg_entry;
use crate::session_diagnostics::{
AsNeededCompatibility, BundleNeedsStatic, EmptyLinkName, ExportSymbolsNeedsStatic,
ImportNameTypeRaw, ImportNameTypeX86, IncompatibleWasmLink, InvalidLinkModifier,
LinkFrameworkApple, LinkOrdinalOutOfRange, LinkRequiresName, MultipleModifiers,
NullOnLinkSection, RawDylibNoNul, RawDylibOnlyWindows, WholeArchiveNeedsStatic,
InvalidMachoSection, InvalidMachoSectionReason, LinkFrameworkApple, LinkOrdinalOutOfRange,
LinkRequiresName, MultipleModifiers, NullOnLinkSection, RawDylibNoNul, RawDylibOnlyWindows,
WholeArchiveNeedsStatic,
};

pub(crate) struct LinkNameParser;
Expand Down Expand Up @@ -460,6 +461,29 @@ impl LinkParser {

pub(crate) struct LinkSectionParser;

fn check_link_section_macho(name: Symbol) -> Result<(), InvalidMachoSectionReason> {
let mut parts = name.as_str().split(',').map(|s| s.trim());
Copy link
Copy Markdown
Member

@bjorn3 bjorn3 Apr 12, 2026

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

View changes since the review

Does LLVM also trim? I don't trim in cg_clif when parsing section names.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.


// The segment can be empty.
let _segment = parts.next();

// But the section is required.
let section = match parts.next() {
None | Some("") => return Err(InvalidMachoSectionReason::MissingSection),
Some(section) => section,
};

if section.len() > 16 {
return Err(InvalidMachoSectionReason::SectionTooLong { section: section.to_string() });
}

// LLVM also checks the other components of the section specifier, but that logic is hard to
// keep in sync. We skip it here for now, assuming that if you got that far you'll be able
// to interpret the LLVM errors.

Ok(())
}

impl<S: Stage> SingleAttributeParser<S> for LinkSectionParser {
const PATH: &[Symbol] = &[sym::link_section];
const ON_DUPLICATE: OnDuplicate<S> = OnDuplicate::WarnButFutureError;
Expand Down Expand Up @@ -492,6 +516,18 @@ impl<S: Stage> SingleAttributeParser<S> for LinkSectionParser {
return None;
}

// We (currently) only validate macho section specifiers.
match cx.sess.target.binary_format {
BinaryFormat::MachO => match check_link_section_macho(name) {
Ok(()) => {}
Err(reason) => {
cx.emit_err(InvalidMachoSection { name_span: nv.value_span, reason });
return None;
}
},
BinaryFormat::Coff | BinaryFormat::Elf | BinaryFormat::Wasm | BinaryFormat::Xcoff => {}
}

Some(LinkSection { name, span: cx.attr_span })
}
}
Expand Down
19 changes: 19 additions & 0 deletions compiler/rustc_attr_parsing/src/session_diagnostics.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1133,3 +1133,22 @@ pub(crate) struct UnstableAttrForAlreadyStableFeature {
#[label("the stability attribute annotates this item")]
pub item_span: Span,
}

#[derive(Diagnostic)]
#[diag("invalid Mach-O section specifier")]
pub(crate) struct InvalidMachoSection {
#[primary_span]
#[label("not a valid Mach-O section specifier")]
pub name_span: Span,
#[subdiagnostic]
pub reason: InvalidMachoSectionReason,
}

#[derive(Subdiagnostic)]
pub(crate) enum InvalidMachoSectionReason {
#[note("a Mach-O section specifier requires a segment and a section, separated by a comma")]
#[help("an example of a valid Mach-O section specifier is `__TEXT,__cstring`")]
MissingSection,
#[note("section name `{$section}` is longer than 16 bytes")]
SectionTooLong { section: String },
}
2 changes: 1 addition & 1 deletion compiler/rustc_hir/src/attrs/data_structures.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1090,8 +1090,8 @@ pub enum AttributeKind {

/// Represents [`#[link_section]`](https://doc.rust-lang.org/reference/abi.html#the-link_section-attribute)
LinkSection {
name: Symbol,
span: Span,
name: Symbol,
},

/// Represents `#[linkage]`.
Expand Down
18 changes: 9 additions & 9 deletions tests/codegen-llvm/link_section.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,14 +3,14 @@

#![crate_type = "lib"]

// CHECK: @VAR1 = {{(dso_local )?}}constant [4 x i8] c"\01\00\00\00", section ".test_one"
// CHECK: @VAR1 = {{(dso_local )?}}constant [4 x i8] c"\01\00\00\00", section "__TEST,one"
#[no_mangle]
#[link_section = ".test_one"]
#[link_section = "__TEST,one"]
#[cfg(target_endian = "little")]
pub static VAR1: u32 = 1;

#[no_mangle]
#[link_section = ".test_one"]
#[link_section = "__TEST,one"]
#[cfg(target_endian = "big")]
pub static VAR1: u32 = 0x01000000;

Expand All @@ -19,17 +19,17 @@ pub enum E {
B(f32),
}

// CHECK: @VAR2 = {{(dso_local )?}}constant {{.*}}, section ".test_two"
// CHECK: @VAR2 = {{(dso_local )?}}constant {{.*}}, section "__TEST,two"
#[no_mangle]
#[link_section = ".test_two"]
#[link_section = "__TEST,two"]
pub static VAR2: E = E::A(666);

// CHECK: @VAR3 = {{(dso_local )?}}constant {{.*}}, section ".test_three"
// CHECK: @VAR3 = {{(dso_local )?}}constant {{.*}}, section "__TEST,three"
#[no_mangle]
#[link_section = ".test_three"]
#[link_section = "__TEST,three"]
pub static VAR3: E = E::B(1.);

// CHECK: define {{(dso_local )?}}void @fn1() {{.*}} section ".test_four" {
// CHECK: define {{(dso_local )?}}void @fn1() {{.*}} section "__TEST,four" {
#[no_mangle]
#[link_section = ".test_four"]
#[link_section = "__TEST,four"]
pub fn fn1() {}
9 changes: 6 additions & 3 deletions tests/codegen-llvm/naked-fn/naked-functions.rs
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@
//@[thumb] needs-llvm-components: arm

#![crate_type = "lib"]
#![feature(no_core, lang_items, rustc_attrs)]
#![feature(no_core, lang_items, rustc_attrs, cfg_target_object_format)]
#![no_core]

extern crate minicore;
Expand Down Expand Up @@ -145,13 +145,16 @@ pub extern "C" fn naked_with_args_and_return(a: isize, b: isize) -> isize {
}

// linux: .pushsection .text.some_different_name,\22ax\22, @progbits
// macos: .pushsection .text.some_different_name,regular,pure_instructions
// macos: .pushsection __TEXT,different,regular,pure_instructions
// win_x86,win_i686: .pushsection .text.some_different_name,\22xr\22
// thumb: .pushsection .text.some_different_name,\22ax\22, %progbits
// CHECK-LABEL: test_link_section:
#[no_mangle]
#[unsafe(naked)]
#[link_section = ".text.some_different_name"]
// FIXME: configure this with `cfg(target_binary_format = "mach-o")`,
// see https://github.com/rust-lang/rust/issues/152586.
#[cfg_attr(not(target_object_format = "mach-o"), link_section = ".text.some_different_name")]
#[cfg_attr(target_object_format = "mach-o", link_section = "__TEXT,different")]
pub extern "C" fn test_link_section() {
cfg_select! {
all(target_arch = "arm", target_feature = "thumb-mode") => {
Expand Down
4 changes: 2 additions & 2 deletions tests/rustdoc-html/attributes-2021-edition.rs
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,6 @@ pub extern "C" fn f() {}
#[export_name = "bar"]
pub extern "C" fn g() {}

//@ has foo/fn.example.html '//pre[@class="rust item-decl"]' '#[unsafe(link_section = ".text")]'
#[link_section = ".text"]
//@ has foo/fn.example.html '//pre[@class="rust item-decl"]' '#[unsafe(link_section = "__TEXT,__text")]'
#[link_section = "__TEXT,__text"]
pub extern "C" fn example() {}
1 change: 1 addition & 0 deletions tests/rustdoc-html/attributes.rs
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
//@ edition: 2024
//@ only-linux
#![crate_name = "foo"]

//@ has foo/fn.f.html '//*[@class="code-attribute"]' '#[unsafe(no_mangle)]'
Expand Down
2 changes: 1 addition & 1 deletion tests/rustdoc-html/inline_cross/attributes.rs
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@
pub use attributes::no_mangle;

//@ has 'user/fn.link_section.html' '//pre[@class="rust item-decl"]' \
// '#[unsafe(link_section = ".here")]'
// '#[unsafe(link_section = "__TEXT,__here")]'
pub use attributes::link_section;

//@ has 'user/fn.export_name.html' '//pre[@class="rust item-decl"]' \
Expand Down
2 changes: 1 addition & 1 deletion tests/rustdoc-html/inline_cross/auxiliary/attributes.rs
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
#[unsafe(no_mangle)]
pub fn no_mangle() {}

#[unsafe(link_section = ".here")]
#[unsafe(link_section = "__TEXT,__here")]
pub fn link_section() {}

#[unsafe(export_name = "exonym")]
Expand Down
4 changes: 2 additions & 2 deletions tests/rustdoc-json/attrs/link_section_2021.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,6 @@
#![no_std]

//@ count "$.index[?(@.name=='example')].attrs[*]" 1
//@ is "$.index[?(@.name=='example')].attrs[*].link_section" '".text"'
#[link_section = ".text"]
//@ is "$.index[?(@.name=='example')].attrs[*].link_section" '"__TEXT,__text"'
#[link_section = "__TEXT,__text"]
pub extern "C" fn example() {}
4 changes: 2 additions & 2 deletions tests/rustdoc-json/attrs/link_section_2024.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,6 @@
// However, the unsafe qualification is not shown by rustdoc.

//@ count "$.index[?(@.name=='example')].attrs[*]" 1
//@ is "$.index[?(@.name=='example')].attrs[*].link_section" '".text"'
#[unsafe(link_section = ".text")]
//@ is "$.index[?(@.name=='example')].attrs[*].link_section" '"__TEXT,__text"'
#[unsafe(link_section = "__TEXT,__text")]
pub extern "C" fn example() {}
5 changes: 3 additions & 2 deletions tests/ui/asm/naked-functions.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@
//@ ignore-spirv
//@ reference: attributes.codegen.naked.body

#![feature(asm_unwind, linkage, rustc_attrs)]
#![feature(asm_unwind, linkage, rustc_attrs, cfg_target_object_format)]
#![crate_type = "lib"]

use std::arch::{asm, naked_asm};
Expand Down Expand Up @@ -200,7 +200,8 @@ pub extern "C" fn compatible_must_use_attributes() -> u64 {
}

#[export_name = "exported_function_name"]
#[link_section = ".custom_section"]
#[cfg_attr(not(target_object_format = "mach-o"), link_section = ".custom")]
#[cfg_attr(target_object_format = "mach-o", link_section = "__TEXT,__custom")]
#[unsafe(naked)]
pub extern "C" fn compatible_ffi_attributes_1() {
naked_asm!("", options(raw));
Expand Down
2 changes: 1 addition & 1 deletion tests/ui/attributes/attr-on-mac-call.rs
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,7 @@ fn main() {
#[link_name = "x"]
//~^ WARN attribute cannot be used on macro calls
//~| WARN previously accepted
#[link_section = "x"]
#[link_section = "__TEXT,__text"]
//~^ WARN attribute cannot be used on macro calls
//~| WARN previously accepted
#[link_ordinal(42)]
Expand Down
4 changes: 2 additions & 2 deletions tests/ui/attributes/attr-on-mac-call.stderr
Original file line number Diff line number Diff line change
Expand Up @@ -78,8 +78,8 @@ LL | #[link_name = "x"]
warning: `#[link_section]` attribute cannot be used on macro calls
--> $DIR/attr-on-mac-call.rs:30:5
|
LL | #[link_section = "x"]
| ^^^^^^^^^^^^^^^^^^^^^
LL | #[link_section = "__TEXT,__text"]
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
|
= warning: this was previously accepted by the compiler but is being phased out; it will become a hard error in a future release!
= help: `#[link_section]` can be applied to functions and statics
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ trait Test {
//~^ ERROR cannot be used on required trait methods [unused_attributes]
//~| WARN previously accepted
fn method1(&self);
#[link_section = ".text"]
#[link_section = "__TEXT,__text"]
//~^ ERROR cannot be used on required trait methods [unused_attributes]
//~| WARN previously accepted
fn method2(&self);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -15,8 +15,8 @@ LL | #![deny(unused_attributes)]
error: `#[link_section]` attribute cannot be used on required trait methods
--> $DIR/codegen_attr_on_required_trait_method.rs:10:5
|
LL | #[link_section = ".text"]
| ^^^^^^^^^^^^^^^^^^^^^^^^^
LL | #[link_section = "__TEXT,__text"]
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
|
= warning: this was previously accepted by the compiler but is being phased out; it will become a hard error in a future release!
= help: `#[link_section]` can be applied to functions, inherent methods, provided trait methods, statics, and trait methods in impl blocks
Expand Down
26 changes: 13 additions & 13 deletions tests/ui/feature-gates/issue-43106-gating-of-builtin-attrs.rs
Original file line number Diff line number Diff line change
Expand Up @@ -74,7 +74,7 @@
//~| WARN previously accepted
//~| HELP can be applied to
//~| HELP remove the attribute
#![link_section = "1800"]
#![link_section = ",1800"]
//~^ WARN attribute cannot be used on
//~| WARN previously accepted
//~| HELP can be applied to
Expand Down Expand Up @@ -616,66 +616,66 @@ mod link_name {
//~| HELP remove the attribute
}

#[link_section = "1800"]
#[link_section = ",1800"]
//~^ WARN attribute cannot be used on
//~| WARN previously accepted
//~| HELP can be applied to
//~| HELP remove the attribute
mod link_section {
mod inner { #![link_section="1800"] }
mod inner { #![link_section=",1800"] }
//~^ WARN attribute cannot be used on
//~| WARN previously accepted
//~| HELP can be applied to
//~| HELP remove the attribute

#[link_section = "1800"] fn f() { }
#[link_section = ",1800"] fn f() { }

#[link_section = "1800"] struct S;
#[link_section = ",1800"] struct S;
//~^ WARN attribute cannot be used on
//~| WARN previously accepted
//~| HELP can be applied to
//~| HELP remove the attribute

#[link_section = "1800"] type T = S;
#[link_section = ",1800"] type T = S;
//~^ WARN attribute cannot be used on
//~| WARN previously accepted
//~| HELP can be applied to
//~| HELP remove the attribute

#[link_section = "1800"] impl S { }
#[link_section = ",1800"] impl S { }
//~^ WARN attribute cannot be used on
//~| WARN previously accepted
//~| HELP can be applied to
//~| HELP remove the attribute

#[link_section = "1800"]
#[link_section = ",1800"]
//~^ WARN attribute cannot be used on
//~| WARN previously accepted
//~| HELP can be applied to
//~| HELP remove the attribute
trait Tr {
#[link_section = "1800"]
#[link_section = ",1800"]
//~^ WARN attribute cannot be used on
//~| WARN previously accepted
//~| HELP can be applied to
//~| HELP remove the attribute
fn inside_tr_no_default(&self);

#[link_section = "1800"]
#[link_section = ",1800"]
fn inside_tr_default(&self) { }
}

impl S {
#[link_section = "1800"]
#[link_section = ",1800"]
fn inside_abc_123(&self) { }
}

impl Tr for S {
#[link_section = "1800"]
#[link_section = ",1800"]
fn inside_tr_no_default(&self) { }
}

#[link_section = "1800"]
#[link_section = ",1800"]
fn should_always_link() { }
}

Expand Down
Loading
Loading