2 use std::cell::{Cell, RefCell};
3 use std::collections::BTreeSet;
10 use std::path::{Path, PathBuf};
11 use std::process::Command;
12 use std::time::{Duration, Instant};
14 use build_helper::{output, t};
16 use crate::cache::{Cache, Interned, INTERNER};
19 use crate::config::TargetSelection;
22 use crate::flags::{Color, Subcommand};
27 use crate::tool::{self, SourceType};
28 use crate::util::{self, add_dylib_path, add_link_lib_path, exe, libdir};
29 use crate::{Build, DocTests, GitRepo, Mode};
31 pub use crate::Compiler;
33 pub struct Builder<'a> {
38 stack: RefCell<Vec<Box<dyn Any>>>,
39 time_spent_on_dependencies: Cell<Duration>,
40 pub paths: Vec<PathBuf>,
43 impl<'a> Deref for Builder<'a> {
46 fn deref(&self) -> &Self::Target {
51 pub trait Step: 'static + Clone + Debug + PartialEq + Eq + Hash {
52 /// `PathBuf` when directories are created or to return a `Compiler` once
53 /// it's been assembled.
56 /// Whether this step is run by default as part of its respective phase.
57 /// `true` here can still be overwritten by `should_run` calling `default_condition`.
58 const DEFAULT: bool = false;
60 /// Whether this step should be run even when `download-rustc` is set.
62 /// Most steps are not important when the compiler is downloaded, since they will be included in
63 /// the pre-compiled sysroot. Steps can set this to `true` to be built anyway.
65 /// When in doubt, set this to `false`.
66 const ENABLE_DOWNLOAD_RUSTC: bool = false;
68 /// If true, then this rule should be skipped if --target was specified, but --host was not
69 const ONLY_HOSTS: bool = false;
71 /// Primary function to execute this rule. Can call `builder.ensure()`
72 /// with other steps to run those.
73 fn run(self, builder: &Builder<'_>) -> Self::Output;
75 /// When bootstrap is passed a set of paths, this controls whether this rule
76 /// will execute. However, it does not get called in a "default" context
77 /// when we are not passed any paths; in that case, `make_run` is called
79 fn should_run(run: ShouldRun<'_>) -> ShouldRun<'_>;
81 /// Builds up a "root" rule, either as a default rule or from a path passed
84 /// When path is `None`, we are executing in a context where no paths were
85 /// passed. When `./x.py build` is run, for example, this rule could get
86 /// called if it is in the correct list below with a path of `None`.
87 fn make_run(_run: RunConfig<'_>) {
88 // It is reasonable to not have an implementation of make_run for rules
89 // who do not want to get called from the root context. This means that
90 // they are likely dependencies (e.g., sysroot creation) or similar, and
91 // as such calling them from ./x.py isn't logical.
96 pub struct RunConfig<'a> {
97 pub builder: &'a Builder<'a>,
98 pub target: TargetSelection,
103 pub fn build_triple(&self) -> TargetSelection {
104 self.builder.build.build
108 struct StepDescription {
110 enable_download_rustc: bool,
112 should_run: fn(ShouldRun<'_>) -> ShouldRun<'_>,
113 make_run: fn(RunConfig<'_>),
117 /// Collection of paths used to match a task rule.
118 #[derive(Debug, Clone, PartialOrd, Ord, PartialEq, Eq)]
120 /// A collection of individual paths.
122 /// These are generally matched as a path suffix. For example, a
123 /// command-line value of `libstd` will match if `src/libstd` is in the
125 Set(BTreeSet<PathBuf>),
126 /// A "suite" of paths.
128 /// These can match as a path suffix (like `Set`), or as a prefix. For
129 /// example, a command-line value of `src/test/ui/abi/variadic-ffi.rs`
130 /// will match `src/test/ui`. A command-line value of `ui` would also
131 /// match `src/test/ui`.
136 fn empty() -> PathSet {
137 PathSet::Set(BTreeSet::new())
140 fn one<P: Into<PathBuf>>(path: P) -> PathSet {
141 let mut set = BTreeSet::new();
142 set.insert(path.into());
146 fn has(&self, needle: &Path) -> bool {
148 PathSet::Set(set) => set.iter().any(|p| p.ends_with(needle)),
149 PathSet::Suite(suite) => suite.ends_with(needle),
153 fn path(&self, builder: &Builder<'_>) -> PathBuf {
155 PathSet::Set(set) => set.iter().next().unwrap_or(&builder.build.src).to_path_buf(),
156 PathSet::Suite(path) => PathBuf::from(path),
161 impl StepDescription {
162 fn from<S: Step>() -> StepDescription {
165 enable_download_rustc: S::ENABLE_DOWNLOAD_RUSTC,
166 only_hosts: S::ONLY_HOSTS,
167 should_run: S::should_run,
168 make_run: S::make_run,
169 name: std::any::type_name::<S>(),
173 fn maybe_run(&self, builder: &Builder<'_>, pathset: &PathSet) {
174 if builder.config.exclude.iter().any(|e| pathset.has(e)) {
175 eprintln!("Skipping {:?} because it is excluded", pathset);
177 } else if !builder.config.exclude.is_empty() {
179 "{:?} not skipped for {:?} -- not in {:?}",
180 pathset, self.name, builder.config.exclude
182 } else if builder.config.download_rustc && !self.enable_download_rustc {
183 if !builder.config.dry_run {
185 "Not running {} because its artifacts have been downloaded from CI (`download-rustc` is set)",
192 // Determine the targets participating in this rule.
193 let targets = if self.only_hosts { &builder.hosts } else { &builder.targets };
195 for target in targets {
196 let run = RunConfig { builder, path: pathset.path(builder), target: *target };
197 (self.make_run)(run);
201 fn run(v: &[StepDescription], builder: &Builder<'_>, paths: &[PathBuf]) {
203 v.iter().map(|desc| (desc.should_run)(ShouldRun::new(builder))).collect::<Vec<_>>();
205 // sanity checks on rules
206 for (desc, should_run) in v.iter().zip(&should_runs) {
208 !should_run.paths.is_empty(),
209 "{:?} should have at least one pathset",
214 if paths.is_empty() || builder.config.include_default_paths {
215 for (desc, should_run) in v.iter().zip(&should_runs) {
216 if desc.default && should_run.is_really_default {
217 for pathset in &should_run.paths {
218 desc.maybe_run(builder, pathset);
225 // strip CurDir prefix if present
226 let path = match path.strip_prefix(".") {
231 let mut attempted_run = false;
232 for (desc, should_run) in v.iter().zip(&should_runs) {
233 if let Some(suite) = should_run.is_suite_path(path) {
234 attempted_run = true;
235 desc.maybe_run(builder, suite);
236 } else if let Some(pathset) = should_run.pathset_for_path(path) {
237 attempted_run = true;
238 desc.maybe_run(builder, pathset);
243 panic!("error: no rules matched {}", path.display());
250 pub struct ShouldRun<'a> {
251 pub builder: &'a Builder<'a>,
252 // use a BTreeSet to maintain sort order
253 paths: BTreeSet<PathSet>,
255 // If this is a default rule, this is an additional constraint placed on
256 // its run. Generally something like compiler docs being enabled.
257 is_really_default: bool,
260 impl<'a> ShouldRun<'a> {
261 fn new(builder: &'a Builder<'_>) -> ShouldRun<'a> {
264 paths: BTreeSet::new(),
265 is_really_default: true, // by default no additional conditions
269 pub fn default_condition(mut self, cond: bool) -> Self {
270 self.is_really_default = cond;
274 /// Indicates it should run if the command-line selects the given crate or
275 /// any of its (local) dependencies.
277 /// Compared to `krate`, this treats the dependencies as aliases for the
278 /// same job. Generally it is preferred to use `krate`, and treat each
279 /// individual path separately. For example `./x.py test src/liballoc`
280 /// (which uses `krate`) will test just `liballoc`. However, `./x.py check
281 /// src/liballoc` (which uses `all_krates`) will check all of `libtest`.
282 /// `all_krates` should probably be removed at some point.
283 pub fn all_krates(mut self, name: &str) -> Self {
284 let mut set = BTreeSet::new();
285 for krate in self.builder.in_tree_crates(name, None) {
286 let path = krate.local_path(self.builder);
289 self.paths.insert(PathSet::Set(set));
293 /// Indicates it should run if the command-line selects the given crate or
294 /// any of its (local) dependencies.
296 /// `make_run` will be called separately for each matching command-line path.
297 pub fn krate(mut self, name: &str) -> Self {
298 for krate in self.builder.in_tree_crates(name, None) {
299 let path = krate.local_path(self.builder);
300 self.paths.insert(PathSet::one(path));
305 // single, non-aliased path
306 pub fn path(self, path: &str) -> Self {
310 // multiple aliases for the same job
311 pub fn paths(mut self, paths: &[&str]) -> Self {
312 self.paths.insert(PathSet::Set(paths.iter().map(PathBuf::from).collect()));
316 pub fn is_suite_path(&self, path: &Path) -> Option<&PathSet> {
317 self.paths.iter().find(|pathset| match pathset {
318 PathSet::Suite(p) => path.starts_with(p),
319 PathSet::Set(_) => false,
323 pub fn suite_path(mut self, suite: &str) -> Self {
324 self.paths.insert(PathSet::Suite(PathBuf::from(suite)));
328 // allows being more explicit about why should_run in Step returns the value passed to it
329 pub fn never(mut self) -> ShouldRun<'a> {
330 self.paths.insert(PathSet::empty());
334 fn pathset_for_path(&self, path: &Path) -> Option<&PathSet> {
335 self.paths.iter().find(|pathset| pathset.has(path))
339 #[derive(Copy, Clone, PartialEq, Eq, Debug)]
354 impl<'a> Builder<'a> {
355 fn get_step_descriptions(kind: Kind) -> Vec<StepDescription> {
356 macro_rules! describe {
357 ($($rule:ty),+ $(,)?) => {{
358 vec![$(StepDescription::from::<$rule>()),+]
362 Kind::Build => describe!(
365 compile::CodegenBackend,
366 compile::StartupObjects,
370 tool::UnstableBookGen,
375 tool::RemoteTestServer,
376 tool::RemoteTestClient,
392 Kind::Check | Kind::Clippy { .. } | Kind::Fix | Kind::Format => describe!(
396 check::CodegenBackend,
400 Kind::Test => describe!(
401 crate::toolstate::ToolStateCheck,
402 test::ExpandYamlAnchors,
405 test::RunPassValgrind,
425 test::RunMakeFullDeps,
440 test::CompiletestTest,
442 test::RustdocJSNotStd,
447 // Run bootstrap close to the end as it's unlikely to fail
449 // Run run-make last, since these won't pass without make on Windows
452 Kind::Bench => describe!(test::Crate, test::CrateLibrustc),
453 Kind::Doc => describe!(
455 doc::UnstableBookGen,
471 Kind::Dist => describe!(
476 dist::DebuggerScripts,
481 dist::PlainSourceTarball,
492 dist::ReproducibleArtifacts,
494 Kind::Install => describe!(
499 install::RustAnalyzer,
507 Kind::Run => describe!(run::ExpandYamlAnchors, run::BuildManifest),
511 pub fn get_help(build: &Build, subcommand: &str) -> Option<String> {
512 let kind = match subcommand {
513 "build" => Kind::Build,
515 "test" => Kind::Test,
516 "bench" => Kind::Bench,
517 "dist" => Kind::Dist,
518 "install" => Kind::Install,
522 let builder = Self::new_internal(build, kind, vec![]);
523 let builder = &builder;
524 let mut should_run = ShouldRun::new(builder);
525 for desc in Builder::get_step_descriptions(builder.kind) {
526 should_run = (desc.should_run)(should_run);
528 let mut help = String::from("Available paths:\n");
529 let mut add_path = |path: &Path| {
530 help.push_str(&format!(" ./x.py {} {}\n", subcommand, path.display()));
532 for pathset in should_run.paths {
534 PathSet::Set(set) => {
539 PathSet::Suite(path) => {
540 add_path(&path.join("..."));
547 fn new_internal(build: &Build, kind: Kind, paths: Vec<PathBuf>) -> Builder<'_> {
550 top_stage: build.config.stage,
553 stack: RefCell::new(Vec::new()),
554 time_spent_on_dependencies: Cell::new(Duration::new(0, 0)),
559 pub fn new(build: &Build) -> Builder<'_> {
560 let (kind, paths) = match build.config.cmd {
561 Subcommand::Build { ref paths } => (Kind::Build, &paths[..]),
562 Subcommand::Check { ref paths, all_targets: _ } => (Kind::Check, &paths[..]),
563 Subcommand::Clippy { ref paths, .. } => (Kind::Clippy, &paths[..]),
564 Subcommand::Fix { ref paths } => (Kind::Fix, &paths[..]),
565 Subcommand::Doc { ref paths, .. } => (Kind::Doc, &paths[..]),
566 Subcommand::Test { ref paths, .. } => (Kind::Test, &paths[..]),
567 Subcommand::Bench { ref paths, .. } => (Kind::Bench, &paths[..]),
568 Subcommand::Dist { ref paths } => (Kind::Dist, &paths[..]),
569 Subcommand::Install { ref paths } => (Kind::Install, &paths[..]),
570 Subcommand::Run { ref paths } => (Kind::Run, &paths[..]),
571 Subcommand::Format { .. } | Subcommand::Clean { .. } | Subcommand::Setup { .. } => {
576 Self::new_internal(build, kind, paths.to_owned())
579 pub fn execute_cli(&self) {
580 self.run_step_descriptions(&Builder::get_step_descriptions(self.kind), &self.paths);
583 pub fn default_doc(&self, paths: &[PathBuf]) {
584 self.run_step_descriptions(&Builder::get_step_descriptions(Kind::Doc), paths);
587 fn run_step_descriptions(&self, v: &[StepDescription], paths: &[PathBuf]) {
588 StepDescription::run(v, self, paths);
591 /// Obtain a compiler at a given stage and for a given host. Explicitly does
592 /// not take `Compiler` since all `Compiler` instances are meant to be
593 /// obtained through this function, since it ensures that they are valid
594 /// (i.e., built and assembled).
595 pub fn compiler(&self, stage: u32, host: TargetSelection) -> Compiler {
596 self.ensure(compile::Assemble { target_compiler: Compiler { stage, host } })
599 /// Similar to `compiler`, except handles the full-bootstrap option to
600 /// silently use the stage1 compiler instead of a stage2 compiler if one is
603 /// Note that this does *not* have the side effect of creating
604 /// `compiler(stage, host)`, unlike `compiler` above which does have such
605 /// a side effect. The returned compiler here can only be used to compile
606 /// new artifacts, it can't be used to rely on the presence of a particular
609 /// See `force_use_stage1` for documentation on what each argument is.
613 host: TargetSelection,
614 target: TargetSelection,
616 if self.build.force_use_stage1(Compiler { stage, host }, target) {
617 self.compiler(1, self.config.build)
619 self.compiler(stage, host)
623 pub fn sysroot(&self, compiler: Compiler) -> Interned<PathBuf> {
624 self.ensure(compile::Sysroot { compiler })
627 /// Returns the libdir where the standard library and other artifacts are
628 /// found for a compiler's sysroot.
629 pub fn sysroot_libdir(&self, compiler: Compiler, target: TargetSelection) -> Interned<PathBuf> {
630 #[derive(Debug, Copy, Clone, Hash, PartialEq, Eq)]
633 target: TargetSelection,
635 impl Step for Libdir {
636 type Output = Interned<PathBuf>;
638 fn should_run(run: ShouldRun<'_>) -> ShouldRun<'_> {
642 fn run(self, builder: &Builder<'_>) -> Interned<PathBuf> {
643 let lib = builder.sysroot_libdir_relative(self.compiler);
644 let sysroot = builder
645 .sysroot(self.compiler)
648 .join(self.target.triple)
650 // Avoid deleting the rustlib/ directory we just copied
651 // (in `impl Step for Sysroot`).
652 if !builder.config.download_rustc {
653 let _ = fs::remove_dir_all(&sysroot);
654 t!(fs::create_dir_all(&sysroot));
656 INTERNER.intern_path(sysroot)
659 self.ensure(Libdir { compiler, target })
662 pub fn sysroot_codegen_backends(&self, compiler: Compiler) -> PathBuf {
663 self.sysroot_libdir(compiler, compiler.host).with_file_name("codegen-backends")
666 /// Returns the compiler's libdir where it stores the dynamic libraries that
667 /// it itself links against.
669 /// For example this returns `<sysroot>/lib` on Unix and `<sysroot>/bin` on
671 pub fn rustc_libdir(&self, compiler: Compiler) -> PathBuf {
672 if compiler.is_snapshot(self) {
673 self.rustc_snapshot_libdir()
675 match self.config.libdir_relative() {
676 Some(relative_libdir) if compiler.stage >= 1 => {
677 self.sysroot(compiler).join(relative_libdir)
679 _ => self.sysroot(compiler).join(libdir(compiler.host)),
684 /// Returns the compiler's relative libdir where it stores the dynamic libraries that
685 /// it itself links against.
687 /// For example this returns `lib` on Unix and `bin` on
689 pub fn libdir_relative(&self, compiler: Compiler) -> &Path {
690 if compiler.is_snapshot(self) {
691 libdir(self.config.build).as_ref()
693 match self.config.libdir_relative() {
694 Some(relative_libdir) if compiler.stage >= 1 => relative_libdir,
695 _ => libdir(compiler.host).as_ref(),
700 /// Returns the compiler's relative libdir where the standard library and other artifacts are
701 /// found for a compiler's sysroot.
703 /// For example this returns `lib` on Unix and Windows.
704 pub fn sysroot_libdir_relative(&self, compiler: Compiler) -> &Path {
705 match self.config.libdir_relative() {
706 Some(relative_libdir) if compiler.stage >= 1 => relative_libdir,
707 _ if compiler.stage == 0 => &self.build.initial_libdir,
708 _ => Path::new("lib"),
712 /// Adds the compiler's directory of dynamic libraries to `cmd`'s dynamic
713 /// library lookup path.
714 pub fn add_rustc_lib_path(&self, compiler: Compiler, cmd: &mut Command) {
715 // Windows doesn't need dylib path munging because the dlls for the
716 // compiler live next to the compiler and the system will find them
722 add_dylib_path(vec![self.rustc_libdir(compiler)], cmd);
725 /// Gets a path to the compiler specified.
726 pub fn rustc(&self, compiler: Compiler) -> PathBuf {
727 if compiler.is_snapshot(self) {
728 self.initial_rustc.clone()
730 self.sysroot(compiler).join("bin").join(exe("rustc", compiler.host))
734 /// Gets the paths to all of the compiler's codegen backends.
735 fn codegen_backends(&self, compiler: Compiler) -> impl Iterator<Item = PathBuf> {
736 fs::read_dir(self.sysroot_codegen_backends(compiler))
739 .filter_map(Result::ok)
740 .map(|entry| entry.path())
743 pub fn rustdoc(&self, compiler: Compiler) -> PathBuf {
744 self.ensure(tool::Rustdoc { compiler })
747 pub fn rustdoc_cmd(&self, compiler: Compiler) -> Command {
748 let mut cmd = Command::new(&self.out.join("bootstrap/debug/rustdoc"));
749 cmd.env("RUSTC_STAGE", compiler.stage.to_string())
750 .env("RUSTC_SYSROOT", self.sysroot(compiler))
751 // Note that this is *not* the sysroot_libdir because rustdoc must be linked
752 // equivalently to rustc.
753 .env("RUSTDOC_LIBDIR", self.rustc_libdir(compiler))
754 .env("CFG_RELEASE_CHANNEL", &self.config.channel)
755 .env("RUSTDOC_REAL", self.rustdoc(compiler))
756 .env("RUSTC_BOOTSTRAP", "1")
757 .arg("-Winvalid_codeblock_attributes");
758 if self.config.deny_warnings {
759 cmd.arg("-Dwarnings");
761 cmd.arg("-Znormalize-docs");
763 // Remove make-related flags that can cause jobserver problems.
764 cmd.env_remove("MAKEFLAGS");
765 cmd.env_remove("MFLAGS");
767 if let Some(linker) = self.linker(compiler.host) {
768 cmd.env("RUSTDOC_LINKER", linker);
770 if self.is_fuse_ld_lld(compiler.host) {
771 cmd.env("RUSTDOC_FUSE_LD_LLD", "1");
776 /// Return the path to `llvm-config` for the target, if it exists.
778 /// Note that this returns `None` if LLVM is disabled, or if we're in a
779 /// check build or dry-run, where there's no need to build all of LLVM.
780 fn llvm_config(&self, target: TargetSelection) -> Option<PathBuf> {
781 if self.config.llvm_enabled() && self.kind != Kind::Check && !self.config.dry_run {
782 let llvm_config = self.ensure(native::Llvm { target });
783 if llvm_config.is_file() {
784 return Some(llvm_config);
790 /// Prepares an invocation of `cargo` to be run.
792 /// This will create a `Command` that represents a pending execution of
793 /// Cargo. This cargo will be configured to use `compiler` as the actual
794 /// rustc compiler, its output will be scoped by `mode`'s output directory,
795 /// it will pass the `--target` flag for the specified `target`, and will be
796 /// executing the Cargo command `cmd`.
801 source_type: SourceType,
802 target: TargetSelection,
805 let mut cargo = Command::new(&self.initial_cargo);
806 let out_dir = self.stage_out(compiler, mode);
808 // Codegen backends are not yet tracked by -Zbinary-dep-depinfo,
809 // so we need to explicitly clear out if they've been updated.
810 for backend in self.codegen_backends(compiler) {
811 self.clear_if_dirty(&out_dir, &backend);
814 if cmd == "doc" || cmd == "rustdoc" {
815 let my_out = match mode {
816 // This is the intended out directory for compiler documentation.
817 Mode::Rustc | Mode::ToolRustc => self.compiler_doc_out(target),
818 Mode::Std => out_dir.join(target.triple).join("doc"),
819 _ => panic!("doc mode {:?} not expected", mode),
821 let rustdoc = self.rustdoc(compiler);
822 self.clear_if_dirty(&my_out, &rustdoc);
825 cargo.env("CARGO_TARGET_DIR", &out_dir).arg(cmd);
827 let profile_var = |name: &str| {
828 let profile = if self.config.rust_optimize { "RELEASE" } else { "DEV" };
829 format!("CARGO_PROFILE_{}_{}", profile, name)
832 // See comment in rustc_llvm/build.rs for why this is necessary, largely llvm-config
833 // needs to not accidentally link to libLLVM in stage0/lib.
834 cargo.env("REAL_LIBRARY_PATH_VAR", &util::dylib_path_var());
835 if let Some(e) = env::var_os(util::dylib_path_var()) {
836 cargo.env("REAL_LIBRARY_PATH", e);
839 // Found with `rg "init_env_logger\("`. If anyone uses `init_env_logger`
840 // from out of tree it shouldn't matter, since x.py is only used for
842 let color_logs = ["RUSTDOC_LOG_COLOR", "RUSTC_LOG_COLOR", "RUST_LOG_COLOR"];
843 match self.build.config.color {
845 cargo.arg("--color=always");
846 for log in &color_logs {
847 cargo.env(log, "always");
851 cargo.arg("--color=never");
852 for log in &color_logs {
853 cargo.env(log, "never");
856 Color::Auto => {} // nothing to do
859 if cmd != "install" {
860 cargo.arg("--target").arg(target.rustc_target_arg());
862 assert_eq!(target, compiler.host);
865 // Set a flag for `check`/`clippy`/`fix`, so that certain build
866 // scripts can do less work (i.e. not building/requiring LLVM).
867 if cmd == "check" || cmd == "clippy" || cmd == "fix" {
868 // If we've not yet built LLVM, or it's stale, then bust
869 // the rustc_llvm cache. That will always work, even though it
870 // may mean that on the next non-check build we'll need to rebuild
871 // rustc_llvm. But if LLVM is stale, that'll be a tiny amount
872 // of work comparitively, and we'd likely need to rebuild it anyway,
874 if crate::native::prebuilt_llvm_config(self, target).is_err() {
875 cargo.env("RUST_CHECK", "1");
879 let stage = if compiler.stage == 0 && self.local_rebuild {
880 // Assume the local-rebuild rustc already has stage1 features.
886 let mut rustflags = Rustflags::new(target);
888 if let Ok(s) = env::var("CARGOFLAGS_NOT_BOOTSTRAP") {
889 cargo.args(s.split_whitespace());
891 rustflags.env("RUSTFLAGS_NOT_BOOTSTRAP");
893 if let Ok(s) = env::var("CARGOFLAGS_BOOTSTRAP") {
894 cargo.args(s.split_whitespace());
896 rustflags.env("RUSTFLAGS_BOOTSTRAP");
898 // clippy overwrites sysroot if we pass it to cargo.
899 // Pass it directly to clippy instead.
900 // NOTE: this can't be fixed in clippy because we explicitly don't set `RUSTC`,
901 // so it has no way of knowing the sysroot.
902 rustflags.arg("--sysroot");
904 self.sysroot(compiler)
907 .expect("sysroot must be valid UTF-8"),
909 // Only run clippy on a very limited subset of crates (in particular, not build scripts).
910 cargo.arg("-Zunstable-options");
911 // Explicitly does *not* set `--cfg=bootstrap`, since we're using a nightly clippy.
912 let host_version = Command::new("rustc").arg("--version").output().map_err(|_| ());
913 let output = host_version.and_then(|output| {
914 if output.status.success() {
919 }).unwrap_or_else(|_| {
921 "error: `x.py clippy` requires a host `rustc` toolchain with the `clippy` component"
923 eprintln!("help: try `rustup component add clippy`");
924 std::process::exit(1);
926 if !t!(std::str::from_utf8(&output.stdout)).contains("nightly") {
927 rustflags.arg("--cfg=bootstrap");
930 rustflags.arg("--cfg=bootstrap");
934 if self.config.rust_new_symbol_mangling {
935 rustflags.arg("-Zsymbol-mangling-version=v0");
938 // FIXME: It might be better to use the same value for both `RUSTFLAGS` and `RUSTDOCFLAGS`,
939 // but this breaks CI. At the very least, stage0 `rustdoc` needs `--cfg bootstrap`. See
941 let mut rustdocflags = rustflags.clone();
943 if let Ok(s) = env::var("CARGOFLAGS") {
944 cargo.args(s.split_whitespace());
948 Mode::Std | Mode::ToolBootstrap | Mode::ToolStd => {}
949 Mode::Rustc | Mode::Codegen | Mode::ToolRustc => {
950 // Build proc macros both for the host and the target
951 if target != compiler.host && cmd != "check" {
952 cargo.arg("-Zdual-proc-macros");
953 rustflags.arg("-Zdual-proc-macros");
958 // This tells Cargo (and in turn, rustc) to output more complete
959 // dependency information. Most importantly for rustbuild, this
960 // includes sysroot artifacts, like libstd, which means that we don't
961 // need to track those in rustbuild (an error prone process!). This
962 // feature is currently unstable as there may be some bugs and such, but
963 // it represents a big improvement in rustbuild's reliability on
964 // rebuilds, so we're using it here.
966 // For some additional context, see #63470 (the PR originally adding
967 // this), as well as #63012 which is the tracking issue for this
968 // feature on the rustc side.
969 cargo.arg("-Zbinary-dep-depinfo");
971 cargo.arg("-j").arg(self.jobs().to_string());
972 // Remove make-related flags to ensure Cargo can correctly set things up
973 cargo.env_remove("MAKEFLAGS");
974 cargo.env_remove("MFLAGS");
976 // FIXME: Temporary fix for https://github.com/rust-lang/cargo/issues/3005
977 // Force cargo to output binaries with disambiguating hashes in the name
978 let mut metadata = if compiler.stage == 0 {
979 // Treat stage0 like a special channel, whether it's a normal prior-
980 // release rustc or a local rebuild with the same version, so we
981 // never mix these libraries by accident.
982 "bootstrap".to_string()
984 self.config.channel.to_string()
986 // We want to make sure that none of the dependencies between
987 // std/test/rustc unify with one another. This is done for weird linkage
988 // reasons but the gist of the problem is that if librustc, libtest, and
989 // libstd all depend on libc from crates.io (which they actually do) we
990 // want to make sure they all get distinct versions. Things get really
991 // weird if we try to unify all these dependencies right now, namely
992 // around how many times the library is linked in dynamic libraries and
993 // such. If rustc were a static executable or if we didn't ship dylibs
994 // this wouldn't be a problem, but we do, so it is. This is in general
995 // just here to make sure things build right. If you can remove this and
996 // things still build right, please do!
998 Mode::Std => metadata.push_str("std"),
999 // When we're building rustc tools, they're built with a search path
1000 // that contains things built during the rustc build. For example,
1001 // bitflags is built during the rustc build, and is a dependency of
1002 // rustdoc as well. We're building rustdoc in a different target
1003 // directory, though, which means that Cargo will rebuild the
1004 // dependency. When we go on to build rustdoc, we'll look for
1005 // bitflags, and find two different copies: one built during the
1006 // rustc step and one that we just built. This isn't always a
1007 // problem, somehow -- not really clear why -- but we know that this
1009 Mode::ToolRustc => metadata.push_str("tool-rustc"),
1010 // Same for codegen backends.
1011 Mode::Codegen => metadata.push_str("codegen"),
1014 cargo.env("__CARGO_DEFAULT_LIB_METADATA", &metadata);
1016 if cmd == "clippy" {
1017 rustflags.arg("-Zforce-unstable-if-unmarked");
1020 rustflags.arg("-Zmacro-backtrace");
1022 let want_rustdoc = self.doc_tests != DocTests::No;
1024 // We synthetically interpret a stage0 compiler used to build tools as a
1025 // "raw" compiler in that it's the exact snapshot we download. Normally
1026 // the stage0 build means it uses libraries build by the stage0
1027 // compiler, but for tools we just use the precompiled libraries that
1029 let use_snapshot = mode == Mode::ToolBootstrap;
1030 assert!(!use_snapshot || stage == 0 || self.local_rebuild);
1032 let maybe_sysroot = self.sysroot(compiler);
1033 let sysroot = if use_snapshot { self.rustc_snapshot_sysroot() } else { &maybe_sysroot };
1034 let libdir = self.rustc_libdir(compiler);
1036 // Clear the output directory if the real rustc we're using has changed;
1037 // Cargo cannot detect this as it thinks rustc is bootstrap/debug/rustc.
1039 // Avoid doing this during dry run as that usually means the relevant
1040 // compiler is not yet linked/copied properly.
1042 // Only clear out the directory if we're compiling std; otherwise, we
1043 // should let Cargo take care of things for us (via depdep info)
1044 if !self.config.dry_run && mode == Mode::Std && cmd == "build" {
1045 self.clear_if_dirty(&out_dir, &self.rustc(compiler));
1048 // Customize the compiler we're running. Specify the compiler to cargo
1049 // as our shim and then pass it some various options used to configure
1050 // how the actual compiler itself is called.
1052 // These variables are primarily all read by
1053 // src/bootstrap/bin/{rustc.rs,rustdoc.rs}
1055 .env("RUSTBUILD_NATIVE_DIR", self.native_dir(target))
1056 .env("RUSTC_REAL", self.rustc(compiler))
1057 .env("RUSTC_STAGE", stage.to_string())
1058 .env("RUSTC_SYSROOT", &sysroot)
1059 .env("RUSTC_LIBDIR", &libdir)
1060 .env("RUSTDOC", self.out.join("bootstrap/debug/rustdoc"))
1063 if cmd == "doc" || cmd == "rustdoc" || (cmd == "test" && want_rustdoc) {
1064 self.rustdoc(compiler)
1066 PathBuf::from("/path/to/nowhere/rustdoc/not/required")
1069 .env("RUSTC_ERROR_METADATA_DST", self.extended_error_dir())
1070 .env("RUSTC_BREAK_ON_ICE", "1");
1071 // Clippy support is a hack and uses the default `cargo-clippy` in path.
1072 // Don't override RUSTC so that the `cargo-clippy` in path will be run.
1073 if cmd != "clippy" {
1074 cargo.env("RUSTC", self.out.join("bootstrap/debug/rustc"));
1077 // Dealing with rpath here is a little special, so let's go into some
1078 // detail. First off, `-rpath` is a linker option on Unix platforms
1079 // which adds to the runtime dynamic loader path when looking for
1080 // dynamic libraries. We use this by default on Unix platforms to ensure
1081 // that our nightlies behave the same on Windows, that is they work out
1082 // of the box. This can be disabled, of course, but basically that's why
1083 // we're gated on RUSTC_RPATH here.
1085 // Ok, so the astute might be wondering "why isn't `-C rpath` used
1086 // here?" and that is indeed a good question to ask. This codegen
1087 // option is the compiler's current interface to generating an rpath.
1088 // Unfortunately it doesn't quite suffice for us. The flag currently
1089 // takes no value as an argument, so the compiler calculates what it
1090 // should pass to the linker as `-rpath`. This unfortunately is based on
1091 // the **compile time** directory structure which when building with
1092 // Cargo will be very different than the runtime directory structure.
1094 // All that's a really long winded way of saying that if we use
1095 // `-Crpath` then the executables generated have the wrong rpath of
1096 // something like `$ORIGIN/deps` when in fact the way we distribute
1097 // rustc requires the rpath to be `$ORIGIN/../lib`.
1099 // So, all in all, to set up the correct rpath we pass the linker
1100 // argument manually via `-C link-args=-Wl,-rpath,...`. Plus isn't it
1101 // fun to pass a flag to a tool to pass a flag to pass a flag to a tool
1102 // to change a flag in a binary?
1103 if self.config.rust_rpath && util::use_host_linker(target) {
1104 let rpath = if target.contains("apple") {
1105 // Note that we need to take one extra step on macOS to also pass
1106 // `-Wl,-instal_name,@rpath/...` to get things to work right. To
1107 // do that we pass a weird flag to the compiler to get it to do
1108 // so. Note that this is definitely a hack, and we should likely
1109 // flesh out rpath support more fully in the future.
1110 rustflags.arg("-Zosx-rpath-install-name");
1111 Some("-Wl,-rpath,@loader_path/../lib")
1112 } else if !target.contains("windows") {
1113 Some("-Wl,-rpath,$ORIGIN/../lib")
1117 if let Some(rpath) = rpath {
1118 rustflags.arg(&format!("-Clink-args={}", rpath));
1122 if let Some(host_linker) = self.linker(compiler.host) {
1123 cargo.env("RUSTC_HOST_LINKER", host_linker);
1125 if self.is_fuse_ld_lld(compiler.host) {
1126 cargo.env("RUSTC_HOST_FUSE_LD_LLD", "1");
1129 if let Some(target_linker) = self.linker(target) {
1130 let target = crate::envify(&target.triple);
1131 cargo.env(&format!("CARGO_TARGET_{}_LINKER", target), target_linker);
1133 if self.is_fuse_ld_lld(target) {
1134 rustflags.arg("-Clink-args=-fuse-ld=lld");
1137 if !(["build", "check", "clippy", "fix", "rustc"].contains(&cmd)) && want_rustdoc {
1138 cargo.env("RUSTDOC_LIBDIR", self.rustc_libdir(compiler));
1141 let debuginfo_level = match mode {
1142 Mode::Rustc | Mode::Codegen => self.config.rust_debuginfo_level_rustc,
1143 Mode::Std => self.config.rust_debuginfo_level_std,
1144 Mode::ToolBootstrap | Mode::ToolStd | Mode::ToolRustc => {
1145 self.config.rust_debuginfo_level_tools
1148 cargo.env(profile_var("DEBUG"), debuginfo_level.to_string());
1150 profile_var("DEBUG_ASSERTIONS"),
1151 if mode == Mode::Std {
1152 self.config.rust_debug_assertions_std.to_string()
1154 self.config.rust_debug_assertions.to_string()
1158 // `dsymutil` adds time to builds on Apple platforms for no clear benefit, and also makes
1159 // it more difficult for debuggers to find debug info. The compiler currently defaults to
1160 // running `dsymutil` to preserve its historical default, but when compiling the compiler
1161 // itself, we skip it by default since we know it's safe to do so in that case.
1162 // See https://github.com/rust-lang/rust/issues/79361 for more info on this flag.
1163 if target.contains("apple") {
1165 if self.config.rust_run_dsymutil {
1166 rustflags.arg("-Zrun-dsymutil=yes");
1168 rustflags.arg("-Zrun-dsymutil=no");
1171 if self.config.rust_run_dsymutil {
1172 rustflags.arg("-Csplit-debuginfo=packed");
1174 rustflags.arg("-Csplit-debuginfo=unpacked");
1179 if self.config.cmd.bless() {
1180 // Bless `expect!` tests.
1181 cargo.env("UPDATE_EXPECT", "1");
1184 if !mode.is_tool() {
1185 cargo.env("RUSTC_FORCE_UNSTABLE", "1");
1188 if let Some(x) = self.crt_static(target) {
1190 rustflags.arg("-Ctarget-feature=+crt-static");
1192 rustflags.arg("-Ctarget-feature=-crt-static");
1196 if let Some(x) = self.crt_static(compiler.host) {
1197 cargo.env("RUSTC_HOST_CRT_STATIC", x.to_string());
1200 if let Some(map_to) = self.build.debuginfo_map_to(GitRepo::Rustc) {
1201 let map = format!("{}={}", self.build.src.display(), map_to);
1202 cargo.env("RUSTC_DEBUGINFO_MAP", map);
1204 // `rustc` needs to know the virtual `/rustc/$hash` we're mapping to,
1205 // in order to opportunistically reverse it later.
1206 cargo.env("CFG_VIRTUAL_RUST_SOURCE_BASE_DIR", map_to);
1209 // Enable usage of unstable features
1210 cargo.env("RUSTC_BOOTSTRAP", "1");
1211 self.add_rust_test_threads(&mut cargo);
1213 // Almost all of the crates that we compile as part of the bootstrap may
1214 // have a build script, including the standard library. To compile a
1215 // build script, however, it itself needs a standard library! This
1216 // introduces a bit of a pickle when we're compiling the standard
1219 // To work around this we actually end up using the snapshot compiler
1220 // (stage0) for compiling build scripts of the standard library itself.
1221 // The stage0 compiler is guaranteed to have a libstd available for use.
1223 // For other crates, however, we know that we've already got a standard
1224 // library up and running, so we can use the normal compiler to compile
1225 // build scripts in that situation.
1226 if mode == Mode::Std {
1228 .env("RUSTC_SNAPSHOT", &self.initial_rustc)
1229 .env("RUSTC_SNAPSHOT_LIBDIR", self.rustc_snapshot_libdir());
1232 .env("RUSTC_SNAPSHOT", self.rustc(compiler))
1233 .env("RUSTC_SNAPSHOT_LIBDIR", self.rustc_libdir(compiler));
1236 // Tools that use compiler libraries may inherit the `-lLLVM` link
1237 // requirement, but the `-L` library path is not propagated across
1238 // separate Cargo projects. We can add LLVM's library path to the
1239 // platform-specific environment variable as a workaround.
1240 if mode == Mode::ToolRustc {
1241 if let Some(llvm_config) = self.llvm_config(target) {
1242 let llvm_libdir = output(Command::new(&llvm_config).arg("--libdir"));
1243 add_link_lib_path(vec![llvm_libdir.trim().into()], &mut cargo);
1247 // Compile everything except libraries and proc macros with the more
1248 // efficient initial-exec TLS model. This doesn't work with `dlopen`,
1249 // so we can't use it by default in general, but we can use it for tools
1250 // and our own internal libraries.
1251 if !mode.must_support_dlopen() {
1252 rustflags.arg("-Ztls-model=initial-exec");
1255 if self.config.incremental {
1256 cargo.env("CARGO_INCREMENTAL", "1");
1258 // Don't rely on any default setting for incr. comp. in Cargo
1259 cargo.env("CARGO_INCREMENTAL", "0");
1262 if let Some(ref on_fail) = self.config.on_fail {
1263 cargo.env("RUSTC_ON_FAIL", on_fail);
1266 if self.config.print_step_timings {
1267 cargo.env("RUSTC_PRINT_STEP_TIMINGS", "1");
1270 if self.config.backtrace_on_ice {
1271 cargo.env("RUSTC_BACKTRACE_ON_ICE", "1");
1274 cargo.env("RUSTC_VERBOSE", self.verbosity.to_string());
1276 if source_type == SourceType::InTree {
1277 let mut lint_flags = Vec::new();
1278 // When extending this list, add the new lints to the RUSTFLAGS of the
1279 // build_bootstrap function of src/bootstrap/bootstrap.py as well as
1280 // some code doesn't go through this `rustc` wrapper.
1281 lint_flags.push("-Wrust_2018_idioms");
1282 lint_flags.push("-Wunused_lifetimes");
1283 // cfg(bootstrap): unconditionally enable this warning after the next beta bump
1284 // This is currently disabled for the stage1 libstd, since build scripts
1285 // will end up using the bootstrap compiler (which doesn't yet support this lint)
1286 if compiler.stage != 0 && mode != Mode::Std {
1287 lint_flags.push("-Wsemicolon_in_expressions_from_macros");
1290 if self.config.deny_warnings {
1291 lint_flags.push("-Dwarnings");
1292 rustdocflags.arg("-Dwarnings");
1295 // FIXME(#58633) hide "unused attribute" errors in incremental
1296 // builds of the standard library, as the underlying checks are
1297 // not yet properly integrated with incremental recompilation.
1298 if mode == Mode::Std && compiler.stage == 0 && self.config.incremental {
1299 lint_flags.push("-Aunused-attributes");
1301 // This does not use RUSTFLAGS due to caching issues with Cargo.
1302 // Clippy is treated as an "in tree" tool, but shares the same
1303 // cache as other "submodule" tools. With these options set in
1304 // RUSTFLAGS, that causes *every* shared dependency to be rebuilt.
1305 // By injecting this into the rustc wrapper, this circumvents
1306 // Cargo's fingerprint detection. This is fine because lint flags
1307 // are always ignored in dependencies. Eventually this should be
1308 // fixed via better support from Cargo.
1309 cargo.env("RUSTC_LINT_FLAGS", lint_flags.join(" "));
1311 rustdocflags.arg("-Winvalid_codeblock_attributes");
1314 if mode == Mode::Rustc {
1315 rustflags.arg("-Zunstable-options");
1316 rustflags.arg("-Wrustc::internal");
1319 // Throughout the build Cargo can execute a number of build scripts
1320 // compiling C/C++ code and we need to pass compilers, archivers, flags, etc
1321 // obtained previously to those build scripts.
1322 // Build scripts use either the `cc` crate or `configure/make` so we pass
1323 // the options through environment variables that are fetched and understood by both.
1325 // FIXME: the guard against msvc shouldn't need to be here
1326 if target.contains("msvc") {
1327 if let Some(ref cl) = self.config.llvm_clang_cl {
1328 cargo.env("CC", cl).env("CXX", cl);
1331 let ccache = self.config.ccache.as_ref();
1332 let ccacheify = |s: &Path| {
1333 let ccache = match ccache {
1335 None => return s.display().to_string(),
1337 // FIXME: the cc-rs crate only recognizes the literal strings
1338 // `ccache` and `sccache` when doing caching compilations, so we
1339 // mirror that here. It should probably be fixed upstream to
1340 // accept a new env var or otherwise work with custom ccache
1343 "ccache" | "sccache" => format!("{} {}", ccache, s.display()),
1344 _ => s.display().to_string(),
1347 let cc = ccacheify(&self.cc(target));
1348 cargo.env(format!("CC_{}", target.triple), &cc);
1350 let cflags = self.cflags(target, GitRepo::Rustc).join(" ");
1351 cargo.env(format!("CFLAGS_{}", target.triple), &cflags);
1353 if let Some(ar) = self.ar(target) {
1354 let ranlib = format!("{} s", ar.display());
1356 .env(format!("AR_{}", target.triple), ar)
1357 .env(format!("RANLIB_{}", target.triple), ranlib);
1360 if let Ok(cxx) = self.cxx(target) {
1361 let cxx = ccacheify(&cxx);
1363 .env(format!("CXX_{}", target.triple), &cxx)
1364 .env(format!("CXXFLAGS_{}", target.triple), cflags);
1368 if mode == Mode::Std && self.config.extended && compiler.is_final_stage(self) {
1369 rustflags.arg("-Zsave-analysis");
1371 "RUST_SAVE_ANALYSIS_CONFIG",
1372 "{\"output_file\": null,\"full_docs\": false,\
1373 \"pub_only\": true,\"reachable_only\": false,\
1374 \"distro_crate\": true,\"signatures\": false,\"borrow_data\": false}",
1378 // If Control Flow Guard is enabled, pass the `control-flow-guard` flag to rustc
1379 // when compiling the standard library, since this might be linked into the final outputs
1380 // produced by rustc. Since this mitigation is only available on Windows, only enable it
1381 // for the standard library in case the compiler is run on a non-Windows platform.
1382 // This is not needed for stage 0 artifacts because these will only be used for building
1383 // the stage 1 compiler.
1385 && mode == Mode::Std
1386 && self.config.control_flow_guard
1387 && compiler.stage >= 1
1389 rustflags.arg("-Ccontrol-flow-guard");
1392 // For `cargo doc` invocations, make rustdoc print the Rust version into the docs
1393 // This replaces spaces with newlines because RUSTDOCFLAGS does not
1394 // support arguments with regular spaces. Hopefully someday Cargo will
1395 // have space support.
1396 let rust_version = self.rust_version().replace(' ', "\n");
1397 rustdocflags.arg("--crate-version").arg(&rust_version);
1399 // Environment variables *required* throughout the build
1401 // FIXME: should update code to not require this env var
1402 cargo.env("CFG_COMPILER_HOST_TRIPLE", target.triple);
1404 // Set this for all builds to make sure doc builds also get it.
1405 cargo.env("CFG_RELEASE_CHANNEL", &self.config.channel);
1407 // This one's a bit tricky. As of the time of this writing the compiler
1408 // links to the `winapi` crate on crates.io. This crate provides raw
1409 // bindings to Windows system functions, sort of like libc does for
1410 // Unix. This crate also, however, provides "import libraries" for the
1411 // MinGW targets. There's an import library per dll in the windows
1412 // distribution which is what's linked to. These custom import libraries
1413 // are used because the winapi crate can reference Windows functions not
1414 // present in the MinGW import libraries.
1416 // For example MinGW may ship libdbghelp.a, but it may not have
1417 // references to all the functions in the dbghelp dll. Instead the
1418 // custom import library for dbghelp in the winapi crates has all this
1421 // Unfortunately for us though the import libraries are linked by
1422 // default via `-ldylib=winapi_foo`. That is, they're linked with the
1423 // `dylib` type with a `winapi_` prefix (so the winapi ones don't
1424 // conflict with the system MinGW ones). This consequently means that
1425 // the binaries we ship of things like rustc_codegen_llvm (aka the rustc_codegen_llvm
1426 // DLL) when linked against *again*, for example with procedural macros
1427 // or plugins, will trigger the propagation logic of `-ldylib`, passing
1428 // `-lwinapi_foo` to the linker again. This isn't actually available in
1429 // our distribution, however, so the link fails.
1431 // To solve this problem we tell winapi to not use its bundled import
1432 // libraries. This means that it will link to the system MinGW import
1433 // libraries by default, and the `-ldylib=foo` directives will still get
1434 // passed to the final linker, but they'll look like `-lfoo` which can
1435 // be resolved because MinGW has the import library. The downside is we
1436 // don't get newer functions from Windows, but we don't use any of them
1438 if !mode.is_tool() {
1439 cargo.env("WINAPI_NO_BUNDLED_LIBRARIES", "1");
1442 for _ in 1..self.verbosity {
1446 match (mode, self.config.rust_codegen_units_std, self.config.rust_codegen_units) {
1447 (Mode::Std, Some(n), _) | (_, _, Some(n)) => {
1448 cargo.env(profile_var("CODEGEN_UNITS"), n.to_string());
1451 // Don't set anything
1455 if self.config.rust_optimize {
1456 // FIXME: cargo bench/install do not accept `--release`
1457 if cmd != "bench" && cmd != "install" {
1458 cargo.arg("--release");
1462 if self.config.locked_deps {
1463 cargo.arg("--locked");
1465 if self.config.vendor || self.is_sudo {
1466 cargo.arg("--frozen");
1469 // Try to use a sysroot-relative bindir, in case it was configured absolutely.
1470 cargo.env("RUSTC_INSTALL_BINDIR", self.config.bindir_relative());
1472 self.ci_env.force_coloring_in_ci(&mut cargo);
1474 // When we build Rust dylibs they're all intended for intermediate
1475 // usage, so make sure we pass the -Cprefer-dynamic flag instead of
1476 // linking all deps statically into the dylib.
1477 if matches!(mode, Mode::Std | Mode::Rustc) {
1478 rustflags.arg("-Cprefer-dynamic");
1481 // When building incrementally we default to a lower ThinLTO import limit
1482 // (unless explicitly specified otherwise). This will produce a somewhat
1483 // slower code but give way better compile times.
1485 let limit = match self.config.rust_thin_lto_import_instr_limit {
1486 Some(limit) => Some(limit),
1487 None if self.config.incremental => Some(10),
1491 if let Some(limit) = limit {
1492 rustflags.arg(&format!("-Cllvm-args=-import-instr-limit={}", limit));
1496 Cargo { command: cargo, rustflags, rustdocflags }
1499 /// Ensure that a given step is built, returning its output. This will
1500 /// cache the step, so it is safe (and good!) to call this as often as
1501 /// needed to ensure that all dependencies are built.
1502 pub fn ensure<S: Step>(&'a self, step: S) -> S::Output {
1504 let mut stack = self.stack.borrow_mut();
1505 for stack_step in stack.iter() {
1507 if stack_step.downcast_ref::<S>().map_or(true, |stack_step| *stack_step != step) {
1510 let mut out = String::new();
1511 out += &format!("\n\nCycle in build detected when adding {:?}\n", step);
1512 for el in stack.iter().rev() {
1513 out += &format!("\t{:?}\n", el);
1517 if let Some(out) = self.cache.get(&step) {
1518 self.verbose(&format!("{}c {:?}", " ".repeat(stack.len()), step));
1522 self.verbose(&format!("{}> {:?}", " ".repeat(stack.len()), step));
1523 stack.push(Box::new(step.clone()));
1527 let start = Instant::now();
1528 let zero = Duration::new(0, 0);
1529 let parent = self.time_spent_on_dependencies.replace(zero);
1530 let out = step.clone().run(self);
1531 let dur = start.elapsed();
1532 let deps = self.time_spent_on_dependencies.replace(parent + dur);
1536 if self.config.print_step_timings && !self.config.dry_run {
1537 println!("[TIMING] {:?} -- {}.{:03}", step, dur.as_secs(), dur.subsec_millis());
1541 let mut stack = self.stack.borrow_mut();
1542 let cur_step = stack.pop().expect("step stack empty");
1543 assert_eq!(cur_step.downcast_ref(), Some(&step));
1545 self.verbose(&format!("{}< {:?}", " ".repeat(self.stack.borrow().len()), step));
1546 self.cache.put(step, out.clone());
1554 #[derive(Debug, Clone)]
1555 struct Rustflags(String);
1558 fn new(target: TargetSelection) -> Rustflags {
1559 let mut ret = Rustflags(String::new());
1561 // Inherit `RUSTFLAGS` by default ...
1562 ret.env("RUSTFLAGS");
1564 // ... and also handle target-specific env RUSTFLAGS if they're
1566 let target_specific = format!("CARGO_TARGET_{}_RUSTFLAGS", crate::envify(&target.triple));
1567 ret.env(&target_specific);
1572 fn env(&mut self, env: &str) {
1573 if let Ok(s) = env::var(env) {
1574 for part in s.split(' ') {
1580 fn arg(&mut self, arg: &str) -> &mut Self {
1581 assert_eq!(arg.split(' ').count(), 1);
1582 if !self.0.is_empty() {
1585 self.0.push_str(arg);
1593 rustflags: Rustflags,
1594 rustdocflags: Rustflags,
1598 pub fn rustdocflag(&mut self, arg: &str) -> &mut Cargo {
1599 self.rustdocflags.arg(arg);
1602 pub fn rustflag(&mut self, arg: &str) -> &mut Cargo {
1603 self.rustflags.arg(arg);
1607 pub fn arg(&mut self, arg: impl AsRef<OsStr>) -> &mut Cargo {
1608 self.command.arg(arg.as_ref());
1612 pub fn args<I, S>(&mut self, args: I) -> &mut Cargo
1614 I: IntoIterator<Item = S>,
1618 self.arg(arg.as_ref());
1623 pub fn env(&mut self, key: impl AsRef<OsStr>, value: impl AsRef<OsStr>) -> &mut Cargo {
1624 // These are managed through rustflag/rustdocflag interfaces.
1625 assert_ne!(key.as_ref(), "RUSTFLAGS");
1626 assert_ne!(key.as_ref(), "RUSTDOCFLAGS");
1627 self.command.env(key.as_ref(), value.as_ref());
1631 pub fn add_rustc_lib_path(&mut self, builder: &Builder<'_>, compiler: Compiler) {
1632 builder.add_rustc_lib_path(compiler, &mut self.command);
1636 impl From<Cargo> for Command {
1637 fn from(mut cargo: Cargo) -> Command {
1638 let rustflags = &cargo.rustflags.0;
1639 if !rustflags.is_empty() {
1640 cargo.command.env("RUSTFLAGS", rustflags);
1643 let rustdocflags = &cargo.rustdocflags.0;
1644 if !rustdocflags.is_empty() {
1645 cargo.command.env("RUSTDOCFLAGS", rustdocflags);