Skip to content

Commit 41bc5d7

Browse files
Rollup merge of #142089 - bjorn3:sysroot_handling_cleanup3, r=petrochenkov
Replace all uses of sysroot_candidates with get_or_default_sysroot Before this change we had two different ways to attempt to locate the sysroot which are inconsistently used: * `get_or_default_sysroot` which tries to locate based on the 0th cli argument and if that doesn't work falls back to locating it using the librustc_driver.so location and returns a single path., * `sysroot_candidates` which takes the former and additionally does another attempt at locating using `librustc_driver.so` except without linux multiarch handling and then returns both paths., The latter was originally introduced to be able to locate the codegen backend back when cg_llvm was dynamically linked even for a custom driver when the `--sysroot` passed in does not contain a copy of cg_llvm. Back then `get_or_default_sysroot` did not attempt to locate the sysroot based on the location of librustc_driver.so yet. Because that is now done, the only case where removing `sysroot_candidates` can break things is if you have a custom driver inside what looks like a sysroot including the `lib/rustlib` directory, but which is missing some parts of the full sysroot like eg rust-lld. Follow up to #138404
2 parents 840baa4 + e4c4c4c commit 41bc5d7

File tree

7 files changed

+33
-69
lines changed

7 files changed

+33
-69
lines changed

Cargo.lock

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -3652,6 +3652,7 @@ dependencies = [
36523652
"rustc_macros",
36533653
"rustc_serialize",
36543654
"rustc_span",
3655+
"smallvec",
36553656
"tracing",
36563657
"unic-langid",
36573658
]

compiler/rustc_error_messages/Cargo.toml

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -16,6 +16,7 @@ rustc_data_structures = { path = "../rustc_data_structures" }
1616
rustc_macros = { path = "../rustc_macros" }
1717
rustc_serialize = { path = "../rustc_serialize" }
1818
rustc_span = { path = "../rustc_span" }
19+
smallvec = { version = "1.8.1", features = ["union", "may_dangle"] }
1920
tracing = "0.1"
2021
unic-langid = { version = "0.9.0", features = ["macros"] }
2122
# tidy-alphabetical-end

compiler/rustc_error_messages/src/lib.rs

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -21,6 +21,7 @@ use intl_memoizer::concurrent::IntlLangMemoizer;
2121
use rustc_data_structures::sync::IntoDynSyncSend;
2222
use rustc_macros::{Decodable, Encodable};
2323
use rustc_span::Span;
24+
use smallvec::SmallVec;
2425
use tracing::{instrument, trace};
2526
pub use unic_langid::{LanguageIdentifier, langid};
2627

