Skip to content
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.

Commit 4a7f683

Browse files
authoredMar 13, 2025
Rollup merge of #138404 - bjorn3:sysroot_handling_cleanup, r=petrochenkov,jieyouxu
Cleanup sysroot locating a bit All commits should preserve existing behavior.
2 parents 53d68e5 + 1543256 commit 4a7f683

File tree

12 files changed

+43
-52
lines changed

12 files changed

+43
-52
lines changed
 

‎compiler/rustc_codegen_ssa/src/back/link.rs

+1-2
Original file line numberDiff line numberDiff line change
@@ -1286,8 +1286,7 @@ fn link_sanitizer_runtime(
12861286
if path.exists() {
12871287
sess.target_tlib_path.dir.clone()
12881288
} else {
1289-
let default_sysroot =
1290-
filesearch::get_or_default_sysroot().expect("Failed finding sysroot");
1289+
let default_sysroot = filesearch::get_or_default_sysroot();
12911290
let default_tlib =
12921291
filesearch::make_target_lib_path(&default_sysroot, sess.opts.target_triple.tuple());
12931292
default_tlib

‎compiler/rustc_error_messages/src/lib.rs

+3-3
Original file line numberDiff line numberDiff line change
@@ -106,8 +106,8 @@ impl From<Vec<FluentError>> for TranslationBundleError {
106106
/// (overriding any conflicting messages).
107107
#[instrument(level = "trace")]
108108
pub fn fluent_bundle(
109-
mut user_provided_sysroot: Option<PathBuf>,
110-
mut sysroot_candidates: Vec<PathBuf>,
109+
sysroot: PathBuf,
110+
sysroot_candidates: Vec<PathBuf>,
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 sysroot in user_provided_sysroot.iter_mut().chain(sysroot_candidates.iter_mut()) {
144+
for mut sysroot in Some(sysroot).into_iter().chain(sysroot_candidates.into_iter()) {
145145
sysroot.push("share");
146146
sysroot.push("locale");
147147
sysroot.push(requested_locale.to_string());

‎compiler/rustc_interface/src/interface.rs

+3-3
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::{self, sysroot_candidates};
21+
use rustc_session::filesearch::sysroot_candidates;
2222
use rustc_session::parse::ParseSess;
2323
use rustc_session::{CompilerIO, EarlyDiagCtxt, Session, lint};
2424
use rustc_span::source_map::{FileLoader, RealFileLoader, SourceMapInputs};
@@ -390,7 +390,7 @@ pub fn run_compiler<R: Send>(config: Config, f: impl FnOnce(&Compiler) -> R + Se
390390

391391
crate::callbacks::setup_callbacks();
392392

393-
let sysroot = filesearch::materialize_sysroot(config.opts.maybe_sysroot.clone());
393+
let sysroot = config.opts.sysroot.clone();
394394
let target = config::build_target_config(&early_dcx, &config.opts.target_triple, &sysroot);
395395
let file_loader = config.file_loader.unwrap_or_else(|| Box::new(RealFileLoader));
396396
let path_mapping = config.opts.file_path_mapping();
@@ -424,7 +424,7 @@ pub fn run_compiler<R: Send>(config: Config, f: impl FnOnce(&Compiler) -> R + Se
424424
let temps_dir = config.opts.unstable_opts.temps_dir.as_deref().map(PathBuf::from);
425425

426426
let bundle = match rustc_errors::fluent_bundle(
427-
config.opts.maybe_sysroot.clone(),
427+
config.opts.sysroot.clone(),
428428
sysroot_candidates().to_vec(),
429429
config.opts.unstable_opts.translate_lang.clone(),
430430
config.opts.unstable_opts.translate_additional_ftl.as_deref(),

‎compiler/rustc_interface/src/tests.rs

+2-2
Original file line numberDiff line numberDiff line change
@@ -21,7 +21,7 @@ use rustc_session::config::{
2121
use rustc_session::lint::Level;
2222
use rustc_session::search_paths::SearchPath;
2323
use rustc_session::utils::{CanonicalizedPath, NativeLib, NativeLibKind};
24-
use rustc_session::{CompilerIO, EarlyDiagCtxt, Session, build_session, filesearch, getopts};
24+
use rustc_session::{CompilerIO, EarlyDiagCtxt, Session, build_session, getopts};
2525
use rustc_span::edition::{DEFAULT_EDITION, Edition};
2626
use rustc_span::source_map::{RealFileLoader, SourceMapInputs};
2727
use rustc_span::{FileName, SourceFileHashAlgorithm, sym};
@@ -41,7 +41,7 @@ where
4141

4242
let matches = optgroups().parse(args).unwrap();
4343
let sessopts = build_session_options(&mut early_dcx, &matches);
44-
let sysroot = filesearch::materialize_sysroot(sessopts.maybe_sysroot.clone());
44+
let sysroot = sessopts.sysroot.clone();
4545
let target =
4646
rustc_session::config::build_target_config(&early_dcx, &sessopts.target_triple, &sysroot);
4747
let hash_kind = sessopts.unstable_opts.src_hash_algorithm(&target);

‎compiler/rustc_session/src/config.rs

+2-2
Original file line numberDiff line numberDiff line change
@@ -1214,7 +1214,7 @@ impl Default for Options {
12141214
describe_lints: false,
12151215
output_types: OutputTypes(BTreeMap::new()),
12161216
search_paths: vec![],
1217-
maybe_sysroot: None,
1217+
sysroot: filesearch::materialize_sysroot(None),
12181218
target_triple: TargetTuple::from_tuple(host_tuple()),
12191219
test: false,
12201220
incremental: None,
@@ -2618,7 +2618,7 @@ pub fn build_session_options(early_dcx: &mut EarlyDiagCtxt, matches: &getopts::M
26182618
describe_lints,
26192619
output_types,
26202620
search_paths,
2621-
maybe_sysroot: Some(sysroot),
2621+
sysroot,
26222622
target_triple,
26232623
test,
26242624
incremental,

‎compiler/rustc_session/src/filesearch.rs

+21-27
Original file line numberDiff line numberDiff line change
@@ -160,8 +160,7 @@ fn current_dll_path() -> Result<PathBuf, String> {
160160

161161
pub fn sysroot_candidates() -> SmallVec<[PathBuf; 2]> {
162162
let target = crate::config::host_tuple();
163-
let mut sysroot_candidates: SmallVec<[PathBuf; 2]> =
164-
smallvec![get_or_default_sysroot().expect("Failed finding sysroot")];
163+
let mut sysroot_candidates: SmallVec<[PathBuf; 2]> = smallvec![get_or_default_sysroot()];
165164
let path = current_dll_path().and_then(|s| try_canonicalize(s).map_err(|e| e.to_string()));
166165
if let Ok(dll) = path {
167166
// use `parent` twice to chop off the file name and then also the
@@ -195,12 +194,12 @@ pub fn sysroot_candidates() -> SmallVec<[PathBuf; 2]> {
195194
/// Returns the provided sysroot or calls [`get_or_default_sysroot`] if it's none.
196195
/// Panics if [`get_or_default_sysroot`] returns an error.
197196
pub fn materialize_sysroot(maybe_sysroot: Option<PathBuf>) -> PathBuf {
198-
maybe_sysroot.unwrap_or_else(|| get_or_default_sysroot().expect("Failed finding sysroot"))
197+
maybe_sysroot.unwrap_or_else(|| get_or_default_sysroot())
199198
}
200199

201200
/// This function checks if sysroot is found using env::args().next(), and if it
202201
/// is not found, finds sysroot from current rustc_driver dll.
203-
pub fn get_or_default_sysroot() -> Result<PathBuf, String> {
202+
pub fn get_or_default_sysroot() -> PathBuf {
204203
// Follow symlinks. If the resolved path is relative, make it absolute.
205204
fn canonicalize(path: PathBuf) -> PathBuf {
206205
let path = try_canonicalize(&path).unwrap_or(path);
@@ -255,30 +254,25 @@ pub fn get_or_default_sysroot() -> Result<PathBuf, String> {
255254
// binary able to locate Rust libraries in systems using content-addressable
256255
// storage (CAS).
257256
fn from_env_args_next() -> Option<PathBuf> {
258-
match env::args_os().next() {
259-
Some(first_arg) => {
260-
let mut p = PathBuf::from(first_arg);
261-
262-
// Check if sysroot is found using env::args().next() only if the rustc in argv[0]
263-
// is a symlink (see #79253). We might want to change/remove it to conform with
264-
// https://www.gnu.org/prep/standards/standards.html#Finding-Program-Files in the
265-
// future.
266-
if fs::read_link(&p).is_err() {
267-
// Path is not a symbolic link or does not exist.
268-
return None;
269-
}
270-
271-
// Pop off `bin/rustc`, obtaining the suspected sysroot.
272-
p.pop();
273-
p.pop();
274-
// Look for the target rustlib directory in the suspected sysroot.
275-
let mut rustlib_path = rustc_target::relative_target_rustlib_path(&p, "dummy");
276-
rustlib_path.pop(); // pop off the dummy target.
277-
rustlib_path.exists().then_some(p)
278-
}
279-
None => None,
257+
let mut p = PathBuf::from(env::args_os().next()?);
258+
259+
// Check if sysroot is found using env::args().next() only if the rustc in argv[0]
260+
// is a symlink (see #79253). We might want to change/remove it to conform with
261+
// https://www.gnu.org/prep/standards/standards.html#Finding-Program-Files in the
262+
// future.
263+
if fs::read_link(&p).is_err() {
264+
// Path is not a symbolic link or does not exist.
265+
return None;
280266
}
267+
268+
// Pop off `bin/rustc`, obtaining the suspected sysroot.
269+
p.pop();
270+
p.pop();
271+
// Look for the target rustlib directory in the suspected sysroot.
272+
let mut rustlib_path = rustc_target::relative_target_rustlib_path(&p, "dummy");
273+
rustlib_path.pop(); // pop off the dummy target.
274+
rustlib_path.exists().then_some(p)
281275
}
282276

283-
Ok(from_env_args_next().unwrap_or(default_from_rustc_driver_dll()?))
277+
from_env_args_next().unwrap_or(default_from_rustc_driver_dll().expect("Failed finding sysroot"))
284278
}

‎compiler/rustc_session/src/options.rs

+1-1
Original file line numberDiff line numberDiff line change
@@ -333,7 +333,7 @@ top_level_options!(
333333
output_types: OutputTypes [TRACKED],
334334
search_paths: Vec<SearchPath> [UNTRACKED],
335335
libs: Vec<NativeLib> [TRACKED],
336-
maybe_sysroot: Option<PathBuf> [UNTRACKED],
336+
sysroot: PathBuf [UNTRACKED],
337337

338338
target_triple: TargetTuple [TRACKED],
339339

‎compiler/rustc_session/src/session.rs

+1-2
Original file line numberDiff line numberDiff line change
@@ -143,7 +143,6 @@ pub struct Session {
143143
pub target: Target,
144144
pub host: Target,
145145
pub opts: config::Options,
146-
pub host_tlib_path: Arc<SearchPath>,
147146
pub target_tlib_path: Arc<SearchPath>,
148147
pub psess: ParseSess,
149148
pub sysroot: PathBuf,
@@ -1042,6 +1041,7 @@ pub fn build_session(
10421041

10431042
let host_triple = config::host_tuple();
10441043
let target_triple = sopts.target_triple.tuple();
1044+
// FIXME use host sysroot?
10451045
let host_tlib_path = Arc::new(SearchPath::from_sysroot_and_triple(&sysroot, host_triple));
10461046
let target_tlib_path = if host_triple == target_triple {
10471047
// Use the same `SearchPath` if host and target triple are identical to avoid unnecessary
@@ -1070,7 +1070,6 @@ pub fn build_session(
10701070
target,
10711071
host,
10721072
opts: sopts,
1073-
host_tlib_path,
10741073
target_tlib_path,
10751074
psess,
10761075
sysroot,

‎src/librustdoc/config.rs

+5-6
Original file line numberDiff line numberDiff line change
@@ -103,6 +103,8 @@ pub(crate) struct Options {
103103
/// compiling doctests from the crate.
104104
pub(crate) edition: Edition,
105105
/// The path to the sysroot. Used during the compilation process.
106+
pub(crate) sysroot: PathBuf,
107+
/// Has the same value as `sysroot` except is `None` when the user didn't pass `---sysroot`.
106108
pub(crate) maybe_sysroot: Option<PathBuf>,
107109
/// Lint information passed over the command-line.
108110
pub(crate) lint_opts: Vec<(String, Level)>,
@@ -202,6 +204,7 @@ impl fmt::Debug for Options {
202204
.field("unstable_options", &"...")
203205
.field("target", &self.target)
204206
.field("edition", &self.edition)
207+
.field("sysroot", &self.sysroot)
205208
.field("maybe_sysroot", &self.maybe_sysroot)
206209
.field("lint_opts", &self.lint_opts)
207210
.field("describe_lints", &self.describe_lints)
@@ -729,12 +732,7 @@ impl Options {
729732
let target = parse_target_triple(early_dcx, matches);
730733
let maybe_sysroot = matches.opt_str("sysroot").map(PathBuf::from);
731734

732-
let sysroot = match &maybe_sysroot {
733-
Some(s) => s.clone(),
734-
None => {
735-
rustc_session::filesearch::get_or_default_sysroot().expect("Failed finding sysroot")
736-
}
737-
};
735+
let sysroot = rustc_session::filesearch::materialize_sysroot(maybe_sysroot.clone());
738736

739737
let libs = matches
740738
.opt_strs("L")
@@ -834,6 +832,7 @@ impl Options {
834832
unstable_opts_strs,
835833
target,
836834
edition,
835+
sysroot,
837836
maybe_sysroot,
838837
lint_opts,
839838
describe_lints,

‎src/librustdoc/core.rs

+2-2
Original file line numberDiff line numberDiff line change
@@ -210,7 +210,7 @@ pub(crate) fn create_config(
210210
unstable_opts,
211211
target,
212212
edition,
213-
maybe_sysroot,
213+
sysroot,
214214
lint_opts,
215215
describe_lints,
216216
lint_cap,
@@ -253,7 +253,7 @@ pub(crate) fn create_config(
253253
let test = scrape_examples_options.map(|opts| opts.scrape_tests).unwrap_or(false);
254254
// plays with error output here!
255255
let sessopts = config::Options {
256-
maybe_sysroot,
256+
sysroot,
257257
search_paths: libs,
258258
crate_types,
259259
lint_opts,

‎src/librustdoc/doctest.rs

+1-1
Original file line numberDiff line numberDiff line change
@@ -158,7 +158,7 @@ pub(crate) fn run(dcx: DiagCtxtHandle<'_>, input: Input, options: RustdocOptions
158158
if options.proc_macro_crate { vec![CrateType::ProcMacro] } else { vec![CrateType::Rlib] };
159159

160160
let sessopts = config::Options {
161-
maybe_sysroot: options.maybe_sysroot.clone(),
161+
sysroot: options.sysroot.clone(),
162162
search_paths: options.libs.clone(),
163163
crate_types,
164164
lint_opts,

‎tests/ui-fulldeps/run-compiler-twice.rs

+1-1
Original file line numberDiff line numberDiff line change
@@ -46,7 +46,7 @@ fn main() {
4646
fn compile(code: String, output: PathBuf, sysroot: PathBuf, linker: Option<&Path>) {
4747
let mut opts = Options::default();
4848
opts.output_types = OutputTypes::new(&[(OutputType::Exe, None)]);
49-
opts.maybe_sysroot = Some(sysroot);
49+
opts.sysroot = sysroot;
5050

5151
if let Some(linker) = linker {
5252
opts.cg.linker = Some(linker.to_owned());

0 commit comments

Comments
 (0)
Failed to load comments.