Skip to content

Commit c9b147c

Browse files
bjorn3xobs
authored andcommitted
Fix linker failures when #[global_allocator] is used in a dependency
1 parent 752d1be commit c9b147c

File tree

4 files changed

+38
-2
lines changed

4 files changed

+38
-2
lines changed

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};
@@ -909,7 +909,21 @@ impl CrateInfo {
909909
missing_weak_lang_items
910910
.iter()
911911
.map(|item| (format!("{prefix}{item}"), SymbolExportKind::Text)),
912-
)
912+
);
913+
if tcx.allocator_kind(()).is_some() {
914+
// At least one crate needs a global allocator. This crate may be placed
915+
// after the crate that defines it in the linker order, in which case some
916+
// linkers return an error. By adding the global allocator shim methods to
917+
// the linked_symbols list, linking the generated symbols.o will ensure that
918+
// circular dependencies involving the global allocator don't lead to linker
919+
// errors.
920+
linked_symbols.extend(ALLOCATOR_METHODS.iter().map(|method| {
921+
(
922+
format!("{prefix}{}", global_fn_name(method.name).as_str()),
923+
SymbolExportKind::Text,
924+
)
925+
}));
926+
}
913927
});
914928
}
915929

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
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+
}
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)