Skip to content

Commit e18e599

Browse files
committed
set subsections_via_symbols for ld64 helper sections
1 parent 65fa0ab commit e18e599

File tree

3 files changed

+51
-0
lines changed

3 files changed

+51
-0
lines changed

compiler/rustc_codegen_ssa/src/back/link.rs

+6
Original file line numberDiff line numberDiff line change
@@ -2015,6 +2015,12 @@ fn add_linked_symbol_object(
20152015
file.set_mangling(object::write::Mangling::None);
20162016
}
20172017

2018+
if file.format() == object::BinaryFormat::MachO {
2019+
// Divide up the sections into sub-sections via symbols for dead code stripping.
2020+
// Without this flag, unused `#[no_mangle]` or `#[used]` cannot be discard on MachO targets.
2021+
file.set_subsections_via_symbols();
2022+
}
2023+
20182024
// ld64 requires a relocation to load undefined symbols, see below.
20192025
// Not strictly needed if linking with lld, but might as well do it there too.
20202026
let ld64_section_helper = if file.format() == object::BinaryFormat::MachO {

tests/ui/linking/cdylib-no-mangle.rs

+20
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,20 @@
1+
//@ only-apple
2+
//@ build-fail
3+
//@ dont-check-compiler-stderr
4+
//@ dont-check-compiler-stdout
5+
6+
// Regression test for <https://github.com/rust-lang/rust/issues/139744>.
7+
// Functions in the dynamic library marked with no_mangle should not be GC-ed.
8+
9+
#![crate_type = "cdylib"]
10+
11+
unsafe extern "C" {
12+
unsafe static THIS_SYMBOL_SHOULD_BE_UNDEFINED: usize;
13+
}
14+
15+
#[unsafe(no_mangle)]
16+
pub unsafe fn function_marked_with_no_mangle() {
17+
println!("FUNCTION_MARKED_WITH_NO_MANGLE = {}", unsafe { THIS_SYMBOL_SHOULD_BE_UNDEFINED });
18+
}
19+
20+
//~? ERROR linking
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,25 @@
1+
//@ build-pass
2+
3+
// Regression test for <https://github.com/rust-lang/rust/issues/139744>.
4+
// Functions in the binary marked with no_mangle should be GC-ed if they
5+
// are not indirectly referenced by main.
6+
7+
#![feature(used_with_arg)]
8+
9+
unsafe extern "C" {
10+
unsafe static THIS_SYMBOL_SHOULD_BE_UNDEFINED: usize;
11+
}
12+
13+
#[unsafe(no_mangle)]
14+
pub unsafe fn function_marked_with_no_mangle() {
15+
println!("FUNCTION_MARKED_WITH_NO_MANGLE = {}", unsafe { THIS_SYMBOL_SHOULD_BE_UNDEFINED });
16+
}
17+
18+
#[used(compiler)]
19+
pub static FUNCTION_MARKED_WITH_USED: unsafe fn() = || {
20+
println!("FUNCTION_MARKED_WITH_USED = {}", unsafe { THIS_SYMBOL_SHOULD_BE_UNDEFINED });
21+
};
22+
23+
fn main() {
24+
println!("MAIN");
25+
}

0 commit comments

Comments
 (0)