Skip to content

Commit 380a85b

Browse files
committed
Auto merge of #122362 - Zoxc:rustc_driver_static_std, r=<try>
Link `std` statically in `rustc_driver` This makes `rustc_driver` statically link to `std`. This is done by not passing `-C prefer-dynamic` when building `rustc_driver`. However building `rustc-main` won't work currently as it tries to dynamically link to both `rustc_driver` and `std` resulting in a crate graph with `std` duplicated. To fix that new command line option `-Z prefer_deps_of_dynamic` is added which prevents linking to a dylib if there's a static variant of it already statically linked into another dylib dependency. The main motivation for this change is to enable `#[global_allocator]` to be used in `rustc_driver` allowing overriding the allocator used in rustc on all platforms.
2 parents 0fa7fea + d5cdb9e commit 380a85b

File tree

6 files changed

+62
-17
lines changed

6 files changed

+62
-17
lines changed

compiler/rustc_interface/src/tests.rs

+1
Original file line numberDiff line numberDiff line change
@@ -806,6 +806,7 @@ fn test_unstable_options_tracking_hash() {
806806
tracked!(plt, Some(true));
807807
tracked!(polonius, Polonius::Legacy);
808808
tracked!(precise_enum_drop_elaboration, false);
809+
tracked!(prefer_deps_of_dynamic, true);
809810
tracked!(print_fuel, Some("abc".to_string()));
810811
tracked!(profile, true);
811812
tracked!(profile_emit, Some(PathBuf::from("abc")));

compiler/rustc_metadata/src/dependency_format.rs

+33-12
Original file line numberDiff line numberDiff line change
@@ -57,7 +57,7 @@ use crate::errors::{
5757
RequiredPanicStrategy, RlibRequired, RustcLibRequired, TwoPanicRuntimes,
5858
};
5959

60-
use rustc_data_structures::fx::FxHashMap;
60+
use rustc_data_structures::fx::{FxHashMap, FxHashSet};
6161
use rustc_hir::def_id::CrateNum;
6262
use rustc_middle::middle::dependency_format::{Dependencies, DependencyList, Linkage};
6363
use rustc_middle::ty::TyCtxt;
@@ -156,25 +156,46 @@ fn calculate_type(tcx: TyCtxt<'_>, ty: CrateType) -> DependencyList {
156156
Linkage::Dynamic | Linkage::IncludedFromDylib => {}
157157
}
158158

159+
let all_dylibs = || {
160+
tcx.crates(()).iter().filter(|&&cnum| {
161+
!tcx.dep_kind(cnum).macros_only() && tcx.used_crate_source(cnum).dylib.is_some()
162+
})
163+
};
164+
165+
let mut upstream_in_dylibs = FxHashSet::default();
166+
167+
if sess.opts.unstable_opts.prefer_deps_of_dynamic || tcx.features().rustc_private {
168+
// Find all libraries statically linked to upstream dylibs.
169+
for &cnum in all_dylibs() {
170+
let deps = tcx.dylib_dependency_formats(cnum);
171+
for &(depnum, style) in deps.iter() {
172+
if let RequireStatic = style {
173+
upstream_in_dylibs.insert(depnum);
174+
}
175+
}
176+
}
177+
}
178+
159179
let mut formats = FxHashMap::default();
160180

161181
// Sweep all crates for found dylibs. Add all dylibs, as well as their
162182
// dependencies, ensuring there are no conflicts. The only valid case for a
163183
// dependency to be relied upon twice is for both cases to rely on a dylib.
164-
for &cnum in tcx.crates(()).iter() {
165-
if tcx.dep_kind(cnum).macros_only() {
184+
for &cnum in all_dylibs() {
185+
if upstream_in_dylibs.contains(&cnum) {
186+
info!("skipping dylib: {}", tcx.crate_name(cnum));
187+
// If this dylib is also available statically linked to another dylib
188+
// we try to use that instead.
166189
continue;
167190
}
191+
168192
let name = tcx.crate_name(cnum);
169-
let src = tcx.used_crate_source(cnum);
170-
if src.dylib.is_some() {
171-
info!("adding dylib: {}", name);
172-
add_library(tcx, cnum, RequireDynamic, &mut formats);
173-
let deps = tcx.dylib_dependency_formats(cnum);
174-
for &(depnum, style) in deps.iter() {
175-
info!("adding {:?}: {}", style, tcx.crate_name(depnum));
176-
add_library(tcx, depnum, style, &mut formats);
177-
}
193+
info!("adding dylib: {}", name);
194+
add_library(tcx, cnum, RequireDynamic, &mut formats);
195+
let deps = tcx.dylib_dependency_formats(cnum);
196+
for &(depnum, style) in deps.iter() {
197+
info!("adding {:?}: {}", style, tcx.crate_name(depnum));
198+
add_library(tcx, depnum, style, &mut formats);
178199
}
179200
}
180201

compiler/rustc_session/src/options.rs

+2
Original file line numberDiff line numberDiff line change
@@ -1810,6 +1810,8 @@ options! {
18101810
"use a more precise version of drop elaboration for matches on enums (default: yes). \
18111811
This results in better codegen, but has caused miscompilations on some tier 2 platforms. \
18121812
See #77382 and #74551."),
1813+
prefer_deps_of_dynamic: bool = (false, parse_bool, [TRACKED],
1814+
"prefer linking to static dependencies of dynamic libraries over available dynamic libraries (default: no)"),
18131815
#[rustc_lint_opt_deny_field_access("use `Session::print_codegen_stats` instead of this field")]
18141816
print_codegen_stats: bool = (false, parse_bool, [UNTRACKED],
18151817
"print codegen statistics (default: no)"),

src/bootstrap/src/bin/rustc.rs

+13-3
Original file line numberDiff line numberDiff line change
@@ -91,6 +91,19 @@ fn main() {
9191
rustc_real
9292
};
9393

94+
// Get the name of the crate we're compiling, if any.
95+
let crate_name = arg("--crate-name");
96+
97+
// We want everything statically linked into `rustc_driver`, so remove `-C prefer-dynamic`
98+
if crate_name == Some("rustc_driver") && stage != "0" {
99+
if let Some(i) = args.iter().enumerate().position(|(i, a)| {
100+
a == "-C" && args.get(i + 1).map(|a| a == "prefer-dynamic").unwrap_or(false)
101+
}) {
102+
args.remove(i);
103+
args.remove(i);
104+
}
105+
}
106+
94107
let mut cmd = if let Some(wrapper) = env::var_os("RUSTC_WRAPPER_REAL") {
95108
let mut cmd = Command::new(wrapper);
96109
cmd.arg(rustc_driver);
@@ -100,9 +113,6 @@ fn main() {
100113
};
101114
cmd.args(&args).env(dylib_path_var(), env::join_paths(&dylib_path).unwrap());
102115

103-
// Get the name of the crate we're compiling, if any.
104-
let crate_name = arg("--crate-name");
105-
106116
if let Some(crate_name) = crate_name {
107117
if let Some(target) = env::var_os("RUSTC_TIME") {
108118
if target == "all"

src/bootstrap/src/core/build_steps/compile.rs

+6-1
Original file line numberDiff line numberDiff line change
@@ -1788,7 +1788,12 @@ impl Step for Assemble {
17881788
let src_libdir = builder.sysroot_libdir(build_compiler, host);
17891789
for f in builder.read_dir(&src_libdir) {
17901790
let filename = f.file_name().into_string().unwrap();
1791-
if (is_dylib(&filename) || is_debug_info(&filename)) && !proc_macros.contains(&filename)
1791+
let can_be_rustc_dep = filename.starts_with("rustc_driver-")
1792+
|| filename.starts_with("librustc_driver-")
1793+
|| build_compiler.stage == 0;
1794+
if can_be_rustc_dep
1795+
&& (is_dylib(&filename) || is_debug_info(&filename))
1796+
&& !proc_macros.contains(&filename)
17921797
{
17931798
builder.copy(&f.path(), &rustc_libdir.join(&filename));
17941799
}

src/bootstrap/src/core/builder.rs

+7-1
Original file line numberDiff line numberDiff line change
@@ -2029,10 +2029,16 @@ impl<'a> Builder<'a> {
20292029
// When we build Rust dylibs they're all intended for intermediate
20302030
// usage, so make sure we pass the -Cprefer-dynamic flag instead of
20312031
// linking all deps statically into the dylib.
2032-
if matches!(mode, Mode::Std | Mode::Rustc) {
2032+
if matches!(mode, Mode::Std) {
20332033
rustflags.arg("-Cprefer-dynamic");
20342034
}
20352035

2036+
// We need this to prevent users of `rustc_driver` from linking to dynamically to `std`
2037+
// which does not work as `std` is statically linked into `rustc_driver`.
2038+
if stage > 0 {
2039+
rustflags.arg("-Zprefer-deps-of-dynamic");
2040+
}
2041+
20362042
// When building incrementally we default to a lower ThinLTO import limit
20372043
// (unless explicitly specified otherwise). This will produce a somewhat
20382044
// slower code but give way better compile times.

0 commit comments

Comments
 (0)