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::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 /// If true, then this rule should be skipped if --target was specified, but --host was not
61 const ONLY_HOSTS: bool = false;
63 /// Primary function to execute this rule. Can call `builder.ensure()`
64 /// with other steps to run those.
65 fn run(self, builder: &Builder<'_>) -> Self::Output;
67 /// When bootstrap is passed a set of paths, this controls whether this rule
68 /// will execute. However, it does not get called in a "default" context
69 /// when we are not passed any paths; in that case, `make_run` is called
71 fn should_run(run: ShouldRun<'_>) -> ShouldRun<'_>;
73 /// Builds up a "root" rule, either as a default rule or from a path passed
76 /// When path is `None`, we are executing in a context where no paths were
77 /// passed. When `./x.py build` is run, for example, this rule could get
78 /// called if it is in the correct list below with a path of `None`.
79 fn make_run(_run: RunConfig<'_>) {
80 // It is reasonable to not have an implementation of make_run for rules
81 // who do not want to get called from the root context. This means that
82 // they are likely dependencies (e.g., sysroot creation) or similar, and
83 // as such calling them from ./x.py isn't logical.
88 pub struct RunConfig<'a> {
89 pub builder: &'a Builder<'a>,
90 pub host: TargetSelection,
91 pub target: TargetSelection,
95 struct StepDescription {
98 should_run: fn(ShouldRun<'_>) -> ShouldRun<'_>,
99 make_run: fn(RunConfig<'_>),
103 /// Collection of paths used to match a task rule.
104 #[derive(Debug, Clone, PartialOrd, Ord, PartialEq, Eq)]
106 /// A collection of individual paths.
108 /// These are generally matched as a path suffix. For example, a
109 /// command-line value of `libstd` will match if `src/libstd` is in the
111 Set(BTreeSet<PathBuf>),
112 /// A "suite" of paths.
114 /// These can match as a path suffix (like `Set`), or as a prefix. For
115 /// example, a command-line value of `src/test/ui/abi/variadic-ffi.rs`
116 /// will match `src/test/ui`. A command-line value of `ui` would also
117 /// match `src/test/ui`.
122 fn empty() -> PathSet {
123 PathSet::Set(BTreeSet::new())
126 fn one<P: Into<PathBuf>>(path: P) -> PathSet {
127 let mut set = BTreeSet::new();
128 set.insert(path.into());
132 fn has(&self, needle: &Path) -> bool {
134 PathSet::Set(set) => set.iter().any(|p| p.ends_with(needle)),
135 PathSet::Suite(suite) => suite.ends_with(needle),
139 fn path(&self, builder: &Builder<'_>) -> PathBuf {
141 PathSet::Set(set) => set.iter().next().unwrap_or(&builder.build.src).to_path_buf(),
142 PathSet::Suite(path) => PathBuf::from(path),
147 impl StepDescription {
148 fn from<S: Step>() -> StepDescription {
151 only_hosts: S::ONLY_HOSTS,
152 should_run: S::should_run,
153 make_run: S::make_run,
154 name: std::any::type_name::<S>(),
158 fn maybe_run(&self, builder: &Builder<'_>, pathset: &PathSet) {
159 if builder.config.exclude.iter().any(|e| pathset.has(e)) {
160 eprintln!("Skipping {:?} because it is excluded", pathset);
162 } else if !builder.config.exclude.is_empty() {
164 "{:?} not skipped for {:?} -- not in {:?}",
165 pathset, self.name, builder.config.exclude
168 let hosts = &builder.hosts;
170 // Determine the targets participating in this rule.
171 let targets = if self.only_hosts {
172 if builder.config.skip_only_host_steps {
173 return; // don't run anything
182 for target in targets {
183 let run = RunConfig {
185 path: pathset.path(builder),
189 (self.make_run)(run);
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() {
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);
217 // strip CurDir prefix if present
218 let path = match path.strip_prefix(".") {
223 let mut attempted_run = false;
224 for (desc, should_run) in v.iter().zip(&should_runs) {
225 if let Some(suite) = should_run.is_suite_path(path) {
226 attempted_run = true;
227 desc.maybe_run(builder, suite);
228 } else if let Some(pathset) = should_run.pathset_for_path(path) {
229 attempted_run = true;
230 desc.maybe_run(builder, pathset);
235 panic!("error: no rules matched {}", path.display());
243 pub struct ShouldRun<'a> {
244 pub builder: &'a Builder<'a>,
245 // use a BTreeSet to maintain sort order
246 paths: BTreeSet<PathSet>,
248 // If this is a default rule, this is an additional constraint placed on
249 // its run. Generally something like compiler docs being enabled.
250 is_really_default: bool,
253 impl<'a> ShouldRun<'a> {
254 fn new(builder: &'a Builder<'_>) -> ShouldRun<'a> {
257 paths: BTreeSet::new(),
258 is_really_default: true, // by default no additional conditions
262 pub fn default_condition(mut self, cond: bool) -> Self {
263 self.is_really_default = cond;
267 /// Indicates it should run if the command-line selects the given crate or
268 /// any of its (local) dependencies.
270 /// Compared to `krate`, this treats the dependencies as aliases for the
271 /// same job. Generally it is preferred to use `krate`, and treat each
272 /// individual path separately. For example `./x.py test src/liballoc`
273 /// (which uses `krate`) will test just `liballoc`. However, `./x.py check
274 /// src/liballoc` (which uses `all_krates`) will check all of `libtest`.
275 /// `all_krates` should probably be removed at some point.
276 pub fn all_krates(mut self, name: &str) -> Self {
277 let mut set = BTreeSet::new();
278 for krate in self.builder.in_tree_crates(name) {
279 let path = krate.local_path(self.builder);
282 self.paths.insert(PathSet::Set(set));
286 /// Indicates it should run if the command-line selects the given crate or
287 /// any of its (local) dependencies.
289 /// `make_run` will be called separately for each matching command-line path.
290 pub fn krate(mut self, name: &str) -> Self {
291 for krate in self.builder.in_tree_crates(name) {
292 let path = krate.local_path(self.builder);
293 self.paths.insert(PathSet::one(path));
298 // single, non-aliased path
299 pub fn path(self, path: &str) -> Self {
303 // multiple aliases for the same job
304 pub fn paths(mut self, paths: &[&str]) -> Self {
305 self.paths.insert(PathSet::Set(paths.iter().map(PathBuf::from).collect()));
309 pub fn is_suite_path(&self, path: &Path) -> Option<&PathSet> {
310 self.paths.iter().find(|pathset| match pathset {
311 PathSet::Suite(p) => path.starts_with(p),
312 PathSet::Set(_) => false,
316 pub fn suite_path(mut self, suite: &str) -> Self {
317 self.paths.insert(PathSet::Suite(PathBuf::from(suite)));
321 // allows being more explicit about why should_run in Step returns the value passed to it
322 pub fn never(mut self) -> ShouldRun<'a> {
323 self.paths.insert(PathSet::empty());
327 fn pathset_for_path(&self, path: &Path) -> Option<&PathSet> {
328 self.paths.iter().find(|pathset| pathset.has(path))
332 #[derive(Copy, Clone, PartialEq, Eq, Debug)]
347 impl<'a> Builder<'a> {
348 fn get_step_descriptions(kind: Kind) -> Vec<StepDescription> {
349 macro_rules! describe {
350 ($($rule:ty),+ $(,)?) => {{
351 vec![$(StepDescription::from::<$rule>()),+]
355 Kind::Build => describe!(
358 compile::StartupObjects,
362 tool::UnstableBookGen,
367 tool::RemoteTestServer,
368 tool::RemoteTestClient,
384 Kind::Check | Kind::Clippy | Kind::Fix | Kind::Format => {
385 describe!(check::Std, check::Rustc, check::Rustdoc, check::Clippy)
387 Kind::Test => describe!(
388 crate::toolstate::ToolStateCheck,
389 test::ExpandYamlAnchors,
393 test::RunPassValgrind,
412 test::RunMakeFullDeps,
426 test::CompiletestTest,
428 test::RustdocJSNotStd,
431 // Run bootstrap close to the end as it's unlikely to fail
433 // Run run-make last, since these won't pass without make on Windows
436 Kind::Bench => describe!(test::Crate, test::CrateLibrustc),
437 Kind::Doc => describe!(
439 doc::UnstableBookGen,
455 Kind::Dist => describe!(
460 dist::DebuggerScripts,
465 dist::PlainSourceTarball,
476 Kind::Install => describe!(
481 install::RustAnalyzer,
489 Kind::Run => describe!(run::ExpandYamlAnchors,),
493 pub fn get_help(build: &Build, subcommand: &str) -> Option<String> {
494 let kind = match subcommand {
495 "build" => Kind::Build,
497 "test" => Kind::Test,
498 "bench" => Kind::Bench,
499 "dist" => Kind::Dist,
500 "install" => Kind::Install,
504 let builder = Self::new_internal(build, kind, vec![]);
505 let builder = &builder;
506 let mut should_run = ShouldRun::new(builder);
507 for desc in Builder::get_step_descriptions(builder.kind) {
508 should_run = (desc.should_run)(should_run);
510 let mut help = String::from("Available paths:\n");
511 let mut add_path = |path: &Path| {
512 help.push_str(&format!(" ./x.py {} {}\n", subcommand, path.display()));
514 for pathset in should_run.paths {
516 PathSet::Set(set) => {
521 PathSet::Suite(path) => {
522 add_path(&path.join("..."));
529 fn new_internal(build: &Build, kind: Kind, paths: Vec<PathBuf>) -> Builder<'_> {
530 let top_stage = if let Some(explicit_stage) = build.config.stage {
533 // See https://github.com/rust-lang/compiler-team/issues/326
536 Kind::Build | Kind::Test => 1,
537 Kind::Bench | Kind::Dist | Kind::Install => 2,
538 // These are all bootstrap tools, which don't depend on the compiler.
539 // The stage we pass shouldn't matter, but use 0 just in case.
540 Kind::Check | Kind::Clippy | Kind::Fix | Kind::Run | Kind::Format => 0,
549 stack: RefCell::new(Vec::new()),
550 time_spent_on_dependencies: Cell::new(Duration::new(0, 0)),
555 pub fn new(build: &Build) -> Builder<'_> {
556 let (kind, paths) = match build.config.cmd {
557 Subcommand::Build { ref paths } => (Kind::Build, &paths[..]),
558 Subcommand::Check { ref paths } => (Kind::Check, &paths[..]),
559 Subcommand::Clippy { ref paths } => (Kind::Clippy, &paths[..]),
560 Subcommand::Fix { ref paths } => (Kind::Fix, &paths[..]),
561 Subcommand::Doc { ref paths, .. } => (Kind::Doc, &paths[..]),
562 Subcommand::Test { ref paths, .. } => (Kind::Test, &paths[..]),
563 Subcommand::Bench { ref paths, .. } => (Kind::Bench, &paths[..]),
564 Subcommand::Dist { ref paths } => (Kind::Dist, &paths[..]),
565 Subcommand::Install { ref paths } => (Kind::Install, &paths[..]),
566 Subcommand::Run { ref paths } => (Kind::Run, &paths[..]),
567 Subcommand::Format { .. } | Subcommand::Clean { .. } => panic!(),
570 let this = Self::new_internal(build, kind, paths.to_owned());
572 // CI should always run stage 2 builds, unless it specifically states otherwise
574 if build.config.stage.is_none() && build.ci_env != crate::CiEnv::None {
576 Kind::Test | Kind::Doc | Kind::Build | Kind::Bench | Kind::Dist | Kind::Install => {
577 assert_eq!(this.top_stage, 2)
579 Kind::Check | Kind::Clippy | Kind::Fix | Kind::Run | Kind::Format => {}
586 pub fn execute_cli(&self) {
587 self.run_step_descriptions(&Builder::get_step_descriptions(self.kind), &self.paths);
590 pub fn default_doc(&self, paths: Option<&[PathBuf]>) {
591 let paths = paths.unwrap_or(&[]);
592 self.run_step_descriptions(&Builder::get_step_descriptions(Kind::Doc), paths);
595 fn run_step_descriptions(&self, v: &[StepDescription], paths: &[PathBuf]) {
596 StepDescription::run(v, self, paths);
599 /// Obtain a compiler at a given stage and for a given host. Explicitly does
600 /// not take `Compiler` since all `Compiler` instances are meant to be
601 /// obtained through this function, since it ensures that they are valid
602 /// (i.e., built and assembled).
603 pub fn compiler(&self, stage: u32, host: TargetSelection) -> Compiler {
604 self.ensure(compile::Assemble { target_compiler: Compiler { stage, host } })
607 /// Similar to `compiler`, except handles the full-bootstrap option to
608 /// silently use the stage1 compiler instead of a stage2 compiler if one is
611 /// Note that this does *not* have the side effect of creating
612 /// `compiler(stage, host)`, unlike `compiler` above which does have such
613 /// a side effect. The returned compiler here can only be used to compile
614 /// new artifacts, it can't be used to rely on the presence of a particular
617 /// See `force_use_stage1` for documentation on what each argument is.
621 host: TargetSelection,
622 target: TargetSelection,
624 if self.build.force_use_stage1(Compiler { stage, host }, target) {
625 self.compiler(1, self.config.build)
627 self.compiler(stage, host)
631 pub fn sysroot(&self, compiler: Compiler) -> Interned<PathBuf> {
632 self.ensure(compile::Sysroot { compiler })
635 /// Returns the libdir where the standard library and other artifacts are
636 /// found for a compiler's sysroot.
637 pub fn sysroot_libdir(&self, compiler: Compiler, target: TargetSelection) -> Interned<PathBuf> {
638 #[derive(Debug, Copy, Clone, Hash, PartialEq, Eq)]
641 target: TargetSelection,
643 impl Step for Libdir {
644 type Output = Interned<PathBuf>;
646 fn should_run(run: ShouldRun<'_>) -> ShouldRun<'_> {
650 fn run(self, builder: &Builder<'_>) -> Interned<PathBuf> {
651 let lib = builder.sysroot_libdir_relative(self.compiler);
652 let sysroot = builder
653 .sysroot(self.compiler)
656 .join(self.target.triple)
658 let _ = fs::remove_dir_all(&sysroot);
659 t!(fs::create_dir_all(&sysroot));
660 INTERNER.intern_path(sysroot)
663 self.ensure(Libdir { compiler, target })
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 Cargo) {
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)], &mut cmd.command);
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 pub fn rustdoc(&self, compiler: Compiler) -> PathBuf {
735 self.ensure(tool::Rustdoc { compiler })
738 pub fn rustdoc_cmd(&self, compiler: Compiler) -> Command {
739 let mut cmd = Command::new(&self.out.join("bootstrap/debug/rustdoc"));
740 cmd.env("RUSTC_STAGE", compiler.stage.to_string())
741 .env("RUSTC_SYSROOT", self.sysroot(compiler))
742 // Note that this is *not* the sysroot_libdir because rustdoc must be linked
743 // equivalently to rustc.
744 .env("RUSTDOC_LIBDIR", self.rustc_libdir(compiler))
745 .env("CFG_RELEASE_CHANNEL", &self.config.channel)
746 .env("RUSTDOC_REAL", self.rustdoc(compiler))
747 .env("RUSTDOC_CRATE_VERSION", self.rust_version())
748 .env("RUSTC_BOOTSTRAP", "1")
749 .arg("-Winvalid_codeblock_attributes");
750 if self.config.deny_warnings {
751 cmd.arg("-Dwarnings");
754 // Remove make-related flags that can cause jobserver problems.
755 cmd.env_remove("MAKEFLAGS");
756 cmd.env_remove("MFLAGS");
758 if let Some(linker) = self.linker(compiler.host, true) {
759 cmd.env("RUSTC_TARGET_LINKER", linker);
764 /// Return the path to `llvm-config` for the target, if it exists.
766 /// Note that this returns `None` if LLVM is disabled, or if we're in a
767 /// check build or dry-run, where there's no need to build all of LLVM.
768 fn llvm_config(&self, target: TargetSelection) -> Option<PathBuf> {
769 if self.config.llvm_enabled() && self.kind != Kind::Check && !self.config.dry_run {
770 let llvm_config = self.ensure(native::Llvm { target });
771 if llvm_config.is_file() {
772 return Some(llvm_config);
778 /// Prepares an invocation of `cargo` to be run.
780 /// This will create a `Command` that represents a pending execution of
781 /// Cargo. This cargo will be configured to use `compiler` as the actual
782 /// rustc compiler, its output will be scoped by `mode`'s output directory,
783 /// it will pass the `--target` flag for the specified `target`, and will be
784 /// executing the Cargo command `cmd`.
789 source_type: SourceType,
790 target: TargetSelection,
793 let mut cargo = Command::new(&self.initial_cargo);
794 let out_dir = self.stage_out(compiler, mode);
796 if cmd == "doc" || cmd == "rustdoc" {
797 let my_out = match mode {
798 // This is the intended out directory for compiler documentation.
799 Mode::Rustc | Mode::ToolRustc | Mode::Codegen => self.compiler_doc_out(target),
800 Mode::Std => out_dir.join(target.triple).join("doc"),
801 _ => panic!("doc mode {:?} not expected", mode),
803 let rustdoc = self.rustdoc(compiler);
804 self.clear_if_dirty(&my_out, &rustdoc);
807 cargo.env("CARGO_TARGET_DIR", &out_dir).arg(cmd);
809 let profile_var = |name: &str| {
810 let profile = if self.config.rust_optimize { "RELEASE" } else { "DEV" };
811 format!("CARGO_PROFILE_{}_{}", profile, name)
814 // See comment in librustc_llvm/build.rs for why this is necessary, largely llvm-config
815 // needs to not accidentally link to libLLVM in stage0/lib.
816 cargo.env("REAL_LIBRARY_PATH_VAR", &util::dylib_path_var());
817 if let Some(e) = env::var_os(util::dylib_path_var()) {
818 cargo.env("REAL_LIBRARY_PATH", e);
821 if cmd != "install" {
822 cargo.arg("--target").arg(target.rustc_target_arg());
824 assert_eq!(target, compiler.host);
827 // Set a flag for `check`/`clippy`/`fix`, so that certain build
828 // scripts can do less work (i.e. not building/requiring LLVM).
829 if cmd == "check" || cmd == "clippy" || cmd == "fix" {
830 // If we've not yet built LLVM, or it's stale, then bust
831 // the librustc_llvm cache. That will always work, even though it
832 // may mean that on the next non-check build we'll need to rebuild
833 // librustc_llvm. But if LLVM is stale, that'll be a tiny amount
834 // of work comparitively, and we'd likely need to rebuild it anyway,
836 if crate::native::prebuilt_llvm_config(self, target).is_err() {
837 cargo.env("RUST_CHECK", "1");
841 let stage = if compiler.stage == 0 && self.local_rebuild {
842 // Assume the local-rebuild rustc already has stage1 features.
848 let mut rustflags = Rustflags::new(target);
850 if let Ok(s) = env::var("CARGOFLAGS_NOT_BOOTSTRAP") {
851 cargo.args(s.split_whitespace());
853 rustflags.env("RUSTFLAGS_NOT_BOOTSTRAP");
855 if let Ok(s) = env::var("CARGOFLAGS_BOOTSTRAP") {
856 cargo.args(s.split_whitespace());
858 rustflags.env("RUSTFLAGS_BOOTSTRAP");
859 rustflags.arg("--cfg=bootstrap");
862 // FIXME: It might be better to use the same value for both `RUSTFLAGS` and `RUSTDOCFLAGS`,
863 // but this breaks CI. At the very least, stage0 `rustdoc` needs `--cfg bootstrap`. See
865 let mut rustdocflags = rustflags.clone();
867 if let Ok(s) = env::var("CARGOFLAGS") {
868 cargo.args(s.split_whitespace());
872 Mode::Std | Mode::ToolBootstrap | Mode::ToolStd => {}
873 Mode::Rustc | Mode::Codegen | Mode::ToolRustc => {
874 // Build proc macros both for the host and the target
875 if target != compiler.host && cmd != "check" {
876 cargo.arg("-Zdual-proc-macros");
877 rustflags.arg("-Zdual-proc-macros");
882 // This tells Cargo (and in turn, rustc) to output more complete
883 // dependency information. Most importantly for rustbuild, this
884 // includes sysroot artifacts, like libstd, which means that we don't
885 // need to track those in rustbuild (an error prone process!). This
886 // feature is currently unstable as there may be some bugs and such, but
887 // it represents a big improvement in rustbuild's reliability on
888 // rebuilds, so we're using it here.
890 // For some additional context, see #63470 (the PR originally adding
891 // this), as well as #63012 which is the tracking issue for this
892 // feature on the rustc side.
893 cargo.arg("-Zbinary-dep-depinfo");
895 cargo.arg("-j").arg(self.jobs().to_string());
896 // Remove make-related flags to ensure Cargo can correctly set things up
897 cargo.env_remove("MAKEFLAGS");
898 cargo.env_remove("MFLAGS");
900 // FIXME: Temporary fix for https://github.com/rust-lang/cargo/issues/3005
901 // Force cargo to output binaries with disambiguating hashes in the name
902 let mut metadata = if compiler.stage == 0 {
903 // Treat stage0 like a special channel, whether it's a normal prior-
904 // release rustc or a local rebuild with the same version, so we
905 // never mix these libraries by accident.
906 "bootstrap".to_string()
908 self.config.channel.to_string()
910 // We want to make sure that none of the dependencies between
911 // std/test/rustc unify with one another. This is done for weird linkage
912 // reasons but the gist of the problem is that if librustc, libtest, and
913 // libstd all depend on libc from crates.io (which they actually do) we
914 // want to make sure they all get distinct versions. Things get really
915 // weird if we try to unify all these dependencies right now, namely
916 // around how many times the library is linked in dynamic libraries and
917 // such. If rustc were a static executable or if we didn't ship dylibs
918 // this wouldn't be a problem, but we do, so it is. This is in general
919 // just here to make sure things build right. If you can remove this and
920 // things still build right, please do!
922 Mode::Std => metadata.push_str("std"),
923 // When we're building rustc tools, they're built with a search path
924 // that contains things built during the rustc build. For example,
925 // bitflags is built during the rustc build, and is a dependency of
926 // rustdoc as well. We're building rustdoc in a different target
927 // directory, though, which means that Cargo will rebuild the
928 // dependency. When we go on to build rustdoc, we'll look for
929 // bitflags, and find two different copies: one built during the
930 // rustc step and one that we just built. This isn't always a
931 // problem, somehow -- not really clear why -- but we know that this
933 Mode::ToolRustc => metadata.push_str("tool-rustc"),
936 cargo.env("__CARGO_DEFAULT_LIB_METADATA", &metadata);
939 rustflags.arg("-Zforce-unstable-if-unmarked");
942 rustflags.arg("-Zmacro-backtrace");
944 let want_rustdoc = self.doc_tests != DocTests::No;
946 // We synthetically interpret a stage0 compiler used to build tools as a
947 // "raw" compiler in that it's the exact snapshot we download. Normally
948 // the stage0 build means it uses libraries build by the stage0
949 // compiler, but for tools we just use the precompiled libraries that
951 let use_snapshot = mode == Mode::ToolBootstrap;
952 assert!(!use_snapshot || stage == 0 || self.local_rebuild);
954 let maybe_sysroot = self.sysroot(compiler);
955 let sysroot = if use_snapshot { self.rustc_snapshot_sysroot() } else { &maybe_sysroot };
956 let libdir = self.rustc_libdir(compiler);
958 // Clear the output directory if the real rustc we're using has changed;
959 // Cargo cannot detect this as it thinks rustc is bootstrap/debug/rustc.
961 // Avoid doing this during dry run as that usually means the relevant
962 // compiler is not yet linked/copied properly.
964 // Only clear out the directory if we're compiling std; otherwise, we
965 // should let Cargo take care of things for us (via depdep info)
966 if !self.config.dry_run && mode == Mode::Std && cmd == "build" {
967 self.clear_if_dirty(&out_dir, &self.rustc(compiler));
970 // Customize the compiler we're running. Specify the compiler to cargo
971 // as our shim and then pass it some various options used to configure
972 // how the actual compiler itself is called.
974 // These variables are primarily all read by
975 // src/bootstrap/bin/{rustc.rs,rustdoc.rs}
977 .env("RUSTBUILD_NATIVE_DIR", self.native_dir(target))
978 .env("RUSTC", self.out.join("bootstrap/debug/rustc"))
979 .env("RUSTC_REAL", self.rustc(compiler))
980 .env("RUSTC_STAGE", stage.to_string())
981 .env("RUSTC_SYSROOT", &sysroot)
982 .env("RUSTC_LIBDIR", &libdir)
983 .env("RUSTDOC", self.out.join("bootstrap/debug/rustdoc"))
986 if cmd == "doc" || cmd == "rustdoc" || (cmd == "test" && want_rustdoc) {
987 self.rustdoc(compiler)
989 PathBuf::from("/path/to/nowhere/rustdoc/not/required")
992 .env("RUSTC_ERROR_METADATA_DST", self.extended_error_dir())
993 .env("RUSTC_BREAK_ON_ICE", "1");
995 // Dealing with rpath here is a little special, so let's go into some
996 // detail. First off, `-rpath` is a linker option on Unix platforms
997 // which adds to the runtime dynamic loader path when looking for
998 // dynamic libraries. We use this by default on Unix platforms to ensure
999 // that our nightlies behave the same on Windows, that is they work out
1000 // of the box. This can be disabled, of course, but basically that's why
1001 // we're gated on RUSTC_RPATH here.
1003 // Ok, so the astute might be wondering "why isn't `-C rpath` used
1004 // here?" and that is indeed a good question to ask. This codegen
1005 // option is the compiler's current interface to generating an rpath.
1006 // Unfortunately it doesn't quite suffice for us. The flag currently
1007 // takes no value as an argument, so the compiler calculates what it
1008 // should pass to the linker as `-rpath`. This unfortunately is based on
1009 // the **compile time** directory structure which when building with
1010 // Cargo will be very different than the runtime directory structure.
1012 // All that's a really long winded way of saying that if we use
1013 // `-Crpath` then the executables generated have the wrong rpath of
1014 // something like `$ORIGIN/deps` when in fact the way we distribute
1015 // rustc requires the rpath to be `$ORIGIN/../lib`.
1017 // So, all in all, to set up the correct rpath we pass the linker
1018 // argument manually via `-C link-args=-Wl,-rpath,...`. Plus isn't it
1019 // fun to pass a flag to a tool to pass a flag to pass a flag to a tool
1020 // to change a flag in a binary?
1021 if self.config.rust_rpath && util::use_host_linker(target) {
1022 let rpath = if target.contains("apple") {
1023 // Note that we need to take one extra step on macOS to also pass
1024 // `-Wl,-instal_name,@rpath/...` to get things to work right. To
1025 // do that we pass a weird flag to the compiler to get it to do
1026 // so. Note that this is definitely a hack, and we should likely
1027 // flesh out rpath support more fully in the future.
1028 rustflags.arg("-Zosx-rpath-install-name");
1029 Some("-Wl,-rpath,@loader_path/../lib")
1030 } else if !target.contains("windows") {
1031 Some("-Wl,-rpath,$ORIGIN/../lib")
1035 if let Some(rpath) = rpath {
1036 rustflags.arg(&format!("-Clink-args={}", rpath));
1040 // FIXME: Don't use LLD if we're compiling libtest, since it fails to link it.
1041 // See https://github.com/rust-lang/rust/issues/68647.
1042 let can_use_lld = mode != Mode::Std;
1044 if let Some(host_linker) = self.linker(compiler.host, can_use_lld) {
1045 cargo.env("RUSTC_HOST_LINKER", host_linker);
1048 if let Some(target_linker) = self.linker(target, can_use_lld) {
1049 let target = crate::envify(&target.triple);
1050 cargo.env(&format!("CARGO_TARGET_{}_LINKER", target), target_linker);
1052 if !(["build", "check", "clippy", "fix", "rustc"].contains(&cmd)) && want_rustdoc {
1053 cargo.env("RUSTDOC_LIBDIR", self.rustc_libdir(compiler));
1056 let debuginfo_level = match mode {
1057 Mode::Rustc | Mode::Codegen => self.config.rust_debuginfo_level_rustc,
1058 Mode::Std => self.config.rust_debuginfo_level_std,
1059 Mode::ToolBootstrap | Mode::ToolStd | Mode::ToolRustc => {
1060 self.config.rust_debuginfo_level_tools
1063 cargo.env(profile_var("DEBUG"), debuginfo_level.to_string());
1065 profile_var("DEBUG_ASSERTIONS"),
1066 if mode == Mode::Std {
1067 self.config.rust_debug_assertions_std.to_string()
1069 self.config.rust_debug_assertions.to_string()
1073 if !mode.is_tool() {
1074 cargo.env("RUSTC_FORCE_UNSTABLE", "1");
1077 if let Some(x) = self.crt_static(target) {
1079 rustflags.arg("-Ctarget-feature=+crt-static");
1081 rustflags.arg("-Ctarget-feature=-crt-static");
1085 if let Some(x) = self.crt_static(compiler.host) {
1086 cargo.env("RUSTC_HOST_CRT_STATIC", x.to_string());
1089 if let Some(map_to) = self.build.debuginfo_map_to(GitRepo::Rustc) {
1090 let map = format!("{}={}", self.build.src.display(), map_to);
1091 cargo.env("RUSTC_DEBUGINFO_MAP", map);
1093 // `rustc` needs to know the virtual `/rustc/$hash` we're mapping to,
1094 // in order to opportunistically reverse it later.
1095 cargo.env("CFG_VIRTUAL_RUST_SOURCE_BASE_DIR", map_to);
1098 // Enable usage of unstable features
1099 cargo.env("RUSTC_BOOTSTRAP", "1");
1100 self.add_rust_test_threads(&mut cargo);
1102 // Almost all of the crates that we compile as part of the bootstrap may
1103 // have a build script, including the standard library. To compile a
1104 // build script, however, it itself needs a standard library! This
1105 // introduces a bit of a pickle when we're compiling the standard
1108 // To work around this we actually end up using the snapshot compiler
1109 // (stage0) for compiling build scripts of the standard library itself.
1110 // The stage0 compiler is guaranteed to have a libstd available for use.
1112 // For other crates, however, we know that we've already got a standard
1113 // library up and running, so we can use the normal compiler to compile
1114 // build scripts in that situation.
1115 if mode == Mode::Std {
1117 .env("RUSTC_SNAPSHOT", &self.initial_rustc)
1118 .env("RUSTC_SNAPSHOT_LIBDIR", self.rustc_snapshot_libdir());
1121 .env("RUSTC_SNAPSHOT", self.rustc(compiler))
1122 .env("RUSTC_SNAPSHOT_LIBDIR", self.rustc_libdir(compiler));
1125 // Tools that use compiler libraries may inherit the `-lLLVM` link
1126 // requirement, but the `-L` library path is not propagated across
1127 // separate Cargo projects. We can add LLVM's library path to the
1128 // platform-specific environment variable as a workaround.
1129 if mode == Mode::ToolRustc {
1130 if let Some(llvm_config) = self.llvm_config(target) {
1131 let llvm_libdir = output(Command::new(&llvm_config).arg("--libdir"));
1132 add_link_lib_path(vec![llvm_libdir.trim().into()], &mut cargo);
1136 if self.config.incremental {
1137 cargo.env("CARGO_INCREMENTAL", "1");
1139 // Don't rely on any default setting for incr. comp. in Cargo
1140 cargo.env("CARGO_INCREMENTAL", "0");
1143 if let Some(ref on_fail) = self.config.on_fail {
1144 cargo.env("RUSTC_ON_FAIL", on_fail);
1147 if self.config.print_step_timings {
1148 cargo.env("RUSTC_PRINT_STEP_TIMINGS", "1");
1151 if self.config.backtrace_on_ice {
1152 cargo.env("RUSTC_BACKTRACE_ON_ICE", "1");
1155 cargo.env("RUSTC_VERBOSE", self.verbosity.to_string());
1157 if source_type == SourceType::InTree {
1158 let mut lint_flags = Vec::new();
1159 // When extending this list, add the new lints to the RUSTFLAGS of the
1160 // build_bootstrap function of src/bootstrap/bootstrap.py as well as
1161 // some code doesn't go through this `rustc` wrapper.
1162 lint_flags.push("-Wrust_2018_idioms");
1163 lint_flags.push("-Wunused_lifetimes");
1165 if self.config.deny_warnings {
1166 lint_flags.push("-Dwarnings");
1167 rustdocflags.arg("-Dwarnings");
1170 // FIXME(#58633) hide "unused attribute" errors in incremental
1171 // builds of the standard library, as the underlying checks are
1172 // not yet properly integrated with incremental recompilation.
1173 if mode == Mode::Std && compiler.stage == 0 && self.config.incremental {
1174 lint_flags.push("-Aunused-attributes");
1176 // This does not use RUSTFLAGS due to caching issues with Cargo.
1177 // Clippy is treated as an "in tree" tool, but shares the same
1178 // cache as other "submodule" tools. With these options set in
1179 // RUSTFLAGS, that causes *every* shared dependency to be rebuilt.
1180 // By injecting this into the rustc wrapper, this circumvents
1181 // Cargo's fingerprint detection. This is fine because lint flags
1182 // are always ignored in dependencies. Eventually this should be
1183 // fixed via better support from Cargo.
1184 cargo.env("RUSTC_LINT_FLAGS", lint_flags.join(" "));
1186 rustdocflags.arg("-Winvalid_codeblock_attributes");
1189 if let Mode::Rustc | Mode::Codegen = mode {
1190 rustflags.arg("-Zunstable-options");
1191 rustflags.arg("-Wrustc::internal");
1194 // Throughout the build Cargo can execute a number of build scripts
1195 // compiling C/C++ code and we need to pass compilers, archivers, flags, etc
1196 // obtained previously to those build scripts.
1197 // Build scripts use either the `cc` crate or `configure/make` so we pass
1198 // the options through environment variables that are fetched and understood by both.
1200 // FIXME: the guard against msvc shouldn't need to be here
1201 if target.contains("msvc") {
1202 if let Some(ref cl) = self.config.llvm_clang_cl {
1203 cargo.env("CC", cl).env("CXX", cl);
1206 let ccache = self.config.ccache.as_ref();
1207 let ccacheify = |s: &Path| {
1208 let ccache = match ccache {
1210 None => return s.display().to_string(),
1212 // FIXME: the cc-rs crate only recognizes the literal strings
1213 // `ccache` and `sccache` when doing caching compilations, so we
1214 // mirror that here. It should probably be fixed upstream to
1215 // accept a new env var or otherwise work with custom ccache
1218 "ccache" | "sccache" => format!("{} {}", ccache, s.display()),
1219 _ => s.display().to_string(),
1222 let cc = ccacheify(&self.cc(target));
1223 cargo.env(format!("CC_{}", target.triple), &cc);
1225 let cflags = self.cflags(target, GitRepo::Rustc).join(" ");
1226 cargo.env(format!("CFLAGS_{}", target.triple), cflags.clone());
1228 if let Some(ar) = self.ar(target) {
1229 let ranlib = format!("{} s", ar.display());
1231 .env(format!("AR_{}", target.triple), ar)
1232 .env(format!("RANLIB_{}", target.triple), ranlib);
1235 if let Ok(cxx) = self.cxx(target) {
1236 let cxx = ccacheify(&cxx);
1238 .env(format!("CXX_{}", target.triple), &cxx)
1239 .env(format!("CXXFLAGS_{}", target.triple), cflags);
1243 if mode == Mode::Std && self.config.extended && compiler.is_final_stage(self) {
1244 rustflags.arg("-Zsave-analysis");
1246 "RUST_SAVE_ANALYSIS_CONFIG",
1247 "{\"output_file\": null,\"full_docs\": false,\
1248 \"pub_only\": true,\"reachable_only\": false,\
1249 \"distro_crate\": true,\"signatures\": false,\"borrow_data\": false}",
1253 // If Control Flow Guard is enabled, pass the `control-flow-guard` flag to rustc
1254 // when compiling the standard library, since this might be linked into the final outputs
1255 // produced by rustc. Since this mitigation is only available on Windows, only enable it
1256 // for the standard library in case the compiler is run on a non-Windows platform.
1257 // This is not needed for stage 0 artifacts because these will only be used for building
1258 // the stage 1 compiler.
1260 && mode == Mode::Std
1261 && self.config.control_flow_guard
1262 && compiler.stage >= 1
1264 rustflags.arg("-Ccontrol-flow-guard");
1267 // For `cargo doc` invocations, make rustdoc print the Rust version into the docs
1268 cargo.env("RUSTDOC_CRATE_VERSION", self.rust_version());
1270 // Environment variables *required* throughout the build
1272 // FIXME: should update code to not require this env var
1273 cargo.env("CFG_COMPILER_HOST_TRIPLE", target.triple);
1275 // Set this for all builds to make sure doc builds also get it.
1276 cargo.env("CFG_RELEASE_CHANNEL", &self.config.channel);
1278 // This one's a bit tricky. As of the time of this writing the compiler
1279 // links to the `winapi` crate on crates.io. This crate provides raw
1280 // bindings to Windows system functions, sort of like libc does for
1281 // Unix. This crate also, however, provides "import libraries" for the
1282 // MinGW targets. There's an import library per dll in the windows
1283 // distribution which is what's linked to. These custom import libraries
1284 // are used because the winapi crate can reference Windows functions not
1285 // present in the MinGW import libraries.
1287 // For example MinGW may ship libdbghelp.a, but it may not have
1288 // references to all the functions in the dbghelp dll. Instead the
1289 // custom import library for dbghelp in the winapi crates has all this
1292 // Unfortunately for us though the import libraries are linked by
1293 // default via `-ldylib=winapi_foo`. That is, they're linked with the
1294 // `dylib` type with a `winapi_` prefix (so the winapi ones don't
1295 // conflict with the system MinGW ones). This consequently means that
1296 // the binaries we ship of things like rustc_codegen_llvm (aka the rustc_codegen_llvm
1297 // DLL) when linked against *again*, for example with procedural macros
1298 // or plugins, will trigger the propagation logic of `-ldylib`, passing
1299 // `-lwinapi_foo` to the linker again. This isn't actually available in
1300 // our distribution, however, so the link fails.
1302 // To solve this problem we tell winapi to not use its bundled import
1303 // libraries. This means that it will link to the system MinGW import
1304 // libraries by default, and the `-ldylib=foo` directives will still get
1305 // passed to the final linker, but they'll look like `-lfoo` which can
1306 // be resolved because MinGW has the import library. The downside is we
1307 // don't get newer functions from Windows, but we don't use any of them
1309 if !mode.is_tool() {
1310 cargo.env("WINAPI_NO_BUNDLED_LIBRARIES", "1");
1313 for _ in 1..self.verbosity {
1317 match (mode, self.config.rust_codegen_units_std, self.config.rust_codegen_units) {
1318 (Mode::Std, Some(n), _) | (_, _, Some(n)) => {
1319 cargo.env(profile_var("CODEGEN_UNITS"), n.to_string());
1322 // Don't set anything
1326 if self.config.rust_optimize {
1327 // FIXME: cargo bench/install do not accept `--release`
1328 if cmd != "bench" && cmd != "install" {
1329 cargo.arg("--release");
1333 if self.config.locked_deps {
1334 cargo.arg("--locked");
1336 if self.config.vendor || self.is_sudo {
1337 cargo.arg("--frozen");
1340 // Try to use a sysroot-relative bindir, in case it was configured absolutely.
1341 cargo.env("RUSTC_INSTALL_BINDIR", self.config.bindir_relative());
1343 self.ci_env.force_coloring_in_ci(&mut cargo);
1345 // When we build Rust dylibs they're all intended for intermediate
1346 // usage, so make sure we pass the -Cprefer-dynamic flag instead of
1347 // linking all deps statically into the dylib.
1348 if let Mode::Std | Mode::Rustc | Mode::Codegen = mode {
1349 rustflags.arg("-Cprefer-dynamic");
1352 // When building incrementally we default to a lower ThinLTO import limit
1353 // (unless explicitly specified otherwise). This will produce a somewhat
1354 // slower code but give way better compile times.
1356 let limit = match self.config.rust_thin_lto_import_instr_limit {
1357 Some(limit) => Some(limit),
1358 None if self.config.incremental => Some(10),
1362 if let Some(limit) = limit {
1363 rustflags.arg(&format!("-Cllvm-args=-import-instr-limit={}", limit));
1367 Cargo { command: cargo, rustflags, rustdocflags }
1370 /// Ensure that a given step is built, returning its output. This will
1371 /// cache the step, so it is safe (and good!) to call this as often as
1372 /// needed to ensure that all dependencies are built.
1373 pub fn ensure<S: Step>(&'a self, step: S) -> S::Output {
1375 let mut stack = self.stack.borrow_mut();
1376 for stack_step in stack.iter() {
1378 if stack_step.downcast_ref::<S>().map_or(true, |stack_step| *stack_step != step) {
1381 let mut out = String::new();
1382 out += &format!("\n\nCycle in build detected when adding {:?}\n", step);
1383 for el in stack.iter().rev() {
1384 out += &format!("\t{:?}\n", el);
1388 if let Some(out) = self.cache.get(&step) {
1389 self.verbose(&format!("{}c {:?}", " ".repeat(stack.len()), step));
1393 self.verbose(&format!("{}> {:?}", " ".repeat(stack.len()), step));
1394 stack.push(Box::new(step.clone()));
1398 let start = Instant::now();
1399 let zero = Duration::new(0, 0);
1400 let parent = self.time_spent_on_dependencies.replace(zero);
1401 let out = step.clone().run(self);
1402 let dur = start.elapsed();
1403 let deps = self.time_spent_on_dependencies.replace(parent + dur);
1407 if self.config.print_step_timings && dur > Duration::from_millis(100) {
1408 println!("[TIMING] {:?} -- {}.{:03}", step, dur.as_secs(), dur.subsec_millis());
1412 let mut stack = self.stack.borrow_mut();
1413 let cur_step = stack.pop().expect("step stack empty");
1414 assert_eq!(cur_step.downcast_ref(), Some(&step));
1416 self.verbose(&format!("{}< {:?}", " ".repeat(self.stack.borrow().len()), step));
1417 self.cache.put(step, out.clone());
1425 #[derive(Debug, Clone)]
1426 struct Rustflags(String);
1429 fn new(target: TargetSelection) -> Rustflags {
1430 let mut ret = Rustflags(String::new());
1432 // Inherit `RUSTFLAGS` by default ...
1433 ret.env("RUSTFLAGS");
1435 // ... and also handle target-specific env RUSTFLAGS if they're
1437 let target_specific = format!("CARGO_TARGET_{}_RUSTFLAGS", crate::envify(&target.triple));
1438 ret.env(&target_specific);
1443 fn env(&mut self, env: &str) {
1444 if let Ok(s) = env::var(env) {
1445 for part in s.split_whitespace() {
1451 fn arg(&mut self, arg: &str) -> &mut Self {
1452 assert_eq!(arg.split_whitespace().count(), 1);
1453 if !self.0.is_empty() {
1454 self.0.push_str(" ");
1456 self.0.push_str(arg);
1464 rustflags: Rustflags,
1465 rustdocflags: Rustflags,
1469 pub fn rustdocflag(&mut self, arg: &str) -> &mut Cargo {
1470 self.rustdocflags.arg(arg);
1473 pub fn rustflag(&mut self, arg: &str) -> &mut Cargo {
1474 self.rustflags.arg(arg);
1478 pub fn arg(&mut self, arg: impl AsRef<OsStr>) -> &mut Cargo {
1479 self.command.arg(arg.as_ref());
1483 pub fn args<I, S>(&mut self, args: I) -> &mut Cargo
1485 I: IntoIterator<Item = S>,
1489 self.arg(arg.as_ref());
1494 pub fn env(&mut self, key: impl AsRef<OsStr>, value: impl AsRef<OsStr>) -> &mut Cargo {
1495 // These are managed through rustflag/rustdocflag interfaces.
1496 assert_ne!(key.as_ref(), "RUSTFLAGS");
1497 assert_ne!(key.as_ref(), "RUSTDOCFLAGS");
1498 self.command.env(key.as_ref(), value.as_ref());
1503 impl From<Cargo> for Command {
1504 fn from(mut cargo: Cargo) -> Command {
1505 let rustflags = &cargo.rustflags.0;
1506 if !rustflags.is_empty() {
1507 cargo.command.env("RUSTFLAGS", rustflags);
1510 let rustdocflags = &cargo.rustdocflags.0;
1511 if !rustdocflags.is_empty() {
1512 cargo.command.env("RUSTDOCFLAGS", rustdocflags);