Skip to content

Commit 206b951

Browse files
committed
Fix linker failures when #[global_allocator] is used in a dependency
1 parent 8d1fa47 commit 206b951

File tree

4 files changed

+38
-2
lines changed

4 files changed

+38
-2
lines changed

Diff for: compiler/rustc_codegen_ssa/src/base.rs

+16-2
Original file line numberDiff line numberDiff line change
@@ -13,7 +13,7 @@ use crate::mir::place::PlaceRef;
1313
use crate::traits::*;
1414
use crate::{CachedModuleCodegen, CompiledModule, CrateInfo, MemFlags, ModuleCodegen, ModuleKind};
1515

16-
use rustc_ast::expand::allocator::AllocatorKind;
16+
use rustc_ast::expand::allocator::{global_fn_name, AllocatorKind, ALLOCATOR_METHODS};
1717
use rustc_attr as attr;
1818
use rustc_data_structures::fx::{FxHashMap, FxHashSet};
1919
use rustc_data_structures::profiling::{get_resident_set_size, print_time_passes_entry};
@@ -921,7 +921,21 @@ impl CrateInfo {
921921
missing_weak_lang_items
922922
.iter()
923923
.map(|item| (format!("{prefix}{item}"), SymbolExportKind::Text)),
924-
)
924+
);
925+
if tcx.allocator_kind(()).is_some() {
926+
// At least one crate needs a global allocator. This crate may be placed
927+
// after the crate that defines it in the linker order, in which case some
928+
// linkers return an error. By adding the global allocator shim methods to
929+
// the linked_symbols list, linking the generated symbols.o will ensure that
930+
// circular dependencies involving the global allocator don't lead to linker
931+
// errors.
932+
linked_symbols.extend(ALLOCATOR_METHODS.iter().map(|method| {
933+
(
934+
format!("{prefix}{}", global_fn_name(method.name).as_str()),
935+
SymbolExportKind::Text,
936+
)
937+
}));
938+
}
925939
});
926940
}
927941

Diff for: tests/run-make/allocator-shim-circular-deps/Makefile

+7
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,7 @@
1+
# ignore-cross-compile
2+
include ../tools.mk
3+
4+
all:
5+
rm -rf $(TMPDIR) && mkdir $(TMPDIR)
6+
$(RUSTC) my_lib.rs
7+
$(RUSTC) main.rs --test --extern my_lib=$(TMPDIR)/libmy_lib.rlib

Diff for: tests/run-make/allocator-shim-circular-deps/main.rs

+5
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,5 @@
1+
#![crate_type = "bin"]
2+
3+
fn main() {
4+
my_lib::do_something();
5+
}
+10
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,10 @@
1+
#![crate_type = "lib"]
2+
3+
use std::alloc::System;
4+
5+
#[global_allocator]
6+
static ALLOCATOR: System = System;
7+
8+
pub fn do_something() {
9+
format!("allocating a string!");
10+
}

0 commit comments

Comments
 (0)