1 use std::any::{type_name, Any};
2 use std::cell::{Cell, RefCell};
3 use std::collections::BTreeSet;
5 use std::ffi::{OsStr, OsString};
6 use std::fmt::{Debug, Write};
7 use std::fs::{self, File};
9 use std::io::{BufRead, BufReader, ErrorKind};
11 use std::path::{Component, Path, PathBuf};
12 use std::process::{Command, Stdio};
13 use std::time::{Duration, Instant};
15 use crate::cache::{Cache, Interned, INTERNER};
17 use crate::config::{SplitDebuginfo, TargetSelection};
20 use crate::flags::{Color, Subcommand};
25 use crate::tool::{self, SourceType};
26 use crate::util::{self, add_dylib_path, add_link_lib_path, exe, libdir, output, t};
27 use crate::EXTRA_CHECK_CFGS;
28 use crate::{check, Config};
29 use crate::{Build, CLang, DocTests, GitRepo, Mode};
31 pub use crate::Compiler;
32 // FIXME: replace with std::lazy after it gets stabilized and reaches beta
33 use once_cell::sync::{Lazy, OnceCell};
34 use xz2::bufread::XzDecoder;
36 pub struct Builder<'a> {
41 stack: RefCell<Vec<Box<dyn Any>>>,
42 time_spent_on_dependencies: Cell<Duration>,
43 pub paths: Vec<PathBuf>,
46 impl<'a> Deref for Builder<'a> {
49 fn deref(&self) -> &Self::Target {
54 pub trait Step: 'static + Clone + Debug + PartialEq + Eq + Hash {
55 /// `PathBuf` when directories are created or to return a `Compiler` once
56 /// it's been assembled.
59 /// Whether this step is run by default as part of its respective phase.
60 /// `true` here can still be overwritten by `should_run` calling `default_condition`.
61 const DEFAULT: bool = false;
63 /// If true, then this rule should be skipped if --target was specified, but --host was not
64 const ONLY_HOSTS: bool = false;
66 /// Primary function to execute this rule. Can call `builder.ensure()`
67 /// with other steps to run those.
68 fn run(self, builder: &Builder<'_>) -> Self::Output;
70 /// When bootstrap is passed a set of paths, this controls whether this rule
71 /// will execute. However, it does not get called in a "default" context
72 /// when we are not passed any paths; in that case, `make_run` is called
74 fn should_run(run: ShouldRun<'_>) -> ShouldRun<'_>;
76 /// Builds up a "root" rule, either as a default rule or from a path passed
79 /// When path is `None`, we are executing in a context where no paths were
80 /// passed. When `./x.py build` is run, for example, this rule could get
81 /// called if it is in the correct list below with a path of `None`.
82 fn make_run(_run: RunConfig<'_>) {
83 // It is reasonable to not have an implementation of make_run for rules
84 // who do not want to get called from the root context. This means that
85 // they are likely dependencies (e.g., sysroot creation) or similar, and
86 // as such calling them from ./x.py isn't logical.
91 pub struct RunConfig<'a> {
92 pub builder: &'a Builder<'a>,
93 pub target: TargetSelection,
98 pub fn build_triple(&self) -> TargetSelection {
99 self.builder.build.build
103 struct StepDescription {
106 should_run: fn(ShouldRun<'_>) -> ShouldRun<'_>,
107 make_run: fn(RunConfig<'_>),
112 #[derive(Clone, PartialOrd, Ord, PartialEq, Eq)]
113 pub struct TaskPath {
115 pub kind: Option<Kind>,
119 pub fn parse(path: impl Into<PathBuf>) -> TaskPath {
121 let mut path = path.into();
123 let mut components = path.components();
124 if let Some(Component::Normal(os_str)) = components.next() {
125 if let Some(str) = os_str.to_str() {
126 if let Some((found_kind, found_prefix)) = str.split_once("::") {
127 if found_kind.is_empty() {
128 panic!("empty kind in task path {}", path.display());
130 kind = Kind::parse(found_kind);
131 assert!(kind.is_some());
132 path = Path::new(found_prefix).join(components.as_path());
137 TaskPath { path, kind }
141 impl Debug for TaskPath {
142 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
143 if let Some(kind) = &self.kind {
144 write!(f, "{}::", kind.as_str())?;
146 write!(f, "{}", self.path.display())
150 /// Collection of paths used to match a task rule.
151 #[derive(Debug, Clone, PartialOrd, Ord, PartialEq, Eq)]
153 /// A collection of individual paths.
155 /// These are generally matched as a path suffix. For example, a
156 /// command-line value of `libstd` will match if `src/libstd` is in the
158 Set(BTreeSet<TaskPath>),
159 /// A "suite" of paths.
161 /// These can match as a path suffix (like `Set`), or as a prefix. For
162 /// example, a command-line value of `src/test/ui/abi/variadic-ffi.rs`
163 /// will match `src/test/ui`. A command-line value of `ui` would also
164 /// match `src/test/ui`.
169 fn empty() -> PathSet {
170 PathSet::Set(BTreeSet::new())
173 fn one<P: Into<PathBuf>>(path: P, kind: Kind) -> PathSet {
174 let mut set = BTreeSet::new();
175 set.insert(TaskPath { path: path.into(), kind: Some(kind) });
179 fn has(&self, needle: &Path, module: Option<Kind>) -> bool {
180 let check = |p: &TaskPath| {
181 if let (Some(p_kind), Some(kind)) = (&p.kind, module) {
182 p.path.ends_with(needle) && *p_kind == kind
184 p.path.ends_with(needle)
189 PathSet::Set(set) => set.iter().any(check),
190 PathSet::Suite(suite) => check(suite),
194 fn path(&self, builder: &Builder<'_>) -> PathBuf {
196 PathSet::Set(set) => {
197 set.iter().next().map(|p| &p.path).unwrap_or(&builder.build.src).clone()
199 PathSet::Suite(path) => path.path.clone(),
204 impl StepDescription {
205 fn from<S: Step>(kind: Kind) -> StepDescription {
208 only_hosts: S::ONLY_HOSTS,
209 should_run: S::should_run,
210 make_run: S::make_run,
211 name: std::any::type_name::<S>(),
216 fn maybe_run(&self, builder: &Builder<'_>, pathset: &PathSet) {
217 if self.is_excluded(builder, pathset) {
221 // Determine the targets participating in this rule.
222 let targets = if self.only_hosts { &builder.hosts } else { &builder.targets };
224 for target in targets {
225 let run = RunConfig { builder, path: pathset.path(builder), target: *target };
226 (self.make_run)(run);
230 fn is_excluded(&self, builder: &Builder<'_>, pathset: &PathSet) -> bool {
231 if builder.config.exclude.iter().any(|e| pathset.has(&e.path, e.kind)) {
232 println!("Skipping {:?} because it is excluded", pathset);
236 if !builder.config.exclude.is_empty() {
237 builder.verbose(&format!(
238 "{:?} not skipped for {:?} -- not in {:?}",
239 pathset, self.name, builder.config.exclude
245 fn run(v: &[StepDescription], builder: &Builder<'_>, paths: &[PathBuf]) {
248 .map(|desc| (desc.should_run)(ShouldRun::new(builder, desc.kind)))
249 .collect::<Vec<_>>();
251 // sanity checks on rules
252 for (desc, should_run) in v.iter().zip(&should_runs) {
254 !should_run.paths.is_empty(),
255 "{:?} should have at least one pathset",
260 if paths.is_empty() || builder.config.include_default_paths {
261 for (desc, should_run) in v.iter().zip(&should_runs) {
262 if desc.default && should_run.is_really_default() {
263 for pathset in &should_run.paths {
264 desc.maybe_run(builder, pathset);
271 // strip CurDir prefix if present
272 let path = match path.strip_prefix(".") {
277 let mut attempted_run = false;
278 for (desc, should_run) in v.iter().zip(&should_runs) {
279 if let Some(suite) = should_run.is_suite_path(path) {
280 attempted_run = true;
281 desc.maybe_run(builder, suite);
282 } else if let Some(pathset) = should_run.pathset_for_path(path, desc.kind) {
283 attempted_run = true;
284 desc.maybe_run(builder, pathset);
290 "error: no `{}` rules matched '{}'",
291 builder.kind.as_str(),
295 "help: run `x.py {} --help --verbose` to show a list of available paths",
296 builder.kind.as_str()
299 "note: if you are adding a new Step to bootstrap itself, make sure you register it with `describe!`"
301 std::process::exit(1);
307 enum ReallyDefault<'a> {
309 Lazy(Lazy<bool, Box<dyn Fn() -> bool + 'a>>),
312 pub struct ShouldRun<'a> {
313 pub builder: &'a Builder<'a>,
316 // use a BTreeSet to maintain sort order
317 paths: BTreeSet<PathSet>,
319 // If this is a default rule, this is an additional constraint placed on
320 // its run. Generally something like compiler docs being enabled.
321 is_really_default: ReallyDefault<'a>,
324 impl<'a> ShouldRun<'a> {
325 fn new(builder: &'a Builder<'_>, kind: Kind) -> ShouldRun<'a> {
329 paths: BTreeSet::new(),
330 is_really_default: ReallyDefault::Bool(true), // by default no additional conditions
334 pub fn default_condition(mut self, cond: bool) -> Self {
335 self.is_really_default = ReallyDefault::Bool(cond);
339 pub fn lazy_default_condition(mut self, lazy_cond: Box<dyn Fn() -> bool + 'a>) -> Self {
340 self.is_really_default = ReallyDefault::Lazy(Lazy::new(lazy_cond));
344 pub fn is_really_default(&self) -> bool {
345 match &self.is_really_default {
346 ReallyDefault::Bool(val) => *val,
347 ReallyDefault::Lazy(lazy) => *lazy.deref(),
351 /// Indicates it should run if the command-line selects the given crate or
352 /// any of its (local) dependencies.
354 /// Compared to `krate`, this treats the dependencies as aliases for the
355 /// same job. Generally it is preferred to use `krate`, and treat each
356 /// individual path separately. For example `./x.py test src/liballoc`
357 /// (which uses `krate`) will test just `liballoc`. However, `./x.py check
358 /// src/liballoc` (which uses `all_krates`) will check all of `libtest`.
359 /// `all_krates` should probably be removed at some point.
360 pub fn all_krates(mut self, name: &str) -> Self {
361 let mut set = BTreeSet::new();
362 for krate in self.builder.in_tree_crates(name, None) {
363 let path = krate.local_path(self.builder);
364 set.insert(TaskPath { path, kind: Some(self.kind) });
366 self.paths.insert(PathSet::Set(set));
370 /// Indicates it should run if the command-line selects the given crate or
371 /// any of its (local) dependencies.
373 /// `make_run` will be called separately for each matching command-line path.
374 pub fn krate(mut self, name: &str) -> Self {
375 for krate in self.builder.in_tree_crates(name, None) {
376 let path = krate.local_path(self.builder);
377 self.paths.insert(PathSet::one(path, self.kind));
382 // single alias, which does not correspond to any on-disk path
383 pub fn alias(mut self, alias: &str) -> Self {
385 !self.builder.src.join(alias).exists(),
386 "use `builder.path()` for real paths: {}",
389 self.paths.insert(PathSet::Set(
390 std::iter::once(TaskPath { path: alias.into(), kind: Some(self.kind) }).collect(),
395 // single, non-aliased path
396 pub fn path(self, path: &str) -> Self {
400 // multiple aliases for the same job
401 pub fn paths(mut self, paths: &[&str]) -> Self {
402 self.paths.insert(PathSet::Set(
406 // FIXME(#96188): make sure this is actually a path.
407 // This currently breaks for paths within submodules.
409 // self.builder.src.join(p).exists(),
410 // "`should_run.paths` should correspond to real on-disk paths - use `alias` if there is no relevant path: {}",
413 TaskPath { path: p.into(), kind: Some(self.kind) }
420 pub fn is_suite_path(&self, path: &Path) -> Option<&PathSet> {
421 self.paths.iter().find(|pathset| match pathset {
422 PathSet::Suite(p) => path.starts_with(&p.path),
423 PathSet::Set(_) => false,
427 pub fn suite_path(mut self, suite: &str) -> Self {
428 self.paths.insert(PathSet::Suite(TaskPath { path: suite.into(), kind: Some(self.kind) }));
432 // allows being more explicit about why should_run in Step returns the value passed to it
433 pub fn never(mut self) -> ShouldRun<'a> {
434 self.paths.insert(PathSet::empty());
438 fn pathset_for_path(&self, path: &Path, kind: Kind) -> Option<&PathSet> {
439 self.paths.iter().find(|pathset| pathset.has(path, Some(kind)))
443 #[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Debug)]
461 pub fn parse(string: &str) -> Option<Kind> {
462 // these strings, including the one-letter aliases, must match the x.py help text
464 "build" | "b" => Kind::Build,
465 "check" | "c" => Kind::Check,
466 "clippy" => Kind::Clippy,
468 "fmt" => Kind::Format,
469 "test" | "t" => Kind::Test,
470 "bench" => Kind::Bench,
471 "doc" | "d" => Kind::Doc,
472 "clean" => Kind::Clean,
473 "dist" => Kind::Dist,
474 "install" => Kind::Install,
475 "run" | "r" => Kind::Run,
476 "setup" => Kind::Setup,
481 pub fn as_str(&self) -> &'static str {
483 Kind::Build => "build",
484 Kind::Check => "check",
485 Kind::Clippy => "clippy",
487 Kind::Format => "fmt",
488 Kind::Test => "test",
489 Kind::Bench => "bench",
491 Kind::Clean => "clean",
492 Kind::Dist => "dist",
493 Kind::Install => "install",
495 Kind::Setup => "setup",
500 impl<'a> Builder<'a> {
501 fn get_step_descriptions(kind: Kind) -> Vec<StepDescription> {
502 macro_rules! describe {
503 ($($rule:ty),+ $(,)?) => {{
504 vec![$(StepDescription::from::<$rule>(kind)),+]
508 Kind::Build => describe!(
511 compile::CodegenBackend,
512 compile::StartupObjects,
516 tool::UnstableBookGen,
521 tool::RemoteTestServer,
522 tool::RemoteTestClient,
539 Kind::Check | Kind::Clippy | Kind::Fix => describe!(
543 check::CodegenBackend,
550 Kind::Test => describe!(
551 crate::toolstate::ToolStateCheck,
552 test::ExpandYamlAnchors,
555 test::RunPassValgrind,
568 test::CrateRustdocJsonTypes,
576 test::RunMakeFullDeps,
592 test::CompiletestTest,
594 test::RustdocJSNotStd,
600 // Run bootstrap close to the end as it's unlikely to fail
602 // Run run-make last, since these won't pass without make on Windows
605 Kind::Bench => describe!(test::Crate, test::CrateLibrustc),
606 Kind::Doc => describe!(
608 doc::UnstableBookGen,
626 Kind::Dist => describe!(
645 // It seems that PlainSourceTarball somehow changes how some of the tools
646 // perceive their dependencies (see #93033) which would invalidate fingerprints
647 // and force us to rebuild tools after vendoring dependencies.
648 // To work around this, create the Tarball after building all the tools.
649 dist::PlainSourceTarball,
651 dist::ReproducibleArtifacts,
653 Kind::Install => describe!(
658 install::RustAnalyzer,
660 install::RustDemangler,
667 Kind::Run => describe!(run::ExpandYamlAnchors, run::BuildManifest, run::BumpStage0),
668 // These commands either don't use paths, or they're special-cased in Build::build()
669 Kind::Clean | Kind::Format | Kind::Setup => vec![],
673 pub fn get_help(build: &Build, kind: Kind) -> Option<String> {
674 let step_descriptions = Builder::get_step_descriptions(kind);
675 if step_descriptions.is_empty() {
679 let builder = Self::new_internal(build, kind, vec![]);
680 let builder = &builder;
681 // The "build" kind here is just a placeholder, it will be replaced with something else in
682 // the following statement.
683 let mut should_run = ShouldRun::new(builder, Kind::Build);
684 for desc in step_descriptions {
685 should_run.kind = desc.kind;
686 should_run = (desc.should_run)(should_run);
688 let mut help = String::from("Available paths:\n");
689 let mut add_path = |path: &Path| {
690 t!(write!(help, " ./x.py {} {}\n", kind.as_str(), path.display()));
692 for pathset in should_run.paths {
694 PathSet::Set(set) => {
696 add_path(&path.path);
699 PathSet::Suite(path) => {
700 add_path(&path.path.join("..."));
707 fn new_internal(build: &Build, kind: Kind, paths: Vec<PathBuf>) -> Builder<'_> {
710 top_stage: build.config.stage,
713 stack: RefCell::new(Vec::new()),
714 time_spent_on_dependencies: Cell::new(Duration::new(0, 0)),
719 pub fn new(build: &Build) -> Builder<'_> {
720 let (kind, paths) = match build.config.cmd {
721 Subcommand::Build { ref paths } => (Kind::Build, &paths[..]),
722 Subcommand::Check { ref paths } => (Kind::Check, &paths[..]),
723 Subcommand::Clippy { ref paths, .. } => (Kind::Clippy, &paths[..]),
724 Subcommand::Fix { ref paths } => (Kind::Fix, &paths[..]),
725 Subcommand::Doc { ref paths, .. } => (Kind::Doc, &paths[..]),
726 Subcommand::Test { ref paths, .. } => (Kind::Test, &paths[..]),
727 Subcommand::Bench { ref paths, .. } => (Kind::Bench, &paths[..]),
728 Subcommand::Dist { ref paths } => (Kind::Dist, &paths[..]),
729 Subcommand::Install { ref paths } => (Kind::Install, &paths[..]),
730 Subcommand::Run { ref paths } => (Kind::Run, &paths[..]),
731 Subcommand::Format { .. } | Subcommand::Clean { .. } | Subcommand::Setup { .. } => {
736 Self::new_internal(build, kind, paths.to_owned())
739 pub fn execute_cli(&self) {
740 self.run_step_descriptions(&Builder::get_step_descriptions(self.kind), &self.paths);
743 pub fn default_doc(&self, paths: &[PathBuf]) {
744 self.run_step_descriptions(&Builder::get_step_descriptions(Kind::Doc), paths);
747 /// NOTE: keep this in sync with `rustdoc::clean::utils::doc_rust_lang_org_channel`, or tests will fail on beta/stable.
748 pub fn doc_rust_lang_org_channel(&self) -> String {
749 let channel = match &*self.config.channel {
750 "stable" => &self.version,
752 "nightly" | "dev" => "nightly",
753 // custom build of rustdoc maybe? link to the latest stable docs just in case
756 "https://doc.rust-lang.org/".to_owned() + channel
759 fn run_step_descriptions(&self, v: &[StepDescription], paths: &[PathBuf]) {
760 StepDescription::run(v, self, paths);
763 /// Modifies the interpreter section of 'fname' to fix the dynamic linker,
764 /// or the RPATH section, to fix the dynamic library search path
766 /// This is only required on NixOS and uses the PatchELF utility to
767 /// change the interpreter/RPATH of ELF executables.
769 /// Please see https://nixos.org/patchelf.html for more information
770 pub(crate) fn fix_bin_or_dylib(&self, fname: &Path) {
771 // FIXME: cache NixOS detection?
772 match Command::new("uname").arg("-s").stderr(Stdio::inherit()).output() {
774 Ok(output) if !output.status.success() => return,
776 let mut s = output.stdout;
777 if s.last() == Some(&b'\n') {
786 // If the user has asked binaries to be patched for Nix, then
787 // don't check for NixOS or `/lib`, just continue to the patching.
788 // NOTE: this intentionally comes after the Linux check:
789 // - patchelf only works with ELF files, so no need to run it on Mac or Windows
790 // - On other Unix systems, there is no stable syscall interface, so Nix doesn't manage the global libc.
791 if !self.config.patch_binaries_for_nix {
792 // Use `/etc/os-release` instead of `/etc/NIXOS`.
793 // The latter one does not exist on NixOS when using tmpfs as root.
794 const NIX_IDS: &[&str] = &["ID=nixos", "ID='nixos'", "ID=\"nixos\""];
795 let os_release = match File::open("/etc/os-release") {
796 Err(e) if e.kind() == ErrorKind::NotFound => return,
797 Err(e) => panic!("failed to access /etc/os-release: {}", e),
800 if !BufReader::new(os_release).lines().any(|l| NIX_IDS.contains(&t!(l).trim())) {
803 if Path::new("/lib").exists() {
808 // At this point we're pretty sure the user is running NixOS or using Nix
809 println!("info: you seem to be using Nix. Attempting to patch {}", fname.display());
811 // Only build `.nix-deps` once.
812 static NIX_DEPS_DIR: OnceCell<PathBuf> = OnceCell::new();
813 let mut nix_build_succeeded = true;
814 let nix_deps_dir = NIX_DEPS_DIR.get_or_init(|| {
815 // Run `nix-build` to "build" each dependency (which will likely reuse
816 // the existing `/nix/store` copy, or at most download a pre-built copy).
818 // Importantly, we create a gc-root called `.nix-deps` in the `build/`
819 // directory, but still reference the actual `/nix/store` path in the rpath
820 // as it makes it significantly more robust against changes to the location of
821 // the `.nix-deps` location.
823 // bintools: Needed for the path of `ld-linux.so` (via `nix-support/dynamic-linker`).
824 // zlib: Needed as a system dependency of `libLLVM-*.so`.
825 // patchelf: Needed for patching ELF binaries (see doc comment above).
826 let nix_deps_dir = self.out.join(".nix-deps");
827 const NIX_EXPR: &str = "
828 with (import <nixpkgs> {});
830 name = \"rust-stage0-dependencies\";
838 nix_build_succeeded = self.try_run(Command::new("nix-build").args(&[
846 if !nix_build_succeeded {
850 let mut patchelf = Command::new(nix_deps_dir.join("bin/patchelf"));
851 let rpath_entries = {
852 // ORIGIN is a relative default, all binary and dynamic libraries we ship
853 // appear to have this (even when `../lib` is redundant).
854 // NOTE: there are only two paths here, delimited by a `:`
855 let mut entries = OsString::from("$ORIGIN/../lib:");
856 entries.push(t!(fs::canonicalize(nix_deps_dir)));
857 entries.push("/lib");
860 patchelf.args(&[OsString::from("--set-rpath"), rpath_entries]);
861 if !fname.extension().map_or(false, |ext| ext == "so") {
862 // Finally, set the corret .interp for binaries
863 let dynamic_linker_path = nix_deps_dir.join("nix-support/dynamic-linker");
864 // FIXME: can we support utf8 here? `args` doesn't accept Vec<u8>, only OsString ...
865 let dynamic_linker = t!(String::from_utf8(t!(fs::read(dynamic_linker_path))));
866 patchelf.args(&["--set-interpreter", dynamic_linker.trim_end()]);
869 self.try_run(patchelf.arg(fname));
872 pub(crate) fn download_component(
879 // Use a temporary file in case we crash while downloading, to avoid a corrupt download in cache/.
880 let tempfile = self.tempdir().join(dest_path.file_name().unwrap());
881 // FIXME: support `do_verify` (only really needed for nightly rustfmt)
882 self.download_with_retries(&tempfile, &format!("{}/{}", base, url), help_on_error);
883 t!(std::fs::rename(&tempfile, dest_path));
886 fn download_with_retries(&self, tempfile: &Path, url: &str, help_on_error: &str) {
887 println!("downloading {}", url);
888 // Try curl. If that fails and we are on windows, fallback to PowerShell.
889 let mut curl = Command::new("curl");
895 "10", // timeout if speed is < 10 bytes/sec for > 30 seconds
897 "30", // timeout if cannot connect within 30 seconds
905 if !self.check_run(&mut curl) {
906 if self.build.build.contains("windows-msvc") {
907 println!("Fallback to PowerShell");
909 if self.try_run(Command::new("PowerShell.exe").args(&[
912 "[Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12;",
914 "(New-Object System.Net.WebClient).DownloadFile('{}', '{}')",
915 url, tempfile.to_str().expect("invalid UTF-8 not supported with powershell downloads"),
920 println!("\nspurious failure, trying again");
923 if !help_on_error.is_empty() {
924 eprintln!("{}", help_on_error);
926 std::process::exit(1);
930 pub(crate) fn unpack(&self, tarball: &Path, dst: &Path, pattern: &str) {
931 println!("extracting {} to {}", tarball.display(), dst.display());
933 t!(fs::create_dir_all(dst));
936 // `tarball` ends with `.tar.xz`; strip that suffix
937 // example: `rust-dev-nightly-x86_64-unknown-linux-gnu`
938 let uncompressed_filename =
939 Path::new(tarball.file_name().expect("missing tarball filename")).file_stem().unwrap();
940 let directory_prefix = Path::new(Path::new(uncompressed_filename).file_stem().unwrap());
942 // decompress the file
943 let data = t!(File::open(tarball));
944 let decompressor = XzDecoder::new(BufReader::new(data));
946 let mut tar = tar::Archive::new(decompressor);
947 for member in t!(tar.entries()) {
948 let mut member = t!(member);
949 let original_path = t!(member.path()).into_owned();
950 // skip the top-level directory
951 if original_path == directory_prefix {
954 let mut short_path = t!(original_path.strip_prefix(directory_prefix));
955 if !short_path.starts_with(pattern) {
958 short_path = t!(short_path.strip_prefix(pattern));
959 let dst_path = dst.join(short_path);
960 self.verbose(&format!("extracting {} to {}", original_path.display(), dst.display()));
961 if !t!(member.unpack_in(dst)) {
962 panic!("path traversal attack ??");
964 let src_path = dst.join(original_path);
965 if src_path.is_dir() && dst_path.exists() {
968 t!(fs::rename(src_path, dst_path));
970 t!(fs::remove_dir_all(dst.join(directory_prefix)));
973 /// Obtain a compiler at a given stage and for a given host. Explicitly does
974 /// not take `Compiler` since all `Compiler` instances are meant to be
975 /// obtained through this function, since it ensures that they are valid
976 /// (i.e., built and assembled).
977 pub fn compiler(&self, stage: u32, host: TargetSelection) -> Compiler {
978 self.ensure(compile::Assemble { target_compiler: Compiler { stage, host } })
981 /// Similar to `compiler`, except handles the full-bootstrap option to
982 /// silently use the stage1 compiler instead of a stage2 compiler if one is
985 /// Note that this does *not* have the side effect of creating
986 /// `compiler(stage, host)`, unlike `compiler` above which does have such
987 /// a side effect. The returned compiler here can only be used to compile
988 /// new artifacts, it can't be used to rely on the presence of a particular
991 /// See `force_use_stage1` for documentation on what each argument is.
995 host: TargetSelection,
996 target: TargetSelection,
998 if self.build.force_use_stage1(Compiler { stage, host }, target) {
999 self.compiler(1, self.config.build)
1001 self.compiler(stage, host)
1005 pub fn sysroot(&self, compiler: Compiler) -> Interned<PathBuf> {
1006 self.ensure(compile::Sysroot { compiler })
1009 /// Returns the libdir where the standard library and other artifacts are
1010 /// found for a compiler's sysroot.
1011 pub fn sysroot_libdir(&self, compiler: Compiler, target: TargetSelection) -> Interned<PathBuf> {
1012 #[derive(Debug, Copy, Clone, Hash, PartialEq, Eq)]
1015 target: TargetSelection,
1017 impl Step for Libdir {
1018 type Output = Interned<PathBuf>;
1020 fn should_run(run: ShouldRun<'_>) -> ShouldRun<'_> {
1024 fn run(self, builder: &Builder<'_>) -> Interned<PathBuf> {
1025 let lib = builder.sysroot_libdir_relative(self.compiler);
1026 let sysroot = builder
1027 .sysroot(self.compiler)
1030 .join(self.target.triple)
1032 // Avoid deleting the rustlib/ directory we just copied
1033 // (in `impl Step for Sysroot`).
1034 if !builder.download_rustc() {
1035 let _ = fs::remove_dir_all(&sysroot);
1036 t!(fs::create_dir_all(&sysroot));
1038 INTERNER.intern_path(sysroot)
1041 self.ensure(Libdir { compiler, target })
1044 pub fn sysroot_codegen_backends(&self, compiler: Compiler) -> PathBuf {
1045 self.sysroot_libdir(compiler, compiler.host).with_file_name("codegen-backends")
1048 /// Returns the compiler's libdir where it stores the dynamic libraries that
1049 /// it itself links against.
1051 /// For example this returns `<sysroot>/lib` on Unix and `<sysroot>/bin` on
1053 pub fn rustc_libdir(&self, compiler: Compiler) -> PathBuf {
1054 if compiler.is_snapshot(self) {
1055 self.rustc_snapshot_libdir()
1057 match self.config.libdir_relative() {
1058 Some(relative_libdir) if compiler.stage >= 1 => {
1059 self.sysroot(compiler).join(relative_libdir)
1061 _ => self.sysroot(compiler).join(libdir(compiler.host)),
1066 /// Returns the compiler's relative libdir where it stores the dynamic libraries that
1067 /// it itself links against.
1069 /// For example this returns `lib` on Unix and `bin` on
1071 pub fn libdir_relative(&self, compiler: Compiler) -> &Path {
1072 if compiler.is_snapshot(self) {
1073 libdir(self.config.build).as_ref()
1075 match self.config.libdir_relative() {
1076 Some(relative_libdir) if compiler.stage >= 1 => relative_libdir,
1077 _ => libdir(compiler.host).as_ref(),
1082 /// Returns the compiler's relative libdir where the standard library and other artifacts are
1083 /// found for a compiler's sysroot.
1085 /// For example this returns `lib` on Unix and Windows.
1086 pub fn sysroot_libdir_relative(&self, compiler: Compiler) -> &Path {
1087 match self.config.libdir_relative() {
1088 Some(relative_libdir) if compiler.stage >= 1 => relative_libdir,
1089 _ if compiler.stage == 0 => &self.build.initial_libdir,
1090 _ => Path::new("lib"),
1094 pub fn rustc_lib_paths(&self, compiler: Compiler) -> Vec<PathBuf> {
1095 let mut dylib_dirs = vec![self.rustc_libdir(compiler)];
1097 // Ensure that the downloaded LLVM libraries can be found.
1098 if self.config.llvm_from_ci {
1099 let ci_llvm_lib = self.out.join(&*compiler.host.triple).join("ci-llvm").join("lib");
1100 dylib_dirs.push(ci_llvm_lib);
1106 /// Adds the compiler's directory of dynamic libraries to `cmd`'s dynamic
1107 /// library lookup path.
1108 pub fn add_rustc_lib_path(&self, compiler: Compiler, cmd: &mut Command) {
1109 // Windows doesn't need dylib path munging because the dlls for the
1110 // compiler live next to the compiler and the system will find them
1116 add_dylib_path(self.rustc_lib_paths(compiler), cmd);
1119 /// Gets a path to the compiler specified.
1120 pub fn rustc(&self, compiler: Compiler) -> PathBuf {
1121 if compiler.is_snapshot(self) {
1122 self.initial_rustc.clone()
1124 self.sysroot(compiler).join("bin").join(exe("rustc", compiler.host))
1128 /// Gets the paths to all of the compiler's codegen backends.
1129 fn codegen_backends(&self, compiler: Compiler) -> impl Iterator<Item = PathBuf> {
1130 fs::read_dir(self.sysroot_codegen_backends(compiler))
1133 .filter_map(Result::ok)
1134 .map(|entry| entry.path())
1137 pub fn rustdoc(&self, compiler: Compiler) -> PathBuf {
1138 self.ensure(tool::Rustdoc { compiler })
1141 pub fn rustdoc_cmd(&self, compiler: Compiler) -> Command {
1142 let mut cmd = Command::new(&self.bootstrap_out.join("rustdoc"));
1143 cmd.env("RUSTC_STAGE", compiler.stage.to_string())
1144 .env("RUSTC_SYSROOT", self.sysroot(compiler))
1145 // Note that this is *not* the sysroot_libdir because rustdoc must be linked
1146 // equivalently to rustc.
1147 .env("RUSTDOC_LIBDIR", self.rustc_libdir(compiler))
1148 .env("CFG_RELEASE_CHANNEL", &self.config.channel)
1149 .env("RUSTDOC_REAL", self.rustdoc(compiler))
1150 .env("RUSTC_BOOTSTRAP", "1");
1152 cmd.arg("-Wrustdoc::invalid_codeblock_attributes");
1154 if self.config.deny_warnings {
1155 cmd.arg("-Dwarnings");
1157 cmd.arg("-Znormalize-docs");
1159 // Remove make-related flags that can cause jobserver problems.
1160 cmd.env_remove("MAKEFLAGS");
1161 cmd.env_remove("MFLAGS");
1163 if let Some(linker) = self.linker(compiler.host) {
1164 cmd.env("RUSTDOC_LINKER", linker);
1166 if self.is_fuse_ld_lld(compiler.host) {
1167 cmd.env("RUSTDOC_FUSE_LD_LLD", "1");
1172 /// Return the path to `llvm-config` for the target, if it exists.
1174 /// Note that this returns `None` if LLVM is disabled, or if we're in a
1175 /// check build or dry-run, where there's no need to build all of LLVM.
1176 fn llvm_config(&self, target: TargetSelection) -> Option<PathBuf> {
1177 if self.config.llvm_enabled() && self.kind != Kind::Check && !self.config.dry_run {
1178 let llvm_config = self.ensure(native::Llvm { target });
1179 if llvm_config.is_file() {
1180 return Some(llvm_config);
1186 /// Convenience wrapper to allow `builder.llvm_link_shared()` instead of `builder.config.llvm_link_shared(&builder)`.
1187 pub(crate) fn llvm_link_shared(&self) -> bool {
1188 Config::llvm_link_shared(self)
1191 pub(crate) fn download_rustc(&self) -> bool {
1192 Config::download_rustc(self)
1195 /// Prepares an invocation of `cargo` to be run.
1197 /// This will create a `Command` that represents a pending execution of
1198 /// Cargo. This cargo will be configured to use `compiler` as the actual
1199 /// rustc compiler, its output will be scoped by `mode`'s output directory,
1200 /// it will pass the `--target` flag for the specified `target`, and will be
1201 /// executing the Cargo command `cmd`.
1206 source_type: SourceType,
1207 target: TargetSelection,
1210 let mut cargo = Command::new(&self.initial_cargo);
1211 let out_dir = self.stage_out(compiler, mode);
1213 // Codegen backends are not yet tracked by -Zbinary-dep-depinfo,
1214 // so we need to explicitly clear out if they've been updated.
1215 for backend in self.codegen_backends(compiler) {
1216 self.clear_if_dirty(&out_dir, &backend);
1219 if cmd == "doc" || cmd == "rustdoc" {
1220 let my_out = match mode {
1221 // This is the intended out directory for compiler documentation.
1222 Mode::Rustc | Mode::ToolRustc => self.compiler_doc_out(target),
1223 Mode::Std => out_dir.join(target.triple).join("doc"),
1224 _ => panic!("doc mode {:?} not expected", mode),
1226 let rustdoc = self.rustdoc(compiler);
1227 self.clear_if_dirty(&my_out, &rustdoc);
1230 cargo.env("CARGO_TARGET_DIR", &out_dir).arg(cmd);
1232 let profile_var = |name: &str| {
1233 let profile = if self.config.rust_optimize { "RELEASE" } else { "DEV" };
1234 format!("CARGO_PROFILE_{}_{}", profile, name)
1237 // See comment in rustc_llvm/build.rs for why this is necessary, largely llvm-config
1238 // needs to not accidentally link to libLLVM in stage0/lib.
1239 cargo.env("REAL_LIBRARY_PATH_VAR", &util::dylib_path_var());
1240 if let Some(e) = env::var_os(util::dylib_path_var()) {
1241 cargo.env("REAL_LIBRARY_PATH", e);
1244 // Found with `rg "init_env_logger\("`. If anyone uses `init_env_logger`
1245 // from out of tree it shouldn't matter, since x.py is only used for
1246 // building in-tree.
1247 let color_logs = ["RUSTDOC_LOG_COLOR", "RUSTC_LOG_COLOR", "RUST_LOG_COLOR"];
1248 match self.build.config.color {
1250 cargo.arg("--color=always");
1251 for log in &color_logs {
1252 cargo.env(log, "always");
1256 cargo.arg("--color=never");
1257 for log in &color_logs {
1258 cargo.env(log, "never");
1261 Color::Auto => {} // nothing to do
1264 if cmd != "install" {
1265 cargo.arg("--target").arg(target.rustc_target_arg());
1267 assert_eq!(target, compiler.host);
1270 // Set a flag for `check`/`clippy`/`fix`, so that certain build
1271 // scripts can do less work (i.e. not building/requiring LLVM).
1272 if cmd == "check" || cmd == "clippy" || cmd == "fix" {
1273 // If we've not yet built LLVM, or it's stale, then bust
1274 // the rustc_llvm cache. That will always work, even though it
1275 // may mean that on the next non-check build we'll need to rebuild
1276 // rustc_llvm. But if LLVM is stale, that'll be a tiny amount
1277 // of work comparatively, and we'd likely need to rebuild it anyway,
1279 if crate::native::prebuilt_llvm_config(self, target).is_err() {
1280 cargo.env("RUST_CHECK", "1");
1284 let stage = if compiler.stage == 0 && self.local_rebuild {
1285 // Assume the local-rebuild rustc already has stage1 features.
1291 let mut rustflags = Rustflags::new(target);
1293 if let Ok(s) = env::var("CARGOFLAGS_NOT_BOOTSTRAP") {
1294 cargo.args(s.split_whitespace());
1296 rustflags.env("RUSTFLAGS_NOT_BOOTSTRAP");
1298 if let Ok(s) = env::var("CARGOFLAGS_BOOTSTRAP") {
1299 cargo.args(s.split_whitespace());
1301 rustflags.env("RUSTFLAGS_BOOTSTRAP");
1302 if cmd == "clippy" {
1303 // clippy overwrites sysroot if we pass it to cargo.
1304 // Pass it directly to clippy instead.
1305 // NOTE: this can't be fixed in clippy because we explicitly don't set `RUSTC`,
1306 // so it has no way of knowing the sysroot.
1307 rustflags.arg("--sysroot");
1309 self.sysroot(compiler)
1312 .expect("sysroot must be valid UTF-8"),
1314 // Only run clippy on a very limited subset of crates (in particular, not build scripts).
1315 cargo.arg("-Zunstable-options");
1316 // Explicitly does *not* set `--cfg=bootstrap`, since we're using a nightly clippy.
1317 let host_version = Command::new("rustc").arg("--version").output().map_err(|_| ());
1318 let output = host_version.and_then(|output| {
1319 if output.status.success() {
1324 }).unwrap_or_else(|_| {
1326 "error: `x.py clippy` requires a host `rustc` toolchain with the `clippy` component"
1328 eprintln!("help: try `rustup component add clippy`");
1329 std::process::exit(1);
1331 if !t!(std::str::from_utf8(&output.stdout)).contains("nightly") {
1332 rustflags.arg("--cfg=bootstrap");
1335 rustflags.arg("--cfg=bootstrap");
1339 let use_new_symbol_mangling = match self.config.rust_new_symbol_mangling {
1341 // If an explicit setting is given, use that
1345 if mode == Mode::Std {
1346 // The standard library defaults to the legacy scheme
1349 // The compiler and tools default to the new scheme
1355 if use_new_symbol_mangling {
1356 rustflags.arg("-Csymbol-mangling-version=v0");
1358 rustflags.arg("-Csymbol-mangling-version=legacy");
1359 rustflags.arg("-Zunstable-options");
1362 // FIXME(Urgau): This a hack as it shouldn't be gated on stage 0 but until `rustc_llvm`
1363 // is made to work with `--check-cfg` which is currently not easly possible until cargo
1364 // get some support for setting `--check-cfg` within build script, it's the least invasive
1365 // hack that still let's us have cfg checking for the vast majority of the codebase.
1367 // Enable cfg checking of cargo features for everything but std and also enable cfg
1368 // checking of names and values.
1370 // Note: `std`, `alloc` and `core` imports some dependencies by #[path] (like
1371 // backtrace, core_simd, std_float, ...), those dependencies have their own
1372 // features but cargo isn't involved in the #[path] process and so cannot pass the
1373 // complete list of features, so for that reason we don't enable checking of
1374 // features for std crates.
1375 cargo.arg(if mode != Mode::Std {
1376 "-Zcheck-cfg=names,values,features"
1378 "-Zcheck-cfg=names,values"
1381 // Add extra cfg not defined in/by rustc
1383 // Note: Altrough it would seems that "-Zunstable-options" to `rustflags` is useless as
1384 // cargo would implicitly add it, it was discover that sometimes bootstrap only use
1385 // `rustflags` without `cargo` making it required.
1386 rustflags.arg("-Zunstable-options");
1387 for (restricted_mode, name, values) in EXTRA_CHECK_CFGS {
1388 if *restricted_mode == None || *restricted_mode == Some(mode) {
1389 // Creating a string of the values by concatenating each value:
1390 // ',"tvos","watchos"' or '' (nothing) when there are no values
1391 let values = match values {
1392 Some(values) => values
1394 .map(|val| [",", "\"", val, "\""])
1396 .collect::<String>(),
1397 None => String::new(),
1399 rustflags.arg(&format!("--check-cfg=values({name}{values})"));
1404 // FIXME: It might be better to use the same value for both `RUSTFLAGS` and `RUSTDOCFLAGS`,
1405 // but this breaks CI. At the very least, stage0 `rustdoc` needs `--cfg bootstrap`. See
1407 let mut rustdocflags = rustflags.clone();
1408 rustdocflags.propagate_cargo_env("RUSTDOCFLAGS");
1410 rustdocflags.env("RUSTDOCFLAGS_BOOTSTRAP");
1412 rustdocflags.env("RUSTDOCFLAGS_NOT_BOOTSTRAP");
1415 if let Ok(s) = env::var("CARGOFLAGS") {
1416 cargo.args(s.split_whitespace());
1420 Mode::Std | Mode::ToolBootstrap | Mode::ToolStd => {}
1421 Mode::Rustc | Mode::Codegen | Mode::ToolRustc => {
1422 // Build proc macros both for the host and the target
1423 if target != compiler.host && cmd != "check" {
1424 cargo.arg("-Zdual-proc-macros");
1425 rustflags.arg("-Zdual-proc-macros");
1430 // This tells Cargo (and in turn, rustc) to output more complete
1431 // dependency information. Most importantly for rustbuild, this
1432 // includes sysroot artifacts, like libstd, which means that we don't
1433 // need to track those in rustbuild (an error prone process!). This
1434 // feature is currently unstable as there may be some bugs and such, but
1435 // it represents a big improvement in rustbuild's reliability on
1436 // rebuilds, so we're using it here.
1438 // For some additional context, see #63470 (the PR originally adding
1439 // this), as well as #63012 which is the tracking issue for this
1440 // feature on the rustc side.
1441 cargo.arg("-Zbinary-dep-depinfo");
1443 Mode::ToolBootstrap => {
1444 // Restrict the allowed features to those passed by rustbuild, so we don't depend on nightly accidentally.
1445 // HACK: because anyhow does feature detection in build.rs, we need to allow the backtrace feature too.
1446 rustflags.arg("-Zallow-features=binary-dep-depinfo,backtrace");
1449 // Right now this is just compiletest and a few other tools that build on stable.
1450 // Allow them to use `feature(test)`, but nothing else.
1451 rustflags.arg("-Zallow-features=binary-dep-depinfo,test,backtrace");
1453 Mode::Std | Mode::Rustc | Mode::Codegen | Mode::ToolRustc => {}
1456 cargo.arg("-j").arg(self.jobs().to_string());
1457 // Remove make-related flags to ensure Cargo can correctly set things up
1458 cargo.env_remove("MAKEFLAGS");
1459 cargo.env_remove("MFLAGS");
1461 // FIXME: Temporary fix for https://github.com/rust-lang/cargo/issues/3005
1462 // Force cargo to output binaries with disambiguating hashes in the name
1463 let mut metadata = if compiler.stage == 0 {
1464 // Treat stage0 like a special channel, whether it's a normal prior-
1465 // release rustc or a local rebuild with the same version, so we
1466 // never mix these libraries by accident.
1467 "bootstrap".to_string()
1469 self.config.channel.to_string()
1471 // We want to make sure that none of the dependencies between
1472 // std/test/rustc unify with one another. This is done for weird linkage
1473 // reasons but the gist of the problem is that if librustc, libtest, and
1474 // libstd all depend on libc from crates.io (which they actually do) we
1475 // want to make sure they all get distinct versions. Things get really
1476 // weird if we try to unify all these dependencies right now, namely
1477 // around how many times the library is linked in dynamic libraries and
1478 // such. If rustc were a static executable or if we didn't ship dylibs
1479 // this wouldn't be a problem, but we do, so it is. This is in general
1480 // just here to make sure things build right. If you can remove this and
1481 // things still build right, please do!
1483 Mode::Std => metadata.push_str("std"),
1484 // When we're building rustc tools, they're built with a search path
1485 // that contains things built during the rustc build. For example,
1486 // bitflags is built during the rustc build, and is a dependency of
1487 // rustdoc as well. We're building rustdoc in a different target
1488 // directory, though, which means that Cargo will rebuild the
1489 // dependency. When we go on to build rustdoc, we'll look for
1490 // bitflags, and find two different copies: one built during the
1491 // rustc step and one that we just built. This isn't always a
1492 // problem, somehow -- not really clear why -- but we know that this
1494 Mode::ToolRustc => metadata.push_str("tool-rustc"),
1495 // Same for codegen backends.
1496 Mode::Codegen => metadata.push_str("codegen"),
1499 cargo.env("__CARGO_DEFAULT_LIB_METADATA", &metadata);
1501 if cmd == "clippy" {
1502 rustflags.arg("-Zforce-unstable-if-unmarked");
1505 rustflags.arg("-Zmacro-backtrace");
1507 let want_rustdoc = self.doc_tests != DocTests::No;
1509 // We synthetically interpret a stage0 compiler used to build tools as a
1510 // "raw" compiler in that it's the exact snapshot we download. Normally
1511 // the stage0 build means it uses libraries build by the stage0
1512 // compiler, but for tools we just use the precompiled libraries that
1514 let use_snapshot = mode == Mode::ToolBootstrap;
1515 assert!(!use_snapshot || stage == 0 || self.local_rebuild);
1517 let maybe_sysroot = self.sysroot(compiler);
1518 let sysroot = if use_snapshot { self.rustc_snapshot_sysroot() } else { &maybe_sysroot };
1519 let libdir = self.rustc_libdir(compiler);
1521 // Clear the output directory if the real rustc we're using has changed;
1522 // Cargo cannot detect this as it thinks rustc is bootstrap/debug/rustc.
1524 // Avoid doing this during dry run as that usually means the relevant
1525 // compiler is not yet linked/copied properly.
1527 // Only clear out the directory if we're compiling std; otherwise, we
1528 // should let Cargo take care of things for us (via depdep info)
1529 if !self.config.dry_run && mode == Mode::Std && cmd == "build" {
1530 self.clear_if_dirty(&out_dir, &self.rustc(compiler));
1533 // Customize the compiler we're running. Specify the compiler to cargo
1534 // as our shim and then pass it some various options used to configure
1535 // how the actual compiler itself is called.
1537 // These variables are primarily all read by
1538 // src/bootstrap/bin/{rustc.rs,rustdoc.rs}
1540 .env("RUSTBUILD_NATIVE_DIR", self.native_dir(target))
1541 .env("RUSTC_REAL", self.rustc(compiler))
1542 .env("RUSTC_STAGE", stage.to_string())
1543 .env("RUSTC_SYSROOT", &sysroot)
1544 .env("RUSTC_LIBDIR", &libdir)
1545 .env("RUSTDOC", self.bootstrap_out.join("rustdoc"))
1548 if cmd == "doc" || cmd == "rustdoc" || (cmd == "test" && want_rustdoc) {
1549 self.rustdoc(compiler)
1551 PathBuf::from("/path/to/nowhere/rustdoc/not/required")
1554 .env("RUSTC_ERROR_METADATA_DST", self.extended_error_dir())
1555 .env("RUSTC_BREAK_ON_ICE", "1");
1556 // Clippy support is a hack and uses the default `cargo-clippy` in path.
1557 // Don't override RUSTC so that the `cargo-clippy` in path will be run.
1558 if cmd != "clippy" {
1559 cargo.env("RUSTC", self.bootstrap_out.join("rustc"));
1562 // Dealing with rpath here is a little special, so let's go into some
1563 // detail. First off, `-rpath` is a linker option on Unix platforms
1564 // which adds to the runtime dynamic loader path when looking for
1565 // dynamic libraries. We use this by default on Unix platforms to ensure
1566 // that our nightlies behave the same on Windows, that is they work out
1567 // of the box. This can be disabled, of course, but basically that's why
1568 // we're gated on RUSTC_RPATH here.
1570 // Ok, so the astute might be wondering "why isn't `-C rpath` used
1571 // here?" and that is indeed a good question to ask. This codegen
1572 // option is the compiler's current interface to generating an rpath.
1573 // Unfortunately it doesn't quite suffice for us. The flag currently
1574 // takes no value as an argument, so the compiler calculates what it
1575 // should pass to the linker as `-rpath`. This unfortunately is based on
1576 // the **compile time** directory structure which when building with
1577 // Cargo will be very different than the runtime directory structure.
1579 // All that's a really long winded way of saying that if we use
1580 // `-Crpath` then the executables generated have the wrong rpath of
1581 // something like `$ORIGIN/deps` when in fact the way we distribute
1582 // rustc requires the rpath to be `$ORIGIN/../lib`.
1584 // So, all in all, to set up the correct rpath we pass the linker
1585 // argument manually via `-C link-args=-Wl,-rpath,...`. Plus isn't it
1586 // fun to pass a flag to a tool to pass a flag to pass a flag to a tool
1587 // to change a flag in a binary?
1588 if self.config.rust_rpath && util::use_host_linker(target) {
1589 let rpath = if target.contains("apple") {
1590 // Note that we need to take one extra step on macOS to also pass
1591 // `-Wl,-instal_name,@rpath/...` to get things to work right. To
1592 // do that we pass a weird flag to the compiler to get it to do
1593 // so. Note that this is definitely a hack, and we should likely
1594 // flesh out rpath support more fully in the future.
1595 rustflags.arg("-Zosx-rpath-install-name");
1596 Some("-Wl,-rpath,@loader_path/../lib")
1597 } else if !target.contains("windows") {
1598 rustflags.arg("-Clink-args=-Wl,-z,origin");
1599 Some("-Wl,-rpath,$ORIGIN/../lib")
1603 if let Some(rpath) = rpath {
1604 rustflags.arg(&format!("-Clink-args={}", rpath));
1608 if let Some(host_linker) = self.linker(compiler.host) {
1609 cargo.env("RUSTC_HOST_LINKER", host_linker);
1611 if self.is_fuse_ld_lld(compiler.host) {
1612 cargo.env("RUSTC_HOST_FUSE_LD_LLD", "1");
1613 cargo.env("RUSTDOC_FUSE_LD_LLD", "1");
1616 if let Some(target_linker) = self.linker(target) {
1617 let target = crate::envify(&target.triple);
1618 cargo.env(&format!("CARGO_TARGET_{}_LINKER", target), target_linker);
1620 if self.is_fuse_ld_lld(target) {
1621 rustflags.arg("-Clink-args=-fuse-ld=lld");
1623 self.lld_flags(target).for_each(|flag| {
1624 rustdocflags.arg(&flag);
1627 if !(["build", "check", "clippy", "fix", "rustc"].contains(&cmd)) && want_rustdoc {
1628 cargo.env("RUSTDOC_LIBDIR", self.rustc_libdir(compiler));
1631 let debuginfo_level = match mode {
1632 Mode::Rustc | Mode::Codegen => self.config.rust_debuginfo_level_rustc,
1633 Mode::Std => self.config.rust_debuginfo_level_std,
1634 Mode::ToolBootstrap | Mode::ToolStd | Mode::ToolRustc => {
1635 self.config.rust_debuginfo_level_tools
1638 cargo.env(profile_var("DEBUG"), debuginfo_level.to_string());
1640 profile_var("DEBUG_ASSERTIONS"),
1641 if mode == Mode::Std {
1642 self.config.rust_debug_assertions_std.to_string()
1644 self.config.rust_debug_assertions.to_string()
1648 profile_var("OVERFLOW_CHECKS"),
1649 if mode == Mode::Std {
1650 self.config.rust_overflow_checks_std.to_string()
1652 self.config.rust_overflow_checks.to_string()
1656 if !target.contains("windows") {
1657 let needs_unstable_opts = target.contains("linux")
1658 || target.contains("windows")
1659 || target.contains("bsd")
1660 || target.contains("dragonfly");
1662 if needs_unstable_opts {
1663 rustflags.arg("-Zunstable-options");
1665 match self.config.rust_split_debuginfo {
1666 SplitDebuginfo::Packed => rustflags.arg("-Csplit-debuginfo=packed"),
1667 SplitDebuginfo::Unpacked => rustflags.arg("-Csplit-debuginfo=unpacked"),
1668 SplitDebuginfo::Off => rustflags.arg("-Csplit-debuginfo=off"),
1672 if self.config.cmd.bless() {
1673 // Bless `expect!` tests.
1674 cargo.env("UPDATE_EXPECT", "1");
1677 if !mode.is_tool() {
1678 cargo.env("RUSTC_FORCE_UNSTABLE", "1");
1681 if let Some(x) = self.crt_static(target) {
1683 rustflags.arg("-Ctarget-feature=+crt-static");
1685 rustflags.arg("-Ctarget-feature=-crt-static");
1689 if let Some(x) = self.crt_static(compiler.host) {
1690 cargo.env("RUSTC_HOST_CRT_STATIC", x.to_string());
1693 if let Some(map_to) = self.build.debuginfo_map_to(GitRepo::Rustc) {
1694 let map = format!("{}={}", self.build.src.display(), map_to);
1695 cargo.env("RUSTC_DEBUGINFO_MAP", map);
1697 // `rustc` needs to know the virtual `/rustc/$hash` we're mapping to,
1698 // in order to opportunistically reverse it later.
1699 cargo.env("CFG_VIRTUAL_RUST_SOURCE_BASE_DIR", map_to);
1702 // Enable usage of unstable features
1703 cargo.env("RUSTC_BOOTSTRAP", "1");
1704 self.add_rust_test_threads(&mut cargo);
1706 // Almost all of the crates that we compile as part of the bootstrap may
1707 // have a build script, including the standard library. To compile a
1708 // build script, however, it itself needs a standard library! This
1709 // introduces a bit of a pickle when we're compiling the standard
1712 // To work around this we actually end up using the snapshot compiler
1713 // (stage0) for compiling build scripts of the standard library itself.
1714 // The stage0 compiler is guaranteed to have a libstd available for use.
1716 // For other crates, however, we know that we've already got a standard
1717 // library up and running, so we can use the normal compiler to compile
1718 // build scripts in that situation.
1719 if mode == Mode::Std {
1721 .env("RUSTC_SNAPSHOT", &self.initial_rustc)
1722 .env("RUSTC_SNAPSHOT_LIBDIR", self.rustc_snapshot_libdir());
1725 .env("RUSTC_SNAPSHOT", self.rustc(compiler))
1726 .env("RUSTC_SNAPSHOT_LIBDIR", self.rustc_libdir(compiler));
1729 // Tools that use compiler libraries may inherit the `-lLLVM` link
1730 // requirement, but the `-L` library path is not propagated across
1731 // separate Cargo projects. We can add LLVM's library path to the
1732 // platform-specific environment variable as a workaround.
1733 if mode == Mode::ToolRustc || mode == Mode::Codegen {
1734 if let Some(llvm_config) = self.llvm_config(target) {
1735 let llvm_libdir = output(Command::new(&llvm_config).arg("--libdir"));
1736 add_link_lib_path(vec![llvm_libdir.trim().into()], &mut cargo);
1740 // Compile everything except libraries and proc macros with the more
1741 // efficient initial-exec TLS model. This doesn't work with `dlopen`,
1742 // so we can't use it by default in general, but we can use it for tools
1743 // and our own internal libraries.
1744 if !mode.must_support_dlopen() && !target.triple.starts_with("powerpc-") {
1745 rustflags.arg("-Ztls-model=initial-exec");
1748 if self.config.incremental {
1749 cargo.env("CARGO_INCREMENTAL", "1");
1751 // Don't rely on any default setting for incr. comp. in Cargo
1752 cargo.env("CARGO_INCREMENTAL", "0");
1755 if let Some(ref on_fail) = self.config.on_fail {
1756 cargo.env("RUSTC_ON_FAIL", on_fail);
1759 if self.config.print_step_timings {
1760 cargo.env("RUSTC_PRINT_STEP_TIMINGS", "1");
1763 if self.config.print_step_rusage {
1764 cargo.env("RUSTC_PRINT_STEP_RUSAGE", "1");
1767 if self.config.backtrace_on_ice {
1768 cargo.env("RUSTC_BACKTRACE_ON_ICE", "1");
1771 cargo.env("RUSTC_VERBOSE", self.verbosity.to_string());
1773 if source_type == SourceType::InTree {
1774 let mut lint_flags = Vec::new();
1775 // When extending this list, add the new lints to the RUSTFLAGS of the
1776 // build_bootstrap function of src/bootstrap/bootstrap.py as well as
1777 // some code doesn't go through this `rustc` wrapper.
1778 lint_flags.push("-Wrust_2018_idioms");
1779 lint_flags.push("-Wunused_lifetimes");
1780 lint_flags.push("-Wsemicolon_in_expressions_from_macros");
1782 if self.config.deny_warnings {
1783 lint_flags.push("-Dwarnings");
1784 rustdocflags.arg("-Dwarnings");
1787 // This does not use RUSTFLAGS due to caching issues with Cargo.
1788 // Clippy is treated as an "in tree" tool, but shares the same
1789 // cache as other "submodule" tools. With these options set in
1790 // RUSTFLAGS, that causes *every* shared dependency to be rebuilt.
1791 // By injecting this into the rustc wrapper, this circumvents
1792 // Cargo's fingerprint detection. This is fine because lint flags
1793 // are always ignored in dependencies. Eventually this should be
1794 // fixed via better support from Cargo.
1795 cargo.env("RUSTC_LINT_FLAGS", lint_flags.join(" "));
1797 rustdocflags.arg("-Wrustdoc::invalid_codeblock_attributes");
1800 if mode == Mode::Rustc {
1801 rustflags.arg("-Zunstable-options");
1802 rustflags.arg("-Wrustc::internal");
1805 // Throughout the build Cargo can execute a number of build scripts
1806 // compiling C/C++ code and we need to pass compilers, archivers, flags, etc
1807 // obtained previously to those build scripts.
1808 // Build scripts use either the `cc` crate or `configure/make` so we pass
1809 // the options through environment variables that are fetched and understood by both.
1811 // FIXME: the guard against msvc shouldn't need to be here
1812 if target.contains("msvc") {
1813 if let Some(ref cl) = self.config.llvm_clang_cl {
1814 cargo.env("CC", cl).env("CXX", cl);
1817 let ccache = self.config.ccache.as_ref();
1818 let ccacheify = |s: &Path| {
1819 let ccache = match ccache {
1821 None => return s.display().to_string(),
1823 // FIXME: the cc-rs crate only recognizes the literal strings
1824 // `ccache` and `sccache` when doing caching compilations, so we
1825 // mirror that here. It should probably be fixed upstream to
1826 // accept a new env var or otherwise work with custom ccache
1829 "ccache" | "sccache" => format!("{} {}", ccache, s.display()),
1830 _ => s.display().to_string(),
1833 let cc = ccacheify(&self.cc(target));
1834 cargo.env(format!("CC_{}", target.triple), &cc);
1836 let cflags = self.cflags(target, GitRepo::Rustc, CLang::C).join(" ");
1837 cargo.env(format!("CFLAGS_{}", target.triple), &cflags);
1839 if let Some(ar) = self.ar(target) {
1840 let ranlib = format!("{} s", ar.display());
1842 .env(format!("AR_{}", target.triple), ar)
1843 .env(format!("RANLIB_{}", target.triple), ranlib);
1846 if let Ok(cxx) = self.cxx(target) {
1847 let cxx = ccacheify(&cxx);
1848 let cxxflags = self.cflags(target, GitRepo::Rustc, CLang::Cxx).join(" ");
1850 .env(format!("CXX_{}", target.triple), &cxx)
1851 .env(format!("CXXFLAGS_{}", target.triple), cxxflags);
1855 if mode == Mode::Std && self.config.extended && compiler.is_final_stage(self) {
1856 rustflags.arg("-Zsave-analysis");
1858 "RUST_SAVE_ANALYSIS_CONFIG",
1859 "{\"output_file\": null,\"full_docs\": false,\
1860 \"pub_only\": true,\"reachable_only\": false,\
1861 \"distro_crate\": true,\"signatures\": false,\"borrow_data\": false}",
1865 // If Control Flow Guard is enabled, pass the `control-flow-guard` flag to rustc
1866 // when compiling the standard library, since this might be linked into the final outputs
1867 // produced by rustc. Since this mitigation is only available on Windows, only enable it
1868 // for the standard library in case the compiler is run on a non-Windows platform.
1869 // This is not needed for stage 0 artifacts because these will only be used for building
1870 // the stage 1 compiler.
1872 && mode == Mode::Std
1873 && self.config.control_flow_guard
1874 && compiler.stage >= 1
1876 rustflags.arg("-Ccontrol-flow-guard");
1879 // For `cargo doc` invocations, make rustdoc print the Rust version into the docs
1880 // This replaces spaces with newlines because RUSTDOCFLAGS does not
1881 // support arguments with regular spaces. Hopefully someday Cargo will
1882 // have space support.
1883 let rust_version = self.rust_version().replace(' ', "\n");
1884 rustdocflags.arg("--crate-version").arg(&rust_version);
1886 // Environment variables *required* throughout the build
1888 // FIXME: should update code to not require this env var
1889 cargo.env("CFG_COMPILER_HOST_TRIPLE", target.triple);
1891 // Set this for all builds to make sure doc builds also get it.
1892 cargo.env("CFG_RELEASE_CHANNEL", &self.config.channel);
1894 // This one's a bit tricky. As of the time of this writing the compiler
1895 // links to the `winapi` crate on crates.io. This crate provides raw
1896 // bindings to Windows system functions, sort of like libc does for
1897 // Unix. This crate also, however, provides "import libraries" for the
1898 // MinGW targets. There's an import library per dll in the windows
1899 // distribution which is what's linked to. These custom import libraries
1900 // are used because the winapi crate can reference Windows functions not
1901 // present in the MinGW import libraries.
1903 // For example MinGW may ship libdbghelp.a, but it may not have
1904 // references to all the functions in the dbghelp dll. Instead the
1905 // custom import library for dbghelp in the winapi crates has all this
1908 // Unfortunately for us though the import libraries are linked by
1909 // default via `-ldylib=winapi_foo`. That is, they're linked with the
1910 // `dylib` type with a `winapi_` prefix (so the winapi ones don't
1911 // conflict with the system MinGW ones). This consequently means that
1912 // the binaries we ship of things like rustc_codegen_llvm (aka the rustc_codegen_llvm
1913 // DLL) when linked against *again*, for example with procedural macros
1914 // or plugins, will trigger the propagation logic of `-ldylib`, passing
1915 // `-lwinapi_foo` to the linker again. This isn't actually available in
1916 // our distribution, however, so the link fails.
1918 // To solve this problem we tell winapi to not use its bundled import
1919 // libraries. This means that it will link to the system MinGW import
1920 // libraries by default, and the `-ldylib=foo` directives will still get
1921 // passed to the final linker, but they'll look like `-lfoo` which can
1922 // be resolved because MinGW has the import library. The downside is we
1923 // don't get newer functions from Windows, but we don't use any of them
1925 if !mode.is_tool() {
1926 cargo.env("WINAPI_NO_BUNDLED_LIBRARIES", "1");
1929 for _ in 0..self.verbosity {
1933 match (mode, self.config.rust_codegen_units_std, self.config.rust_codegen_units) {
1934 (Mode::Std, Some(n), _) | (_, _, Some(n)) => {
1935 cargo.env(profile_var("CODEGEN_UNITS"), n.to_string());
1938 // Don't set anything
1942 if self.config.rust_optimize {
1943 // FIXME: cargo bench/install do not accept `--release`
1944 if cmd != "bench" && cmd != "install" {
1945 cargo.arg("--release");
1949 if self.config.locked_deps {
1950 cargo.arg("--locked");
1952 if self.config.vendor || self.is_sudo {
1953 cargo.arg("--frozen");
1956 // Try to use a sysroot-relative bindir, in case it was configured absolutely.
1957 cargo.env("RUSTC_INSTALL_BINDIR", self.config.bindir_relative());
1959 self.ci_env.force_coloring_in_ci(&mut cargo);
1961 // When we build Rust dylibs they're all intended for intermediate
1962 // usage, so make sure we pass the -Cprefer-dynamic flag instead of
1963 // linking all deps statically into the dylib.
1964 if matches!(mode, Mode::Std | Mode::Rustc) {
1965 rustflags.arg("-Cprefer-dynamic");
1968 // When building incrementally we default to a lower ThinLTO import limit
1969 // (unless explicitly specified otherwise). This will produce a somewhat
1970 // slower code but give way better compile times.
1972 let limit = match self.config.rust_thin_lto_import_instr_limit {
1973 Some(limit) => Some(limit),
1974 None if self.config.incremental => Some(10),
1978 if let Some(limit) = limit {
1979 rustflags.arg(&format!("-Cllvm-args=-import-instr-limit={}", limit));
1983 Cargo { command: cargo, rustflags, rustdocflags }
1986 /// Ensure that a given step is built, returning its output. This will
1987 /// cache the step, so it is safe (and good!) to call this as often as
1988 /// needed to ensure that all dependencies are built.
1989 pub fn ensure<S: Step>(&'a self, step: S) -> S::Output {
1991 let mut stack = self.stack.borrow_mut();
1992 for stack_step in stack.iter() {
1994 if stack_step.downcast_ref::<S>().map_or(true, |stack_step| *stack_step != step) {
1997 let mut out = String::new();
1998 out += &format!("\n\nCycle in build detected when adding {:?}\n", step);
1999 for el in stack.iter().rev() {
2000 out += &format!("\t{:?}\n", el);
2004 if let Some(out) = self.cache.get(&step) {
2005 self.verbose_than(1, &format!("{}c {:?}", " ".repeat(stack.len()), step));
2009 self.verbose_than(1, &format!("{}> {:?}", " ".repeat(stack.len()), step));
2010 stack.push(Box::new(step.clone()));
2014 let start = Instant::now();
2015 let zero = Duration::new(0, 0);
2016 let parent = self.time_spent_on_dependencies.replace(zero);
2017 let out = step.clone().run(self);
2018 let dur = start.elapsed();
2019 let deps = self.time_spent_on_dependencies.replace(parent + dur);
2023 if self.config.print_step_timings && !self.config.dry_run {
2024 let step_string = format!("{:?}", step);
2025 let brace_index = step_string.find("{").unwrap_or(0);
2026 let type_string = type_name::<S>();
2028 "[TIMING] {} {} -- {}.{:03}",
2029 &type_string.strip_prefix("bootstrap::").unwrap_or(type_string),
2030 &step_string[brace_index..],
2037 let mut stack = self.stack.borrow_mut();
2038 let cur_step = stack.pop().expect("step stack empty");
2039 assert_eq!(cur_step.downcast_ref(), Some(&step));
2041 self.verbose_than(1, &format!("{}< {:?}", " ".repeat(self.stack.borrow().len()), step));
2042 self.cache.put(step, out.clone());
2046 /// Ensure that a given step is built *only if it's supposed to be built by default*, returning
2047 /// its output. This will cache the step, so it's safe (and good!) to call this as often as
2048 /// needed to ensure that all dependencies are build.
2049 pub(crate) fn ensure_if_default<T, S: Step<Output = Option<T>>>(
2054 let desc = StepDescription::from::<S>(kind);
2055 let should_run = (desc.should_run)(ShouldRun::new(self, desc.kind));
2057 // Avoid running steps contained in --exclude
2058 for pathset in &should_run.paths {
2059 if desc.is_excluded(self, pathset) {
2064 // Only execute if it's supposed to run as default
2065 if desc.default && should_run.is_really_default() { self.ensure(step) } else { None }
2068 /// Checks if any of the "should_run" paths is in the `Builder` paths.
2069 pub(crate) fn was_invoked_explicitly<S: Step>(&'a self, kind: Kind) -> bool {
2070 let desc = StepDescription::from::<S>(kind);
2071 let should_run = (desc.should_run)(ShouldRun::new(self, desc.kind));
2073 for path in &self.paths {
2074 if should_run.paths.iter().any(|s| s.has(path, Some(desc.kind)))
2075 && !desc.is_excluded(
2077 &PathSet::Suite(TaskPath { path: path.clone(), kind: Some(desc.kind) }),
2091 #[derive(Debug, Clone)]
2092 struct Rustflags(String, TargetSelection);
2095 fn new(target: TargetSelection) -> Rustflags {
2096 let mut ret = Rustflags(String::new(), target);
2097 ret.propagate_cargo_env("RUSTFLAGS");
2101 /// By default, cargo will pick up on various variables in the environment. However, bootstrap
2102 /// reuses those variables to pass additional flags to rustdoc, so by default they get overridden.
2103 /// Explicitly add back any previous value in the environment.
2105 /// `prefix` is usually `RUSTFLAGS` or `RUSTDOCFLAGS`.
2106 fn propagate_cargo_env(&mut self, prefix: &str) {
2107 // Inherit `RUSTFLAGS` by default ...
2110 // ... and also handle target-specific env RUSTFLAGS if they're configured.
2111 let target_specific = format!("CARGO_TARGET_{}_{}", crate::envify(&self.1.triple), prefix);
2112 self.env(&target_specific);
2115 fn env(&mut self, env: &str) {
2116 if let Ok(s) = env::var(env) {
2117 for part in s.split(' ') {
2123 fn arg(&mut self, arg: &str) -> &mut Self {
2124 assert_eq!(arg.split(' ').count(), 1);
2125 if !self.0.is_empty() {
2128 self.0.push_str(arg);
2136 rustflags: Rustflags,
2137 rustdocflags: Rustflags,
2141 pub fn rustdocflag(&mut self, arg: &str) -> &mut Cargo {
2142 self.rustdocflags.arg(arg);
2145 pub fn rustflag(&mut self, arg: &str) -> &mut Cargo {
2146 self.rustflags.arg(arg);
2150 pub fn arg(&mut self, arg: impl AsRef<OsStr>) -> &mut Cargo {
2151 self.command.arg(arg.as_ref());
2155 pub fn args<I, S>(&mut self, args: I) -> &mut Cargo
2157 I: IntoIterator<Item = S>,
2161 self.arg(arg.as_ref());
2166 pub fn env(&mut self, key: impl AsRef<OsStr>, value: impl AsRef<OsStr>) -> &mut Cargo {
2167 // These are managed through rustflag/rustdocflag interfaces.
2168 assert_ne!(key.as_ref(), "RUSTFLAGS");
2169 assert_ne!(key.as_ref(), "RUSTDOCFLAGS");
2170 self.command.env(key.as_ref(), value.as_ref());
2174 pub fn add_rustc_lib_path(&mut self, builder: &Builder<'_>, compiler: Compiler) {
2175 builder.add_rustc_lib_path(compiler, &mut self.command);
2178 pub fn current_dir(&mut self, dir: &Path) -> &mut Cargo {
2179 self.command.current_dir(dir);
2184 impl From<Cargo> for Command {
2185 fn from(mut cargo: Cargo) -> Command {
2186 let rustflags = &cargo.rustflags.0;
2187 if !rustflags.is_empty() {
2188 cargo.command.env("RUSTFLAGS", rustflags);
2191 let rustdocflags = &cargo.rustdocflags.0;
2192 if !rustdocflags.is_empty() {
2193 cargo.command.env("RUSTDOCFLAGS", rustdocflags);