@@ -106,8 +107,7 @@ impl From<Vec<FluentError>> for TranslationBundleError {
106107
/// (overriding any conflicting messages).
107108
#[instrument(level = "trace")]
108109
pub fn fluent_bundle(
109-
sysroot: PathBuf,
110-
sysroot_candidates: Vec<PathBuf>,
110+
sysroot_candidates: SmallVec<[PathBuf; 2]>,
111111
requested_locale: Option<LanguageIdentifier>,
112112
additional_ftl_path: Option<&Path>,
113113
with_directionality_markers: bool,
@@ -141,7 +141,7 @@ pub fn fluent_bundle(
141141
// If the user requests the default locale then don't try to load anything.
142142
if let Some(requested_locale) = requested_locale {
143143
let mut found_resources = false;
144-
for mut sysroot in Some(sysroot).into_iter().chain(sysroot_candidates.into_iter()) {
144+
for mut sysroot in sysroot_candidates {
145145
sysroot.push("share");
146146
sysroot.push("locale");
147147
sysroot.push(requested_locale.to_string());

compiler/rustc_interface/src/interface.rs

Lines changed: 2 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -18,7 +18,7 @@ use rustc_parse::parser::attr::AllowLeadingUnsafe;
1818
use rustc_query_impl::QueryCtxt;
1919
use rustc_query_system::query::print_query_stack;
2020
use rustc_session::config::{self, Cfg, CheckCfg, ExpectedValues, Input, OutFileName};
21-
use rustc_session::filesearch::sysroot_candidates;
21+
use rustc_session::filesearch::sysroot_with_fallback;
2222
use rustc_session::parse::ParseSess;
2323
use rustc_session::{CompilerIO, EarlyDiagCtxt, Session, lint};
2424
use rustc_span::source_map::{FileLoader, RealFileLoader, SourceMapInputs};
@@ -442,8 +442,7 @@ pub fn run_compiler<R: Send>(config: Config, f: impl FnOnce(&Compiler) -> R + Se
442442
let temps_dir = config.opts.unstable_opts.temps_dir.as_deref().map(PathBuf::from);
443443

444444
let bundle = match rustc_errors::fluent_bundle(
445-
config.opts.sysroot.clone(),
446-
sysroot_candidates().to_vec(),
445+
sysroot_with_fallback(&config.opts.sysroot),
447446
config.opts.unstable_opts.translate_lang.clone(),
448447
config.opts.unstable_opts.translate_additional_ftl.as_deref(),
449448
config.opts.unstable_opts.translate_directionality_markers,

compiler/rustc_interface/src/util.rs

Lines changed: 8 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,7 @@ use std::env::consts::{DLL_PREFIX, DLL_SUFFIX};
22
use std::path::{Path, PathBuf};
33
use std::sync::atomic::{AtomicBool, Ordering};
44
use std::sync::{Arc, OnceLock};
5-
use std::{env, iter, thread};
5+
use std::{env, thread};
66

77
use rustc_ast as ast;
88
use rustc_codegen_ssa::traits::CodegenBackend;
@@ -12,7 +12,6 @@ use rustc_metadata::{DylibError, load_symbol_from_dylib};
1212
use rustc_middle::ty::CurrentGcx;
1313
use rustc_parse::validate_attr;
1414
use rustc_session::config::{Cfg, OutFileName, OutputFilenames, OutputTypes, host_tuple};
15-
use rustc_session::filesearch::sysroot_candidates;
1615
use rustc_session::lint::{self, BuiltinLintDiag, LintBuffer};
1716
use rustc_session::output::{CRATE_TYPES, categorize_crate_type};
1817
use rustc_session::{EarlyDiagCtxt, Session, filesearch};
@@ -346,14 +345,10 @@ pub fn rustc_path<'a>() -> Option<&'a Path> {
346345
}
347346

348347
fn get_rustc_path_inner(bin_path: &str) -> Option<PathBuf> {
349-
sysroot_candidates().iter().find_map(|sysroot| {
350-
let candidate = sysroot.join(bin_path).join(if cfg!(target_os = "windows") {
351-
"rustc.exe"
352-
} else {
353-
"rustc"
354-
});
355-
candidate.exists().then_some(candidate)
356-
})
348+
let candidate = filesearch::get_or_default_sysroot()
349+
.join(bin_path)
350+
.join(if cfg!(target_os = "windows") { "rustc.exe" } else { "rustc" });
351+
candidate.exists().then_some(candidate)
357352
}
358353

359354
#[allow(rustc::untranslatable_diagnostic)] // FIXME: make this translatable
@@ -374,10 +369,10 @@ fn get_codegen_sysroot(
374369
);
375370

376371
let target = host_tuple();
377-
let sysroot_candidates = sysroot_candidates();
372+
let sysroot_candidates = filesearch::sysroot_with_fallback(&sysroot);
378373

379-
let sysroot = iter::once(sysroot)
380-
.chain(sysroot_candidates.iter().map(<_>::as_ref))
374+
let sysroot = sysroot_candidates
375+
.iter()
381376
.map(|sysroot| {
382377
filesearch::make_target_lib_path(sysroot, target).with_file_name("codegen-backends")
383378
})

compiler/rustc_session/src/filesearch.rs

Lines changed: 17 additions & 45 deletions
Original file line numberDiff line numberDiff line change
@@ -3,7 +3,7 @@
33
use std::path::{Path, PathBuf};
44
use std::{env, fs};
55

6-
use rustc_fs_util::{fix_windows_verbatim_for_gcc, try_canonicalize};
6+
use rustc_fs_util::try_canonicalize;
77
use rustc_target::spec::Target;
88
use smallvec::{SmallVec, smallvec};
99

@@ -87,7 +87,7 @@ fn current_dll_path() -> Result<PathBuf, String> {
8787
};
8888
let bytes = CStr::from_ptr(fname_ptr).to_bytes();
8989
let os = OsStr::from_bytes(bytes);
90-
Ok(PathBuf::from(os))
90+
try_canonicalize(Path::new(os)).map_err(|e| e.to_string())
9191
}
9292

9393
#[cfg(target_os = "aix")]
@@ -122,7 +122,7 @@ fn current_dll_path() -> Result<PathBuf, String> {
122122
if (data_base..data_end).contains(&addr) {
123123
let bytes = CStr::from_ptr(&(*current).ldinfo_filename[0]).to_bytes();
124124
let os = OsStr::from_bytes(bytes);
125-
return Ok(PathBuf::from(os));
125+
return try_canonicalize(Path::new(os)).map_err(|e| e.to_string());
126126
}
127127
if (*current).ldinfo_next == 0 {
128128
break;
@@ -169,45 +169,26 @@ fn current_dll_path() -> Result<PathBuf, String> {
169169

170170
filename.truncate(n);
171171

172-
Ok(OsString::from_wide(&filename).into())
172+
let path = try_canonicalize(OsString::from_wide(&filename)).map_err(|e| e.to_string())?;
173+
174+
// See comments on this target function, but the gist is that
175+
// gcc chokes on verbatim paths which fs::canonicalize generates
176+
// so we try to avoid those kinds of paths.
177+
Ok(rustc_fs_util::fix_windows_verbatim_for_gcc(&path))
173178
}
174179

175180
#[cfg(target_os = "wasi")]
176181
fn current_dll_path() -> Result<PathBuf, String> {
177182
Err("current_dll_path is not supported on WASI".to_string())
178183
}
179184

180-
pub fn sysroot_candidates() -> SmallVec<[PathBuf; 2]> {
181-
let target = crate::config::host_tuple();
182-
let mut sysroot_candidates: SmallVec<[PathBuf; 2]> = smallvec![get_or_default_sysroot()];
183-
let path = current_dll_path().and_then(|s| try_canonicalize(s).map_err(|e| e.to_string()));
184-
if let Ok(dll) = path {
185-
// use `parent` twice to chop off the file name and then also the
186-
// directory containing the dll which should be either `lib` or `bin`.
187-
if let Some(path) = dll.parent().and_then(|p| p.parent()) {
188-
// The original `path` pointed at the `rustc_driver` crate's dll.
189-
// Now that dll should only be in one of two locations. The first is
190-
// in the compiler's libdir, for example `$sysroot/lib/*.dll`. The
191-
// other is the target's libdir, for example
192-
// `$sysroot/lib/rustlib/$target/lib/*.dll`.
193-
//
194-
// We don't know which, so let's assume that if our `path` above
195-
// ends in `$target` we *could* be in the target libdir, and always
196-
// assume that we may be in the main libdir.
197-
sysroot_candidates.push(path.to_owned());
198-
199-
if path.ends_with(target) {
200-
sysroot_candidates.extend(
201-
path.parent() // chop off `$target`
202-
.and_then(|p| p.parent()) // chop off `rustlib`
203-
.and_then(|p| p.parent()) // chop off `lib`
204-
.map(|s| s.to_owned()),
205-
);
206-
}
207-
}
185+
pub fn sysroot_with_fallback(sysroot: &Path) -> SmallVec<[PathBuf; 2]> {
186+
let mut candidates = smallvec![sysroot.to_owned()];
187+
let default_sysroot = get_or_default_sysroot();
188+
if default_sysroot != sysroot {
189+
candidates.push(default_sysroot);
208190
}
209-
210-
sysroot_candidates
191+
candidates
211192
}
212193

213194
/// Returns the provided sysroot or calls [`get_or_default_sysroot`] if it's none.
@@ -219,17 +200,8 @@ pub fn materialize_sysroot(maybe_sysroot: Option<PathBuf>) -> PathBuf {
219200
/// This function checks if sysroot is found using env::args().next(), and if it
220201
/// is not found, finds sysroot from current rustc_driver dll.
221202
pub fn get_or_default_sysroot() -> PathBuf {
222-
// Follow symlinks. If the resolved path is relative, make it absolute.
223-
fn canonicalize(path: PathBuf) -> PathBuf {
224-
let path = try_canonicalize(&path).unwrap_or(path);
225-
// See comments on this target function, but the gist is that
226-
// gcc chokes on verbatim paths which fs::canonicalize generates
227-
// so we try to avoid those kinds of paths.
228-
fix_windows_verbatim_for_gcc(&path)
229-
}
230-
231203
fn default_from_rustc_driver_dll() -> Result<PathBuf, String> {
232-
let dll = current_dll_path().map(|s| canonicalize(s))?;
204+
let dll = current_dll_path()?;
233205

234206
// `dll` will be in one of the following two:
235207
// - compiler's libdir: $sysroot/lib/*.dll
@@ -242,7 +214,7 @@ pub fn get_or_default_sysroot() -> PathBuf {
242214
dll.display()
243215
))?;
244216

245-
// if `dir` points target's dir, move up to the sysroot
217+
// if `dir` points to target's dir, move up to the sysroot
246218
let mut sysroot_dir = if dir.ends_with(crate::config::host_tuple()) {
247219
dir.parent() // chop off `$target`
248220
.and_then(|p| p.parent()) // chop off `rustlib`

compiler/rustc_session/src/session.rs

Lines changed: 1 addition & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -458,13 +458,9 @@ impl Session {
458458
/// directories are also returned, for example if `--sysroot` is used but tools are missing
459459
/// (#125246): we also add the bin directories to the sysroot where rustc is located.
460460
pub fn get_tools_search_paths(&self, self_contained: bool) -> Vec<PathBuf> {
461-
let bin_path = filesearch::make_target_bin_path(&self.sysroot, config::host_tuple());
462-
let fallback_sysroot_paths = filesearch::sysroot_candidates()
461+
let search_paths = filesearch::sysroot_with_fallback(&self.sysroot)
463462
.into_iter()
464-
// Ignore sysroot candidate if it was the same as the sysroot path we just used.
465-
.filter(|sysroot| *sysroot != self.sysroot)
466463
.map(|sysroot| filesearch::make_target_bin_path(&sysroot, config::host_tuple()));
467-
let search_paths = std::iter::once(bin_path).chain(fallback_sysroot_paths);
468464

469465
if self_contained {
470466
// The self-contained tools are expected to be e.g. in `bin/self-contained` in the

0 commit comments

Comments
 (0)