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;
32 // FIXME: replace with std::lazy after it gets stabilized and reaches beta
33 use once_cell::sync::Lazy;
35 pub struct Builder<'a> {
40 stack: RefCell<Vec<Box<dyn Any>>>,
41 time_spent_on_dependencies: Cell<Duration>,
42 pub paths: Vec<PathBuf>,
45 impl<'a> Deref for Builder<'a> {
48 fn deref(&self) -> &Self::Target {
53 pub trait Step: 'static + Clone + Debug + PartialEq + Eq + Hash {
54 /// `PathBuf` when directories are created or to return a `Compiler` once
55 /// it's been assembled.
58 /// Whether this step is run by default as part of its respective phase.
59 /// `true` here can still be overwritten by `should_run` calling `default_condition`.
60 const DEFAULT: bool = false;
62 /// If true, then this rule should be skipped if --target was specified, but --host was not
63 const ONLY_HOSTS: bool = false;
65 /// Primary function to execute this rule. Can call `builder.ensure()`
66 /// with other steps to run those.
67 fn run(self, builder: &Builder<'_>) -> Self::Output;
69 /// When bootstrap is passed a set of paths, this controls whether this rule
70 /// will execute. However, it does not get called in a "default" context
71 /// when we are not passed any paths; in that case, `make_run` is called
73 fn should_run(run: ShouldRun<'_>) -> ShouldRun<'_>;
75 /// Builds up a "root" rule, either as a default rule or from a path passed
78 /// When path is `None`, we are executing in a context where no paths were
79 /// passed. When `./x.py build` is run, for example, this rule could get
80 /// called if it is in the correct list below with a path of `None`.
81 fn make_run(_run: RunConfig<'_>) {
82 // It is reasonable to not have an implementation of make_run for rules
83 // who do not want to get called from the root context. This means that
84 // they are likely dependencies (e.g., sysroot creation) or similar, and
85 // as such calling them from ./x.py isn't logical.
90 pub struct RunConfig<'a> {
91 pub builder: &'a Builder<'a>,
92 pub target: TargetSelection,
97 pub fn build_triple(&self) -> TargetSelection {
98 self.builder.build.build
102 struct StepDescription {
105 should_run: fn(ShouldRun<'_>) -> ShouldRun<'_>,
106 make_run: fn(RunConfig<'_>),
110 /// Collection of paths used to match a task rule.
111 #[derive(Debug, Clone, PartialOrd, Ord, PartialEq, Eq)]
113 /// A collection of individual paths.
115 /// These are generally matched as a path suffix. For example, a
116 /// command-line value of `libstd` will match if `src/libstd` is in the
118 Set(BTreeSet<PathBuf>),
119 /// A "suite" of paths.
121 /// These can match as a path suffix (like `Set`), or as a prefix. For
122 /// example, a command-line value of `src/test/ui/abi/variadic-ffi.rs`
123 /// will match `src/test/ui`. A command-line value of `ui` would also
124 /// match `src/test/ui`.
129 fn empty() -> PathSet {
130 PathSet::Set(BTreeSet::new())
133 fn one<P: Into<PathBuf>>(path: P) -> PathSet {
134 let mut set = BTreeSet::new();
135 set.insert(path.into());
139 fn has(&self, needle: &Path) -> bool {
141 PathSet::Set(set) => set.iter().any(|p| p.ends_with(needle)),
142 PathSet::Suite(suite) => suite.ends_with(needle),
146 fn path(&self, builder: &Builder<'_>) -> PathBuf {
148 PathSet::Set(set) => set.iter().next().unwrap_or(&builder.build.src).to_path_buf(),
149 PathSet::Suite(path) => PathBuf::from(path),
154 impl StepDescription {
155 fn from<S: Step>() -> StepDescription {
158 only_hosts: S::ONLY_HOSTS,
159 should_run: S::should_run,
160 make_run: S::make_run,
161 name: std::any::type_name::<S>(),
165 fn maybe_run(&self, builder: &Builder<'_>, pathset: &PathSet) {
166 if self.is_excluded(builder, pathset) {
170 // Determine the targets participating in this rule.
171 let targets = if self.only_hosts { &builder.hosts } else { &builder.targets };
173 for target in targets {
174 let run = RunConfig { builder, path: pathset.path(builder), target: *target };
175 (self.make_run)(run);
179 fn is_excluded(&self, builder: &Builder<'_>, pathset: &PathSet) -> bool {
180 if builder.config.exclude.iter().any(|e| pathset.has(e)) {
181 eprintln!("Skipping {:?} because it is excluded", pathset);
185 if !builder.config.exclude.is_empty() {
187 "{:?} not skipped for {:?} -- not in {:?}",
188 pathset, self.name, builder.config.exclude
194 fn run(v: &[StepDescription], builder: &Builder<'_>, paths: &[PathBuf]) {
196 v.iter().map(|desc| (desc.should_run)(ShouldRun::new(builder))).collect::<Vec<_>>();
198 // sanity checks on rules
199 for (desc, should_run) in v.iter().zip(&should_runs) {
201 !should_run.paths.is_empty(),
202 "{:?} should have at least one pathset",
207 if paths.is_empty() || builder.config.include_default_paths {
208 for (desc, should_run) in v.iter().zip(&should_runs) {
209 if desc.default && should_run.is_really_default() {
210 for pathset in &should_run.paths {
211 desc.maybe_run(builder, pathset);
218 // strip CurDir prefix if present
219 let path = match path.strip_prefix(".") {
224 let mut attempted_run = false;
225 for (desc, should_run) in v.iter().zip(&should_runs) {
226 if let Some(suite) = should_run.is_suite_path(path) {
227 attempted_run = true;
228 desc.maybe_run(builder, suite);
229 } else if let Some(pathset) = should_run.pathset_for_path(path) {
230 attempted_run = true;
231 desc.maybe_run(builder, pathset);
236 panic!("error: no rules matched {}", path.display());
242 enum ReallyDefault<'a> {
244 Lazy(Lazy<bool, Box<dyn Fn() -> bool + 'a>>),
247 pub struct ShouldRun<'a> {
248 pub builder: &'a Builder<'a>,
249 // use a BTreeSet to maintain sort order
250 paths: BTreeSet<PathSet>,
252 // If this is a default rule, this is an additional constraint placed on
253 // its run. Generally something like compiler docs being enabled.
254 is_really_default: ReallyDefault<'a>,
257 impl<'a> ShouldRun<'a> {
258 fn new(builder: &'a Builder<'_>) -> ShouldRun<'a> {
261 paths: BTreeSet::new(),
262 is_really_default: ReallyDefault::Bool(true), // by default no additional conditions
266 pub fn default_condition(mut self, cond: bool) -> Self {
267 self.is_really_default = ReallyDefault::Bool(cond);
271 pub fn lazy_default_condition(mut self, lazy_cond: Box<dyn Fn() -> bool + 'a>) -> Self {
272 self.is_really_default = ReallyDefault::Lazy(Lazy::new(lazy_cond));
276 pub fn is_really_default(&self) -> bool {
277 match &self.is_really_default {
278 ReallyDefault::Bool(val) => *val,
279 ReallyDefault::Lazy(lazy) => *lazy.deref(),
283 /// Indicates it should run if the command-line selects the given crate or
284 /// any of its (local) dependencies.
286 /// Compared to `krate`, this treats the dependencies as aliases for the
287 /// same job. Generally it is preferred to use `krate`, and treat each
288 /// individual path separately. For example `./x.py test src/liballoc`
289 /// (which uses `krate`) will test just `liballoc`. However, `./x.py check
290 /// src/liballoc` (which uses `all_krates`) will check all of `libtest`.
291 /// `all_krates` should probably be removed at some point.
292 pub fn all_krates(mut self, name: &str) -> Self {
293 let mut set = BTreeSet::new();
294 for krate in self.builder.in_tree_crates(name, None) {
295 let path = krate.local_path(self.builder);
298 self.paths.insert(PathSet::Set(set));
302 /// Indicates it should run if the command-line selects the given crate or
303 /// any of its (local) dependencies.
305 /// `make_run` will be called separately for each matching command-line path.
306 pub fn krate(mut self, name: &str) -> Self {
307 for krate in self.builder.in_tree_crates(name, None) {
308 let path = krate.local_path(self.builder);
309 self.paths.insert(PathSet::one(path));
314 // single, non-aliased path
315 pub fn path(self, path: &str) -> Self {
319 // multiple aliases for the same job
320 pub fn paths(mut self, paths: &[&str]) -> Self {
321 self.paths.insert(PathSet::Set(paths.iter().map(PathBuf::from).collect()));
325 pub fn is_suite_path(&self, path: &Path) -> Option<&PathSet> {
326 self.paths.iter().find(|pathset| match pathset {
327 PathSet::Suite(p) => path.starts_with(p),
328 PathSet::Set(_) => false,
332 pub fn suite_path(mut self, suite: &str) -> Self {
333 self.paths.insert(PathSet::Suite(PathBuf::from(suite)));
337 // allows being more explicit about why should_run in Step returns the value passed to it
338 pub fn never(mut self) -> ShouldRun<'a> {
339 self.paths.insert(PathSet::empty());
343 fn pathset_for_path(&self, path: &Path) -> Option<&PathSet> {
344 self.paths.iter().find(|pathset| pathset.has(path))
348 #[derive(Copy, Clone, PartialEq, Eq, Debug)]
362 impl<'a> Builder<'a> {
363 fn get_step_descriptions(kind: Kind) -> Vec<StepDescription> {
364 macro_rules! describe {
365 ($($rule:ty),+ $(,)?) => {{
366 vec![$(StepDescription::from::<$rule>()),+]
370 Kind::Build => describe!(
373 compile::CodegenBackend,
374 compile::StartupObjects,
378 tool::UnstableBookGen,
383 tool::RemoteTestServer,
384 tool::RemoteTestClient,
401 Kind::Check | Kind::Clippy { .. } | Kind::Fix => describe!(
405 check::CodegenBackend,
412 Kind::Test => describe!(
413 crate::toolstate::ToolStateCheck,
414 test::ExpandYamlAnchors,
417 test::RunPassValgrind,
430 test::CrateRustdocJsonTypes,
438 test::RunMakeFullDeps,
454 test::CompiletestTest,
456 test::RustdocJSNotStd,
462 // Run bootstrap close to the end as it's unlikely to fail
464 // Run run-make last, since these won't pass without make on Windows
467 Kind::Bench => describe!(test::Crate, test::CrateLibrustc),
468 Kind::Doc => describe!(
470 doc::UnstableBookGen,
488 Kind::Dist => describe!(
493 dist::DebuggerScripts,
498 dist::PlainSourceTarball,
510 dist::ReproducibleArtifacts,
512 Kind::Install => describe!(
517 install::RustAnalyzer,
519 install::RustDemangler,
526 Kind::Run => describe!(run::ExpandYamlAnchors, run::BuildManifest, run::BumpStage0),
530 pub fn get_help(build: &Build, subcommand: &str) -> Option<String> {
531 let kind = match subcommand {
532 "build" => Kind::Build,
534 "test" => Kind::Test,
535 "bench" => Kind::Bench,
536 "dist" => Kind::Dist,
537 "install" => Kind::Install,
541 let builder = Self::new_internal(build, kind, vec![]);
542 let builder = &builder;
543 let mut should_run = ShouldRun::new(builder);
544 for desc in Builder::get_step_descriptions(builder.kind) {
545 should_run = (desc.should_run)(should_run);
547 let mut help = String::from("Available paths:\n");
548 let mut add_path = |path: &Path| {
549 help.push_str(&format!(" ./x.py {} {}\n", subcommand, path.display()));
551 for pathset in should_run.paths {
553 PathSet::Set(set) => {
558 PathSet::Suite(path) => {
559 add_path(&path.join("..."));
566 fn new_internal(build: &Build, kind: Kind, paths: Vec<PathBuf>) -> Builder<'_> {
569 top_stage: build.config.stage,
572 stack: RefCell::new(Vec::new()),
573 time_spent_on_dependencies: Cell::new(Duration::new(0, 0)),
578 pub fn new(build: &Build) -> Builder<'_> {
579 let (kind, paths) = match build.config.cmd {
580 Subcommand::Build { ref paths } => (Kind::Build, &paths[..]),
581 Subcommand::Check { ref paths } => (Kind::Check, &paths[..]),
582 Subcommand::Clippy { ref paths, .. } => (Kind::Clippy, &paths[..]),
583 Subcommand::Fix { ref paths } => (Kind::Fix, &paths[..]),
584 Subcommand::Doc { ref paths, .. } => (Kind::Doc, &paths[..]),
585 Subcommand::Test { ref paths, .. } => (Kind::Test, &paths[..]),
586 Subcommand::Bench { ref paths, .. } => (Kind::Bench, &paths[..]),
587 Subcommand::Dist { ref paths } => (Kind::Dist, &paths[..]),
588 Subcommand::Install { ref paths } => (Kind::Install, &paths[..]),
589 Subcommand::Run { ref paths } => (Kind::Run, &paths[..]),
590 Subcommand::Format { .. } | Subcommand::Clean { .. } | Subcommand::Setup { .. } => {
595 Self::new_internal(build, kind, paths.to_owned())
598 pub fn execute_cli(&self) {
599 self.run_step_descriptions(&Builder::get_step_descriptions(self.kind), &self.paths);
602 pub fn default_doc(&self, paths: &[PathBuf]) {
603 self.run_step_descriptions(&Builder::get_step_descriptions(Kind::Doc), paths);
606 /// NOTE: keep this in sync with `rustdoc::clean::utils::doc_rust_lang_org_channel`, or tests will fail on beta/stable.
607 pub fn doc_rust_lang_org_channel(&self) -> String {
608 let channel = match &*self.config.channel {
609 "stable" => &self.version,
611 "nightly" | "dev" => "nightly",
612 // custom build of rustdoc maybe? link to the latest stable docs just in case
615 "https://doc.rust-lang.org/".to_owned() + channel
618 fn run_step_descriptions(&self, v: &[StepDescription], paths: &[PathBuf]) {
619 StepDescription::run(v, self, paths);
622 /// Obtain a compiler at a given stage and for a given host. Explicitly does
623 /// not take `Compiler` since all `Compiler` instances are meant to be
624 /// obtained through this function, since it ensures that they are valid
625 /// (i.e., built and assembled).
626 pub fn compiler(&self, stage: u32, host: TargetSelection) -> Compiler {
627 self.ensure(compile::Assemble { target_compiler: Compiler { stage, host } })
630 /// Similar to `compiler`, except handles the full-bootstrap option to
631 /// silently use the stage1 compiler instead of a stage2 compiler if one is
634 /// Note that this does *not* have the side effect of creating
635 /// `compiler(stage, host)`, unlike `compiler` above which does have such
636 /// a side effect. The returned compiler here can only be used to compile
637 /// new artifacts, it can't be used to rely on the presence of a particular
640 /// See `force_use_stage1` for documentation on what each argument is.
644 host: TargetSelection,
645 target: TargetSelection,
647 if self.build.force_use_stage1(Compiler { stage, host }, target) {
648 self.compiler(1, self.config.build)
650 self.compiler(stage, host)
654 pub fn sysroot(&self, compiler: Compiler) -> Interned<PathBuf> {
655 self.ensure(compile::Sysroot { compiler })
658 /// Returns the libdir where the standard library and other artifacts are
659 /// found for a compiler's sysroot.
660 pub fn sysroot_libdir(&self, compiler: Compiler, target: TargetSelection) -> Interned<PathBuf> {
661 #[derive(Debug, Copy, Clone, Hash, PartialEq, Eq)]
664 target: TargetSelection,
666 impl Step for Libdir {
667 type Output = Interned<PathBuf>;
669 fn should_run(run: ShouldRun<'_>) -> ShouldRun<'_> {
673 fn run(self, builder: &Builder<'_>) -> Interned<PathBuf> {
674 let lib = builder.sysroot_libdir_relative(self.compiler);
675 let sysroot = builder
676 .sysroot(self.compiler)
679 .join(self.target.triple)
681 // Avoid deleting the rustlib/ directory we just copied
682 // (in `impl Step for Sysroot`).
683 if !builder.config.download_rustc {
684 let _ = fs::remove_dir_all(&sysroot);
685 t!(fs::create_dir_all(&sysroot));
687 INTERNER.intern_path(sysroot)
690 self.ensure(Libdir { compiler, target })
693 pub fn sysroot_codegen_backends(&self, compiler: Compiler) -> PathBuf {
694 self.sysroot_libdir(compiler, compiler.host).with_file_name("codegen-backends")
697 /// Returns the compiler's libdir where it stores the dynamic libraries that
698 /// it itself links against.
700 /// For example this returns `<sysroot>/lib` on Unix and `<sysroot>/bin` on
702 pub fn rustc_libdir(&self, compiler: Compiler) -> PathBuf {
703 if compiler.is_snapshot(self) {
704 self.rustc_snapshot_libdir()
706 match self.config.libdir_relative() {
707 Some(relative_libdir) if compiler.stage >= 1 => {
708 self.sysroot(compiler).join(relative_libdir)
710 _ => self.sysroot(compiler).join(libdir(compiler.host)),
715 /// Returns the compiler's relative libdir where it stores the dynamic libraries that
716 /// it itself links against.
718 /// For example this returns `lib` on Unix and `bin` on
720 pub fn libdir_relative(&self, compiler: Compiler) -> &Path {
721 if compiler.is_snapshot(self) {
722 libdir(self.config.build).as_ref()
724 match self.config.libdir_relative() {
725 Some(relative_libdir) if compiler.stage >= 1 => relative_libdir,
726 _ => libdir(compiler.host).as_ref(),
731 /// Returns the compiler's relative libdir where the standard library and other artifacts are
732 /// found for a compiler's sysroot.
734 /// For example this returns `lib` on Unix and Windows.
735 pub fn sysroot_libdir_relative(&self, compiler: Compiler) -> &Path {
736 match self.config.libdir_relative() {
737 Some(relative_libdir) if compiler.stage >= 1 => relative_libdir,
738 _ if compiler.stage == 0 => &self.build.initial_libdir,
739 _ => Path::new("lib"),
743 /// Adds the compiler's directory of dynamic libraries to `cmd`'s dynamic
744 /// library lookup path.
745 pub fn add_rustc_lib_path(&self, compiler: Compiler, cmd: &mut Command) {
746 // Windows doesn't need dylib path munging because the dlls for the
747 // compiler live next to the compiler and the system will find them
753 let mut dylib_dirs = vec![self.rustc_libdir(compiler)];
755 // Ensure that the downloaded LLVM libraries can be found.
756 if self.config.llvm_from_ci {
757 let ci_llvm_lib = self.out.join(&*compiler.host.triple).join("ci-llvm").join("lib");
758 dylib_dirs.push(ci_llvm_lib);
761 add_dylib_path(dylib_dirs, cmd);
764 /// Gets a path to the compiler specified.
765 pub fn rustc(&self, compiler: Compiler) -> PathBuf {
766 if compiler.is_snapshot(self) {
767 self.initial_rustc.clone()
769 self.sysroot(compiler).join("bin").join(exe("rustc", compiler.host))
773 /// Gets the paths to all of the compiler's codegen backends.
774 fn codegen_backends(&self, compiler: Compiler) -> impl Iterator<Item = PathBuf> {
775 fs::read_dir(self.sysroot_codegen_backends(compiler))
778 .filter_map(Result::ok)
779 .map(|entry| entry.path())
782 pub fn rustdoc(&self, compiler: Compiler) -> PathBuf {
783 self.ensure(tool::Rustdoc { compiler })
786 pub fn rustdoc_cmd(&self, compiler: Compiler) -> Command {
787 let mut cmd = Command::new(&self.out.join("bootstrap/debug/rustdoc"));
788 cmd.env("RUSTC_STAGE", compiler.stage.to_string())
789 .env("RUSTC_SYSROOT", self.sysroot(compiler))
790 // Note that this is *not* the sysroot_libdir because rustdoc must be linked
791 // equivalently to rustc.
792 .env("RUSTDOC_LIBDIR", self.rustc_libdir(compiler))
793 .env("CFG_RELEASE_CHANNEL", &self.config.channel)
794 .env("RUSTDOC_REAL", self.rustdoc(compiler))
795 .env("RUSTC_BOOTSTRAP", "1");
797 cmd.arg("-Wrustdoc::invalid_codeblock_attributes");
799 if self.config.deny_warnings {
800 cmd.arg("-Dwarnings");
802 cmd.arg("-Znormalize-docs");
804 // Remove make-related flags that can cause jobserver problems.
805 cmd.env_remove("MAKEFLAGS");
806 cmd.env_remove("MFLAGS");
808 if let Some(linker) = self.linker(compiler.host) {
809 cmd.env("RUSTDOC_LINKER", linker);
811 if self.is_fuse_ld_lld(compiler.host) {
812 cmd.env("RUSTDOC_FUSE_LD_LLD", "1");
817 /// Return the path to `llvm-config` for the target, if it exists.
819 /// Note that this returns `None` if LLVM is disabled, or if we're in a
820 /// check build or dry-run, where there's no need to build all of LLVM.
821 fn llvm_config(&self, target: TargetSelection) -> Option<PathBuf> {
822 if self.config.llvm_enabled() && self.kind != Kind::Check && !self.config.dry_run {
823 let llvm_config = self.ensure(native::Llvm { target });
824 if llvm_config.is_file() {
825 return Some(llvm_config);
831 /// Prepares an invocation of `cargo` to be run.
833 /// This will create a `Command` that represents a pending execution of
834 /// Cargo. This cargo will be configured to use `compiler` as the actual
835 /// rustc compiler, its output will be scoped by `mode`'s output directory,
836 /// it will pass the `--target` flag for the specified `target`, and will be
837 /// executing the Cargo command `cmd`.
842 source_type: SourceType,
843 target: TargetSelection,
846 let mut cargo = Command::new(&self.initial_cargo);
847 let out_dir = self.stage_out(compiler, mode);
849 // Codegen backends are not yet tracked by -Zbinary-dep-depinfo,
850 // so we need to explicitly clear out if they've been updated.
851 for backend in self.codegen_backends(compiler) {
852 self.clear_if_dirty(&out_dir, &backend);
855 if cmd == "doc" || cmd == "rustdoc" {
856 let my_out = match mode {
857 // This is the intended out directory for compiler documentation.
858 Mode::Rustc | Mode::ToolRustc => self.compiler_doc_out(target),
859 Mode::Std => out_dir.join(target.triple).join("doc"),
860 _ => panic!("doc mode {:?} not expected", mode),
862 let rustdoc = self.rustdoc(compiler);
863 self.clear_if_dirty(&my_out, &rustdoc);
866 cargo.env("CARGO_TARGET_DIR", &out_dir).arg(cmd);
868 let profile_var = |name: &str| {
869 let profile = if self.config.rust_optimize { "RELEASE" } else { "DEV" };
870 format!("CARGO_PROFILE_{}_{}", profile, name)
873 // See comment in rustc_llvm/build.rs for why this is necessary, largely llvm-config
874 // needs to not accidentally link to libLLVM in stage0/lib.
875 cargo.env("REAL_LIBRARY_PATH_VAR", &util::dylib_path_var());
876 if let Some(e) = env::var_os(util::dylib_path_var()) {
877 cargo.env("REAL_LIBRARY_PATH", e);
880 // Found with `rg "init_env_logger\("`. If anyone uses `init_env_logger`
881 // from out of tree it shouldn't matter, since x.py is only used for
883 let color_logs = ["RUSTDOC_LOG_COLOR", "RUSTC_LOG_COLOR", "RUST_LOG_COLOR"];
884 match self.build.config.color {
886 cargo.arg("--color=always");
887 for log in &color_logs {
888 cargo.env(log, "always");
892 cargo.arg("--color=never");
893 for log in &color_logs {
894 cargo.env(log, "never");
897 Color::Auto => {} // nothing to do
900 if cmd != "install" {
901 cargo.arg("--target").arg(target.rustc_target_arg());
903 assert_eq!(target, compiler.host);
906 // Set a flag for `check`/`clippy`/`fix`, so that certain build
907 // scripts can do less work (i.e. not building/requiring LLVM).
908 if cmd == "check" || cmd == "clippy" || cmd == "fix" {
909 // If we've not yet built LLVM, or it's stale, then bust
910 // the rustc_llvm cache. That will always work, even though it
911 // may mean that on the next non-check build we'll need to rebuild
912 // rustc_llvm. But if LLVM is stale, that'll be a tiny amount
913 // of work comparitively, and we'd likely need to rebuild it anyway,
915 if crate::native::prebuilt_llvm_config(self, target).is_err() {
916 cargo.env("RUST_CHECK", "1");
920 let stage = if compiler.stage == 0 && self.local_rebuild {
921 // Assume the local-rebuild rustc already has stage1 features.
927 let mut rustflags = Rustflags::new(target);
929 if let Ok(s) = env::var("CARGOFLAGS_NOT_BOOTSTRAP") {
930 cargo.args(s.split_whitespace());
932 rustflags.env("RUSTFLAGS_NOT_BOOTSTRAP");
934 if let Ok(s) = env::var("CARGOFLAGS_BOOTSTRAP") {
935 cargo.args(s.split_whitespace());
937 rustflags.env("RUSTFLAGS_BOOTSTRAP");
939 // clippy overwrites sysroot if we pass it to cargo.
940 // Pass it directly to clippy instead.
941 // NOTE: this can't be fixed in clippy because we explicitly don't set `RUSTC`,
942 // so it has no way of knowing the sysroot.
943 rustflags.arg("--sysroot");
945 self.sysroot(compiler)
948 .expect("sysroot must be valid UTF-8"),
950 // Only run clippy on a very limited subset of crates (in particular, not build scripts).
951 cargo.arg("-Zunstable-options");
952 // Explicitly does *not* set `--cfg=bootstrap`, since we're using a nightly clippy.
953 let host_version = Command::new("rustc").arg("--version").output().map_err(|_| ());
954 let output = host_version.and_then(|output| {
955 if output.status.success() {
960 }).unwrap_or_else(|_| {
962 "error: `x.py clippy` requires a host `rustc` toolchain with the `clippy` component"
964 eprintln!("help: try `rustup component add clippy`");
965 std::process::exit(1);
967 if !t!(std::str::from_utf8(&output.stdout)).contains("nightly") {
968 rustflags.arg("--cfg=bootstrap");
971 rustflags.arg("--cfg=bootstrap");
975 let use_new_symbol_mangling = match self.config.rust_new_symbol_mangling {
977 // If an explicit setting is given, use that
981 if mode == Mode::Std {
982 // The standard library defaults to the legacy scheme
985 // The compiler and tools default to the new scheme
991 // cfg(bootstrap) -- drop the compiler.stage == 0 branch.
992 if compiler.stage == 0 {
993 if use_new_symbol_mangling {
994 rustflags.arg("-Zsymbol-mangling-version=v0");
996 rustflags.arg("-Zsymbol-mangling-version=legacy");
999 if use_new_symbol_mangling {
1000 rustflags.arg("-Csymbol-mangling-version=v0");
1002 rustflags.arg("-Csymbol-mangling-version=legacy");
1003 rustflags.arg("-Zunstable-options");
1007 // FIXME: It might be better to use the same value for both `RUSTFLAGS` and `RUSTDOCFLAGS`,
1008 // but this breaks CI. At the very least, stage0 `rustdoc` needs `--cfg bootstrap`. See
1010 let mut rustdocflags = rustflags.clone();
1011 rustdocflags.propagate_cargo_env("RUSTDOCFLAGS");
1013 rustdocflags.env("RUSTDOCFLAGS_BOOTSTRAP");
1015 rustdocflags.env("RUSTDOCFLAGS_NOT_BOOTSTRAP");
1018 if let Ok(s) = env::var("CARGOFLAGS") {
1019 cargo.args(s.split_whitespace());
1023 Mode::Std | Mode::ToolBootstrap | Mode::ToolStd => {}
1024 Mode::Rustc | Mode::Codegen | Mode::ToolRustc => {
1025 // Build proc macros both for the host and the target
1026 if target != compiler.host && cmd != "check" {
1027 cargo.arg("-Zdual-proc-macros");
1028 rustflags.arg("-Zdual-proc-macros");
1033 // This tells Cargo (and in turn, rustc) to output more complete
1034 // dependency information. Most importantly for rustbuild, this
1035 // includes sysroot artifacts, like libstd, which means that we don't
1036 // need to track those in rustbuild (an error prone process!). This
1037 // feature is currently unstable as there may be some bugs and such, but
1038 // it represents a big improvement in rustbuild's reliability on
1039 // rebuilds, so we're using it here.
1041 // For some additional context, see #63470 (the PR originally adding
1042 // this), as well as #63012 which is the tracking issue for this
1043 // feature on the rustc side.
1044 cargo.arg("-Zbinary-dep-depinfo");
1046 cargo.arg("-j").arg(self.jobs().to_string());
1047 // Remove make-related flags to ensure Cargo can correctly set things up
1048 cargo.env_remove("MAKEFLAGS");
1049 cargo.env_remove("MFLAGS");
1051 // FIXME: Temporary fix for https://github.com/rust-lang/cargo/issues/3005
1052 // Force cargo to output binaries with disambiguating hashes in the name
1053 let mut metadata = if compiler.stage == 0 {
1054 // Treat stage0 like a special channel, whether it's a normal prior-
1055 // release rustc or a local rebuild with the same version, so we
1056 // never mix these libraries by accident.
1057 "bootstrap".to_string()
1059 self.config.channel.to_string()
1061 // We want to make sure that none of the dependencies between
1062 // std/test/rustc unify with one another. This is done for weird linkage
1063 // reasons but the gist of the problem is that if librustc, libtest, and
1064 // libstd all depend on libc from crates.io (which they actually do) we
1065 // want to make sure they all get distinct versions. Things get really
1066 // weird if we try to unify all these dependencies right now, namely
1067 // around how many times the library is linked in dynamic libraries and
1068 // such. If rustc were a static executable or if we didn't ship dylibs
1069 // this wouldn't be a problem, but we do, so it is. This is in general
1070 // just here to make sure things build right. If you can remove this and
1071 // things still build right, please do!
1073 Mode::Std => metadata.push_str("std"),
1074 // When we're building rustc tools, they're built with a search path
1075 // that contains things built during the rustc build. For example,
1076 // bitflags is built during the rustc build, and is a dependency of
1077 // rustdoc as well. We're building rustdoc in a different target
1078 // directory, though, which means that Cargo will rebuild the
1079 // dependency. When we go on to build rustdoc, we'll look for
1080 // bitflags, and find two different copies: one built during the
1081 // rustc step and one that we just built. This isn't always a
1082 // problem, somehow -- not really clear why -- but we know that this
1084 Mode::ToolRustc => metadata.push_str("tool-rustc"),
1085 // Same for codegen backends.
1086 Mode::Codegen => metadata.push_str("codegen"),
1089 cargo.env("__CARGO_DEFAULT_LIB_METADATA", &metadata);
1091 if cmd == "clippy" {
1092 rustflags.arg("-Zforce-unstable-if-unmarked");
1095 rustflags.arg("-Zmacro-backtrace");
1097 let want_rustdoc = self.doc_tests != DocTests::No;
1099 // We synthetically interpret a stage0 compiler used to build tools as a
1100 // "raw" compiler in that it's the exact snapshot we download. Normally
1101 // the stage0 build means it uses libraries build by the stage0
1102 // compiler, but for tools we just use the precompiled libraries that
1104 let use_snapshot = mode == Mode::ToolBootstrap;
1105 assert!(!use_snapshot || stage == 0 || self.local_rebuild);
1107 let maybe_sysroot = self.sysroot(compiler);
1108 let sysroot = if use_snapshot { self.rustc_snapshot_sysroot() } else { &maybe_sysroot };
1109 let libdir = self.rustc_libdir(compiler);
1111 // Clear the output directory if the real rustc we're using has changed;
1112 // Cargo cannot detect this as it thinks rustc is bootstrap/debug/rustc.
1114 // Avoid doing this during dry run as that usually means the relevant
1115 // compiler is not yet linked/copied properly.
1117 // Only clear out the directory if we're compiling std; otherwise, we
1118 // should let Cargo take care of things for us (via depdep info)
1119 if !self.config.dry_run && mode == Mode::Std && cmd == "build" {
1120 self.clear_if_dirty(&out_dir, &self.rustc(compiler));
1123 // Customize the compiler we're running. Specify the compiler to cargo
1124 // as our shim and then pass it some various options used to configure
1125 // how the actual compiler itself is called.
1127 // These variables are primarily all read by
1128 // src/bootstrap/bin/{rustc.rs,rustdoc.rs}
1130 .env("RUSTBUILD_NATIVE_DIR", self.native_dir(target))
1131 .env("RUSTC_REAL", self.rustc(compiler))
1132 .env("RUSTC_STAGE", stage.to_string())
1133 .env("RUSTC_SYSROOT", &sysroot)
1134 .env("RUSTC_LIBDIR", &libdir)
1135 .env("RUSTDOC", self.out.join("bootstrap/debug/rustdoc"))
1138 if cmd == "doc" || cmd == "rustdoc" || (cmd == "test" && want_rustdoc) {
1139 self.rustdoc(compiler)
1141 PathBuf::from("/path/to/nowhere/rustdoc/not/required")
1144 .env("RUSTC_ERROR_METADATA_DST", self.extended_error_dir())
1145 .env("RUSTC_BREAK_ON_ICE", "1");
1146 // Clippy support is a hack and uses the default `cargo-clippy` in path.
1147 // Don't override RUSTC so that the `cargo-clippy` in path will be run.
1148 if cmd != "clippy" {
1149 cargo.env("RUSTC", self.out.join("bootstrap/debug/rustc"));
1152 // Dealing with rpath here is a little special, so let's go into some
1153 // detail. First off, `-rpath` is a linker option on Unix platforms
1154 // which adds to the runtime dynamic loader path when looking for
1155 // dynamic libraries. We use this by default on Unix platforms to ensure
1156 // that our nightlies behave the same on Windows, that is they work out
1157 // of the box. This can be disabled, of course, but basically that's why
1158 // we're gated on RUSTC_RPATH here.
1160 // Ok, so the astute might be wondering "why isn't `-C rpath` used
1161 // here?" and that is indeed a good question to ask. This codegen
1162 // option is the compiler's current interface to generating an rpath.
1163 // Unfortunately it doesn't quite suffice for us. The flag currently
1164 // takes no value as an argument, so the compiler calculates what it
1165 // should pass to the linker as `-rpath`. This unfortunately is based on
1166 // the **compile time** directory structure which when building with
1167 // Cargo will be very different than the runtime directory structure.
1169 // All that's a really long winded way of saying that if we use
1170 // `-Crpath` then the executables generated have the wrong rpath of
1171 // something like `$ORIGIN/deps` when in fact the way we distribute
1172 // rustc requires the rpath to be `$ORIGIN/../lib`.
1174 // So, all in all, to set up the correct rpath we pass the linker
1175 // argument manually via `-C link-args=-Wl,-rpath,...`. Plus isn't it
1176 // fun to pass a flag to a tool to pass a flag to pass a flag to a tool
1177 // to change a flag in a binary?
1178 if self.config.rust_rpath && util::use_host_linker(target) {
1179 let rpath = if target.contains("apple") {
1180 // Note that we need to take one extra step on macOS to also pass
1181 // `-Wl,-instal_name,@rpath/...` to get things to work right. To
1182 // do that we pass a weird flag to the compiler to get it to do
1183 // so. Note that this is definitely a hack, and we should likely
1184 // flesh out rpath support more fully in the future.
1185 rustflags.arg("-Zosx-rpath-install-name");
1186 Some("-Wl,-rpath,@loader_path/../lib")
1187 } else if !target.contains("windows") {
1188 rustflags.arg("-Clink-args=-Wl,-z,origin");
1189 Some("-Wl,-rpath,$ORIGIN/../lib")
1193 if let Some(rpath) = rpath {
1194 rustflags.arg(&format!("-Clink-args={}", rpath));
1198 if let Some(host_linker) = self.linker(compiler.host) {
1199 cargo.env("RUSTC_HOST_LINKER", host_linker);
1201 if self.is_fuse_ld_lld(compiler.host) {
1202 cargo.env("RUSTC_HOST_FUSE_LD_LLD", "1");
1203 cargo.env("RUSTDOC_FUSE_LD_LLD", "1");
1206 if let Some(target_linker) = self.linker(target) {
1207 let target = crate::envify(&target.triple);
1208 cargo.env(&format!("CARGO_TARGET_{}_LINKER", target), target_linker);
1210 if self.is_fuse_ld_lld(target) {
1211 rustflags.arg("-Clink-args=-fuse-ld=lld");
1213 self.lld_flags(target).for_each(|flag| {
1214 rustdocflags.arg(&flag);
1217 if !(["build", "check", "clippy", "fix", "rustc"].contains(&cmd)) && want_rustdoc {
1218 cargo.env("RUSTDOC_LIBDIR", self.rustc_libdir(compiler));
1221 let debuginfo_level = match mode {
1222 Mode::Rustc | Mode::Codegen => self.config.rust_debuginfo_level_rustc,
1223 Mode::Std => self.config.rust_debuginfo_level_std,
1224 Mode::ToolBootstrap | Mode::ToolStd | Mode::ToolRustc => {
1225 self.config.rust_debuginfo_level_tools
1228 cargo.env(profile_var("DEBUG"), debuginfo_level.to_string());
1230 profile_var("DEBUG_ASSERTIONS"),
1231 if mode == Mode::Std {
1232 self.config.rust_debug_assertions_std.to_string()
1234 self.config.rust_debug_assertions.to_string()
1238 profile_var("OVERFLOW_CHECKS"),
1239 if mode == Mode::Std {
1240 self.config.rust_overflow_checks_std.to_string()
1242 self.config.rust_overflow_checks.to_string()
1246 // `dsymutil` adds time to builds on Apple platforms for no clear benefit, and also makes
1247 // it more difficult for debuggers to find debug info. The compiler currently defaults to
1248 // running `dsymutil` to preserve its historical default, but when compiling the compiler
1249 // itself, we skip it by default since we know it's safe to do so in that case.
1250 // See https://github.com/rust-lang/rust/issues/79361 for more info on this flag.
1251 if target.contains("apple") {
1252 if self.config.rust_run_dsymutil {
1253 rustflags.arg("-Csplit-debuginfo=packed");
1255 rustflags.arg("-Csplit-debuginfo=unpacked");
1259 if self.config.cmd.bless() {
1260 // Bless `expect!` tests.
1261 cargo.env("UPDATE_EXPECT", "1");
1264 if !mode.is_tool() {
1265 cargo.env("RUSTC_FORCE_UNSTABLE", "1");
1268 if let Some(x) = self.crt_static(target) {
1270 rustflags.arg("-Ctarget-feature=+crt-static");
1272 rustflags.arg("-Ctarget-feature=-crt-static");
1276 if let Some(x) = self.crt_static(compiler.host) {
1277 cargo.env("RUSTC_HOST_CRT_STATIC", x.to_string());
1280 if let Some(map_to) = self.build.debuginfo_map_to(GitRepo::Rustc) {
1281 let map = format!("{}={}", self.build.src.display(), map_to);
1282 cargo.env("RUSTC_DEBUGINFO_MAP", map);
1284 // `rustc` needs to know the virtual `/rustc/$hash` we're mapping to,
1285 // in order to opportunistically reverse it later.
1286 cargo.env("CFG_VIRTUAL_RUST_SOURCE_BASE_DIR", map_to);
1289 // Enable usage of unstable features
1290 cargo.env("RUSTC_BOOTSTRAP", "1");
1291 self.add_rust_test_threads(&mut cargo);
1293 // Almost all of the crates that we compile as part of the bootstrap may
1294 // have a build script, including the standard library. To compile a
1295 // build script, however, it itself needs a standard library! This
1296 // introduces a bit of a pickle when we're compiling the standard
1299 // To work around this we actually end up using the snapshot compiler
1300 // (stage0) for compiling build scripts of the standard library itself.
1301 // The stage0 compiler is guaranteed to have a libstd available for use.
1303 // For other crates, however, we know that we've already got a standard
1304 // library up and running, so we can use the normal compiler to compile
1305 // build scripts in that situation.
1306 if mode == Mode::Std {
1308 .env("RUSTC_SNAPSHOT", &self.initial_rustc)
1309 .env("RUSTC_SNAPSHOT_LIBDIR", self.rustc_snapshot_libdir());
1312 .env("RUSTC_SNAPSHOT", self.rustc(compiler))
1313 .env("RUSTC_SNAPSHOT_LIBDIR", self.rustc_libdir(compiler));
1316 // Tools that use compiler libraries may inherit the `-lLLVM` link
1317 // requirement, but the `-L` library path is not propagated across
1318 // separate Cargo projects. We can add LLVM's library path to the
1319 // platform-specific environment variable as a workaround.
1320 if mode == Mode::ToolRustc || mode == Mode::Codegen {
1321 if let Some(llvm_config) = self.llvm_config(target) {
1322 let llvm_libdir = output(Command::new(&llvm_config).arg("--libdir"));
1323 add_link_lib_path(vec![llvm_libdir.trim().into()], &mut cargo);
1327 // Compile everything except libraries and proc macros with the more
1328 // efficient initial-exec TLS model. This doesn't work with `dlopen`,
1329 // so we can't use it by default in general, but we can use it for tools
1330 // and our own internal libraries.
1331 if !mode.must_support_dlopen() && !target.triple.starts_with("powerpc-") {
1332 rustflags.arg("-Ztls-model=initial-exec");
1335 if self.config.incremental {
1336 cargo.env("CARGO_INCREMENTAL", "1");
1338 // Don't rely on any default setting for incr. comp. in Cargo
1339 cargo.env("CARGO_INCREMENTAL", "0");
1342 if let Some(ref on_fail) = self.config.on_fail {
1343 cargo.env("RUSTC_ON_FAIL", on_fail);
1346 if self.config.print_step_timings {
1347 cargo.env("RUSTC_PRINT_STEP_TIMINGS", "1");
1350 if self.config.print_step_rusage {
1351 cargo.env("RUSTC_PRINT_STEP_RUSAGE", "1");
1354 if self.config.backtrace_on_ice {
1355 cargo.env("RUSTC_BACKTRACE_ON_ICE", "1");
1358 cargo.env("RUSTC_VERBOSE", self.verbosity.to_string());
1360 if source_type == SourceType::InTree {
1361 let mut lint_flags = Vec::new();
1362 // When extending this list, add the new lints to the RUSTFLAGS of the
1363 // build_bootstrap function of src/bootstrap/bootstrap.py as well as
1364 // some code doesn't go through this `rustc` wrapper.
1365 lint_flags.push("-Wrust_2018_idioms");
1366 lint_flags.push("-Wunused_lifetimes");
1367 lint_flags.push("-Wsemicolon_in_expressions_from_macros");
1369 if self.config.deny_warnings {
1370 lint_flags.push("-Dwarnings");
1371 rustdocflags.arg("-Dwarnings");
1374 // This does not use RUSTFLAGS due to caching issues with Cargo.
1375 // Clippy is treated as an "in tree" tool, but shares the same
1376 // cache as other "submodule" tools. With these options set in
1377 // RUSTFLAGS, that causes *every* shared dependency to be rebuilt.
1378 // By injecting this into the rustc wrapper, this circumvents
1379 // Cargo's fingerprint detection. This is fine because lint flags
1380 // are always ignored in dependencies. Eventually this should be
1381 // fixed via better support from Cargo.
1382 cargo.env("RUSTC_LINT_FLAGS", lint_flags.join(" "));
1384 rustdocflags.arg("-Wrustdoc::invalid_codeblock_attributes");
1387 if mode == Mode::Rustc {
1388 rustflags.arg("-Zunstable-options");
1389 rustflags.arg("-Wrustc::internal");
1392 // Throughout the build Cargo can execute a number of build scripts
1393 // compiling C/C++ code and we need to pass compilers, archivers, flags, etc
1394 // obtained previously to those build scripts.
1395 // Build scripts use either the `cc` crate or `configure/make` so we pass
1396 // the options through environment variables that are fetched and understood by both.
1398 // FIXME: the guard against msvc shouldn't need to be here
1399 if target.contains("msvc") {
1400 if let Some(ref cl) = self.config.llvm_clang_cl {
1401 cargo.env("CC", cl).env("CXX", cl);
1404 let ccache = self.config.ccache.as_ref();
1405 let ccacheify = |s: &Path| {
1406 let ccache = match ccache {
1408 None => return s.display().to_string(),
1410 // FIXME: the cc-rs crate only recognizes the literal strings
1411 // `ccache` and `sccache` when doing caching compilations, so we
1412 // mirror that here. It should probably be fixed upstream to
1413 // accept a new env var or otherwise work with custom ccache
1416 "ccache" | "sccache" => format!("{} {}", ccache, s.display()),
1417 _ => s.display().to_string(),
1420 let cc = ccacheify(&self.cc(target));
1421 cargo.env(format!("CC_{}", target.triple), &cc);
1423 let cflags = self.cflags(target, GitRepo::Rustc).join(" ");
1424 cargo.env(format!("CFLAGS_{}", target.triple), &cflags);
1426 if let Some(ar) = self.ar(target) {
1427 let ranlib = format!("{} s", ar.display());
1429 .env(format!("AR_{}", target.triple), ar)
1430 .env(format!("RANLIB_{}", target.triple), ranlib);
1433 if let Ok(cxx) = self.cxx(target) {
1434 let cxx = ccacheify(&cxx);
1436 .env(format!("CXX_{}", target.triple), &cxx)
1437 .env(format!("CXXFLAGS_{}", target.triple), cflags);
1441 if mode == Mode::Std && self.config.extended && compiler.is_final_stage(self) {
1442 rustflags.arg("-Zsave-analysis");
1444 "RUST_SAVE_ANALYSIS_CONFIG",
1445 "{\"output_file\": null,\"full_docs\": false,\
1446 \"pub_only\": true,\"reachable_only\": false,\
1447 \"distro_crate\": true,\"signatures\": false,\"borrow_data\": false}",
1451 // If Control Flow Guard is enabled, pass the `control-flow-guard` flag to rustc
1452 // when compiling the standard library, since this might be linked into the final outputs
1453 // produced by rustc. Since this mitigation is only available on Windows, only enable it
1454 // for the standard library in case the compiler is run on a non-Windows platform.
1455 // This is not needed for stage 0 artifacts because these will only be used for building
1456 // the stage 1 compiler.
1458 && mode == Mode::Std
1459 && self.config.control_flow_guard
1460 && compiler.stage >= 1
1462 rustflags.arg("-Ccontrol-flow-guard");
1465 // For `cargo doc` invocations, make rustdoc print the Rust version into the docs
1466 // This replaces spaces with newlines because RUSTDOCFLAGS does not
1467 // support arguments with regular spaces. Hopefully someday Cargo will
1468 // have space support.
1469 let rust_version = self.rust_version().replace(' ', "\n");
1470 rustdocflags.arg("--crate-version").arg(&rust_version);
1472 // Environment variables *required* throughout the build
1474 // FIXME: should update code to not require this env var
1475 cargo.env("CFG_COMPILER_HOST_TRIPLE", target.triple);
1477 // Set this for all builds to make sure doc builds also get it.
1478 cargo.env("CFG_RELEASE_CHANNEL", &self.config.channel);
1480 // This one's a bit tricky. As of the time of this writing the compiler
1481 // links to the `winapi` crate on crates.io. This crate provides raw
1482 // bindings to Windows system functions, sort of like libc does for
1483 // Unix. This crate also, however, provides "import libraries" for the
1484 // MinGW targets. There's an import library per dll in the windows
1485 // distribution which is what's linked to. These custom import libraries
1486 // are used because the winapi crate can reference Windows functions not
1487 // present in the MinGW import libraries.
1489 // For example MinGW may ship libdbghelp.a, but it may not have
1490 // references to all the functions in the dbghelp dll. Instead the
1491 // custom import library for dbghelp in the winapi crates has all this
1494 // Unfortunately for us though the import libraries are linked by
1495 // default via `-ldylib=winapi_foo`. That is, they're linked with the
1496 // `dylib` type with a `winapi_` prefix (so the winapi ones don't
1497 // conflict with the system MinGW ones). This consequently means that
1498 // the binaries we ship of things like rustc_codegen_llvm (aka the rustc_codegen_llvm
1499 // DLL) when linked against *again*, for example with procedural macros
1500 // or plugins, will trigger the propagation logic of `-ldylib`, passing
1501 // `-lwinapi_foo` to the linker again. This isn't actually available in
1502 // our distribution, however, so the link fails.
1504 // To solve this problem we tell winapi to not use its bundled import
1505 // libraries. This means that it will link to the system MinGW import
1506 // libraries by default, and the `-ldylib=foo` directives will still get
1507 // passed to the final linker, but they'll look like `-lfoo` which can
1508 // be resolved because MinGW has the import library. The downside is we
1509 // don't get newer functions from Windows, but we don't use any of them
1511 if !mode.is_tool() {
1512 cargo.env("WINAPI_NO_BUNDLED_LIBRARIES", "1");
1515 for _ in 0..self.verbosity {
1519 match (mode, self.config.rust_codegen_units_std, self.config.rust_codegen_units) {
1520 (Mode::Std, Some(n), _) | (_, _, Some(n)) => {
1521 cargo.env(profile_var("CODEGEN_UNITS"), n.to_string());
1524 // Don't set anything
1528 if self.config.rust_optimize {
1529 // FIXME: cargo bench/install do not accept `--release`
1530 if cmd != "bench" && cmd != "install" {
1531 cargo.arg("--release");
1535 if self.config.locked_deps {
1536 cargo.arg("--locked");
1538 if self.config.vendor || self.is_sudo {
1539 cargo.arg("--frozen");
1542 // Try to use a sysroot-relative bindir, in case it was configured absolutely.
1543 cargo.env("RUSTC_INSTALL_BINDIR", self.config.bindir_relative());
1545 self.ci_env.force_coloring_in_ci(&mut cargo);
1547 // When we build Rust dylibs they're all intended for intermediate
1548 // usage, so make sure we pass the -Cprefer-dynamic flag instead of
1549 // linking all deps statically into the dylib.
1550 if matches!(mode, Mode::Std | Mode::Rustc) {
1551 rustflags.arg("-Cprefer-dynamic");
1554 // When building incrementally we default to a lower ThinLTO import limit
1555 // (unless explicitly specified otherwise). This will produce a somewhat
1556 // slower code but give way better compile times.
1558 let limit = match self.config.rust_thin_lto_import_instr_limit {
1559 Some(limit) => Some(limit),
1560 None if self.config.incremental => Some(10),
1564 if let Some(limit) = limit {
1565 rustflags.arg(&format!("-Cllvm-args=-import-instr-limit={}", limit));
1569 Cargo { command: cargo, rustflags, rustdocflags }
1572 /// Ensure that a given step is built, returning its output. This will
1573 /// cache the step, so it is safe (and good!) to call this as often as
1574 /// needed to ensure that all dependencies are built.
1575 pub fn ensure<S: Step>(&'a self, step: S) -> S::Output {
1577 let mut stack = self.stack.borrow_mut();
1578 for stack_step in stack.iter() {
1580 if stack_step.downcast_ref::<S>().map_or(true, |stack_step| *stack_step != step) {
1583 let mut out = String::new();
1584 out += &format!("\n\nCycle in build detected when adding {:?}\n", step);
1585 for el in stack.iter().rev() {
1586 out += &format!("\t{:?}\n", el);
1590 if let Some(out) = self.cache.get(&step) {
1591 self.verbose_than(1, &format!("{}c {:?}", " ".repeat(stack.len()), step));
1595 self.verbose_than(1, &format!("{}> {:?}", " ".repeat(stack.len()), step));
1596 stack.push(Box::new(step.clone()));
1600 let start = Instant::now();
1601 let zero = Duration::new(0, 0);
1602 let parent = self.time_spent_on_dependencies.replace(zero);
1603 let out = step.clone().run(self);
1604 let dur = start.elapsed();
1605 let deps = self.time_spent_on_dependencies.replace(parent + dur);
1609 if self.config.print_step_timings && !self.config.dry_run {
1610 println!("[TIMING] {:?} -- {}.{:03}", step, dur.as_secs(), dur.subsec_millis());
1614 let mut stack = self.stack.borrow_mut();
1615 let cur_step = stack.pop().expect("step stack empty");
1616 assert_eq!(cur_step.downcast_ref(), Some(&step));
1618 self.verbose_than(1, &format!("{}< {:?}", " ".repeat(self.stack.borrow().len()), step));
1619 self.cache.put(step, out.clone());
1623 /// Ensure that a given step is built *only if it's supposed to be built by default*, returning
1624 /// its output. This will cache the step, so it's safe (and good!) to call this as often as
1625 /// needed to ensure that all dependencies are build.
1626 pub(crate) fn ensure_if_default<T, S: Step<Output = Option<T>>>(
1630 let desc = StepDescription::from::<S>();
1631 let should_run = (desc.should_run)(ShouldRun::new(self));
1633 // Avoid running steps contained in --exclude
1634 for pathset in &should_run.paths {
1635 if desc.is_excluded(self, pathset) {
1640 // Only execute if it's supposed to run as default
1641 if desc.default && should_run.is_really_default() { self.ensure(step) } else { None }
1644 /// Checks if any of the "should_run" paths is in the `Builder` paths.
1645 pub(crate) fn was_invoked_explicitly<S: Step>(&'a self) -> bool {
1646 let desc = StepDescription::from::<S>();
1647 let should_run = (desc.should_run)(ShouldRun::new(self));
1649 for path in &self.paths {
1650 if should_run.paths.iter().any(|s| s.has(path))
1651 && !desc.is_excluded(self, &PathSet::Suite(path.clone()))
1664 #[derive(Debug, Clone)]
1665 struct Rustflags(String, TargetSelection);
1668 fn new(target: TargetSelection) -> Rustflags {
1669 let mut ret = Rustflags(String::new(), target);
1670 ret.propagate_cargo_env("RUSTFLAGS");
1674 /// By default, cargo will pick up on various variables in the environment. However, bootstrap
1675 /// reuses those variables to pass additional flags to rustdoc, so by default they get overriden.
1676 /// Explicitly add back any previous value in the environment.
1678 /// `prefix` is usually `RUSTFLAGS` or `RUSTDOCFLAGS`.
1679 fn propagate_cargo_env(&mut self, prefix: &str) {
1680 // Inherit `RUSTFLAGS` by default ...
1683 // ... and also handle target-specific env RUSTFLAGS if they're configured.
1684 let target_specific = format!("CARGO_TARGET_{}_{}", crate::envify(&self.1.triple), prefix);
1685 self.env(&target_specific);
1688 fn env(&mut self, env: &str) {
1689 if let Ok(s) = env::var(env) {
1690 for part in s.split(' ') {
1696 fn arg(&mut self, arg: &str) -> &mut Self {
1697 assert_eq!(arg.split(' ').count(), 1);
1698 if !self.0.is_empty() {
1701 self.0.push_str(arg);
1709 rustflags: Rustflags,
1710 rustdocflags: Rustflags,
1714 pub fn rustdocflag(&mut self, arg: &str) -> &mut Cargo {
1715 self.rustdocflags.arg(arg);
1718 pub fn rustflag(&mut self, arg: &str) -> &mut Cargo {
1719 self.rustflags.arg(arg);
1723 pub fn arg(&mut self, arg: impl AsRef<OsStr>) -> &mut Cargo {
1724 self.command.arg(arg.as_ref());
1728 pub fn args<I, S>(&mut self, args: I) -> &mut Cargo
1730 I: IntoIterator<Item = S>,
1734 self.arg(arg.as_ref());
1739 pub fn env(&mut self, key: impl AsRef<OsStr>, value: impl AsRef<OsStr>) -> &mut Cargo {
1740 // These are managed through rustflag/rustdocflag interfaces.
1741 assert_ne!(key.as_ref(), "RUSTFLAGS");
1742 assert_ne!(key.as_ref(), "RUSTDOCFLAGS");
1743 self.command.env(key.as_ref(), value.as_ref());
1747 pub fn add_rustc_lib_path(&mut self, builder: &Builder<'_>, compiler: Compiler) {
1748 builder.add_rustc_lib_path(compiler, &mut self.command);
1751 pub fn current_dir(&mut self, dir: &Path) -> &mut Cargo {
1752 self.command.current_dir(dir);
1757 impl From<Cargo> for Command {
1758 fn from(mut cargo: Cargo) -> Command {
1759 let rustflags = &cargo.rustflags.0;
1760 if !rustflags.is_empty() {
1761 cargo.command.env("RUSTFLAGS", rustflags);
1764 let rustdocflags = &cargo.rustdocflags.0;
1765 if !rustdocflags.is_empty() {
1766 cargo.command.env("RUSTDOCFLAGS", rustdocflags);