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};
21 use crate::flags::Subcommand;
27 use crate::util::{self, add_dylib_path, add_link_lib_path, exe, libdir};
28 use crate::{Build, DocTests, GitRepo, Mode};
30 pub use crate::Compiler;
32 pub struct Builder<'a> {
37 stack: RefCell<Vec<Box<dyn Any>>>,
38 time_spent_on_dependencies: Cell<Duration>,
39 pub paths: Vec<PathBuf>,
42 impl<'a> Deref for Builder<'a> {
45 fn deref(&self) -> &Self::Target {
50 pub trait Step: 'static + Clone + Debug + PartialEq + Eq + Hash {
51 /// `PathBuf` when directories are created or to return a `Compiler` once
52 /// it's been assembled.
55 const DEFAULT: bool = false;
57 /// If true, then this rule should be skipped if --target was specified, but --host was not
58 const ONLY_HOSTS: bool = false;
60 /// Primary function to execute this rule. Can call `builder.ensure()`
61 /// with other steps to run those.
62 fn run(self, builder: &Builder<'_>) -> Self::Output;
64 /// When bootstrap is passed a set of paths, this controls whether this rule
65 /// will execute. However, it does not get called in a "default" context
66 /// when we are not passed any paths; in that case, `make_run` is called
68 fn should_run(run: ShouldRun<'_>) -> ShouldRun<'_>;
70 /// Builds up a "root" rule, either as a default rule or from a path passed
73 /// When path is `None`, we are executing in a context where no paths were
74 /// passed. When `./x.py build` is run, for example, this rule could get
75 /// called if it is in the correct list below with a path of `None`.
76 fn make_run(_run: RunConfig<'_>) {
77 // It is reasonable to not have an implementation of make_run for rules
78 // who do not want to get called from the root context. This means that
79 // they are likely dependencies (e.g., sysroot creation) or similar, and
80 // as such calling them from ./x.py isn't logical.
85 pub struct RunConfig<'a> {
86 pub builder: &'a Builder<'a>,
87 pub host: Interned<String>,
88 pub target: Interned<String>,
92 struct StepDescription {
95 should_run: fn(ShouldRun<'_>) -> ShouldRun<'_>,
96 make_run: fn(RunConfig<'_>),
100 #[derive(Debug, Clone, PartialOrd, Ord, PartialEq, Eq)]
102 Set(BTreeSet<PathBuf>),
107 fn empty() -> PathSet {
108 PathSet::Set(BTreeSet::new())
111 fn one<P: Into<PathBuf>>(path: P) -> PathSet {
112 let mut set = BTreeSet::new();
113 set.insert(path.into());
117 fn has(&self, needle: &Path) -> bool {
119 PathSet::Set(set) => set.iter().any(|p| p.ends_with(needle)),
120 PathSet::Suite(suite) => suite.ends_with(needle),
124 fn path(&self, builder: &Builder<'_>) -> PathBuf {
126 PathSet::Set(set) => set.iter().next().unwrap_or(&builder.build.src).to_path_buf(),
127 PathSet::Suite(path) => PathBuf::from(path),
132 impl StepDescription {
133 fn from<S: Step>() -> StepDescription {
136 only_hosts: S::ONLY_HOSTS,
137 should_run: S::should_run,
138 make_run: S::make_run,
139 name: std::any::type_name::<S>(),
143 fn maybe_run(&self, builder: &Builder<'_>, pathset: &PathSet) {
144 if builder.config.exclude.iter().any(|e| pathset.has(e)) {
145 eprintln!("Skipping {:?} because it is excluded", pathset);
147 } else if !builder.config.exclude.is_empty() {
149 "{:?} not skipped for {:?} -- not in {:?}",
150 pathset, self.name, builder.config.exclude
153 let hosts = &builder.hosts;
155 // Determine the targets participating in this rule.
156 let targets = if self.only_hosts {
157 if builder.config.skip_only_host_steps {
158 return; // don't run anything
167 for target in targets {
168 let run = RunConfig {
170 path: pathset.path(builder),
174 (self.make_run)(run);
179 fn run(v: &[StepDescription], builder: &Builder<'_>, paths: &[PathBuf]) {
181 v.iter().map(|desc| (desc.should_run)(ShouldRun::new(builder))).collect::<Vec<_>>();
183 // sanity checks on rules
184 for (desc, should_run) in v.iter().zip(&should_runs) {
186 !should_run.paths.is_empty(),
187 "{:?} should have at least one pathset",
192 if paths.is_empty() {
193 for (desc, should_run) in v.iter().zip(should_runs) {
194 if desc.default && should_run.is_really_default {
195 for pathset in &should_run.paths {
196 desc.maybe_run(builder, pathset);
202 // strip CurDir prefix if present
203 let path = match path.strip_prefix(".") {
208 let mut attempted_run = false;
209 for (desc, should_run) in v.iter().zip(&should_runs) {
210 if let Some(suite) = should_run.is_suite_path(path) {
211 attempted_run = true;
212 desc.maybe_run(builder, suite);
213 } else if let Some(pathset) = should_run.pathset_for_path(path) {
214 attempted_run = true;
215 desc.maybe_run(builder, pathset);
220 panic!("Error: no rules matched {}.", path.display());
228 pub struct ShouldRun<'a> {
229 pub builder: &'a Builder<'a>,
230 // use a BTreeSet to maintain sort order
231 paths: BTreeSet<PathSet>,
233 // If this is a default rule, this is an additional constraint placed on
234 // its run. Generally something like compiler docs being enabled.
235 is_really_default: bool,
238 impl<'a> ShouldRun<'a> {
239 fn new(builder: &'a Builder<'_>) -> ShouldRun<'a> {
242 paths: BTreeSet::new(),
243 is_really_default: true, // by default no additional conditions
247 pub fn default_condition(mut self, cond: bool) -> Self {
248 self.is_really_default = cond;
252 // Unlike `krate` this will create just one pathset. As such, it probably shouldn't actually
253 // ever be used, but as we transition to having all rules properly handle passing krate(...) by
254 // actually doing something different for every crate passed.
255 pub fn all_krates(mut self, name: &str) -> Self {
256 let mut set = BTreeSet::new();
257 for krate in self.builder.in_tree_crates(name) {
258 set.insert(PathBuf::from(&krate.path));
260 self.paths.insert(PathSet::Set(set));
264 pub fn krate(mut self, name: &str) -> Self {
265 for krate in self.builder.in_tree_crates(name) {
266 self.paths.insert(PathSet::one(&krate.path));
271 // single, non-aliased path
272 pub fn path(self, path: &str) -> Self {
276 // multiple aliases for the same job
277 pub fn paths(mut self, paths: &[&str]) -> Self {
278 self.paths.insert(PathSet::Set(paths.iter().map(PathBuf::from).collect()));
282 pub fn is_suite_path(&self, path: &Path) -> Option<&PathSet> {
283 self.paths.iter().find(|pathset| match pathset {
284 PathSet::Suite(p) => path.starts_with(p),
285 PathSet::Set(_) => false,
289 pub fn suite_path(mut self, suite: &str) -> Self {
290 self.paths.insert(PathSet::Suite(PathBuf::from(suite)));
294 // allows being more explicit about why should_run in Step returns the value passed to it
295 pub fn never(mut self) -> ShouldRun<'a> {
296 self.paths.insert(PathSet::empty());
300 fn pathset_for_path(&self, path: &Path) -> Option<&PathSet> {
301 self.paths.iter().find(|pathset| pathset.has(path))
305 #[derive(Copy, Clone, PartialEq, Eq, Debug)]
320 impl<'a> Builder<'a> {
321 fn get_step_descriptions(kind: Kind) -> Vec<StepDescription> {
322 macro_rules! describe {
323 ($($rule:ty),+ $(,)?) => {{
324 vec![$(StepDescription::from::<$rule>()),+]
328 Kind::Build => describe!(
331 compile::StartupObjects,
335 tool::UnstableBookGen,
340 tool::RemoteTestServer,
341 tool::RemoteTestClient,
353 Kind::Check | Kind::Clippy | Kind::Fix | Kind::Format => {
354 describe!(check::Std, check::Rustc, check::Rustdoc)
356 Kind::Test => describe!(
357 crate::toolstate::ToolStateCheck,
358 test::ExpandYamlAnchors,
363 test::RunPassValgrind,
374 test::RunPassValgrindPretty,
384 test::RunMakeFullDeps,
398 test::CompiletestTest,
400 test::RustdocJSNotStd,
403 // Run bootstrap close to the end as it's unlikely to fail
405 // Run run-make last, since these won't pass without make on Windows
408 Kind::Bench => describe!(test::Crate, test::CrateLibrustc),
409 Kind::Doc => describe!(
411 doc::UnstableBookGen,
427 Kind::Dist => describe!(
432 dist::DebuggerScripts,
437 dist::PlainSourceTarball,
448 Kind::Install => describe!(
460 Kind::Run => describe!(run::ExpandYamlAnchors,),
464 pub fn get_help(build: &Build, subcommand: &str) -> Option<String> {
465 let kind = match subcommand {
466 "build" => Kind::Build,
468 "test" => Kind::Test,
469 "bench" => Kind::Bench,
470 "dist" => Kind::Dist,
471 "install" => Kind::Install,
475 let builder = Builder {
477 top_stage: build.config.stage.unwrap_or(2),
480 stack: RefCell::new(Vec::new()),
481 time_spent_on_dependencies: Cell::new(Duration::new(0, 0)),
485 let builder = &builder;
486 let mut should_run = ShouldRun::new(builder);
487 for desc in Builder::get_step_descriptions(builder.kind) {
488 should_run = (desc.should_run)(should_run);
490 let mut help = String::from("Available paths:\n");
491 for pathset in should_run.paths {
492 if let PathSet::Set(set) = pathset {
493 set.iter().for_each(|path| {
495 format!(" ./x.py {} {}\n", subcommand, path.display()).as_str(),
503 pub fn new(build: &Build) -> Builder<'_> {
504 let (kind, paths) = match build.config.cmd {
505 Subcommand::Build { ref paths } => (Kind::Build, &paths[..]),
506 Subcommand::Check { ref paths } => (Kind::Check, &paths[..]),
507 Subcommand::Clippy { ref paths } => (Kind::Clippy, &paths[..]),
508 Subcommand::Fix { ref paths } => (Kind::Fix, &paths[..]),
509 Subcommand::Doc { ref paths } => (Kind::Doc, &paths[..]),
510 Subcommand::Test { ref paths, .. } => (Kind::Test, &paths[..]),
511 Subcommand::Bench { ref paths, .. } => (Kind::Bench, &paths[..]),
512 Subcommand::Dist { ref paths } => (Kind::Dist, &paths[..]),
513 Subcommand::Install { ref paths } => (Kind::Install, &paths[..]),
514 Subcommand::Run { ref paths } => (Kind::Run, &paths[..]),
515 Subcommand::Format { .. } | Subcommand::Clean { .. } => panic!(),
520 top_stage: build.config.stage.unwrap_or(2),
523 stack: RefCell::new(Vec::new()),
524 time_spent_on_dependencies: Cell::new(Duration::new(0, 0)),
525 paths: paths.to_owned(),
529 pub fn execute_cli(&self) {
530 self.run_step_descriptions(&Builder::get_step_descriptions(self.kind), &self.paths);
533 pub fn default_doc(&self, paths: Option<&[PathBuf]>) {
534 let paths = paths.unwrap_or(&[]);
535 self.run_step_descriptions(&Builder::get_step_descriptions(Kind::Doc), paths);
538 fn run_step_descriptions(&self, v: &[StepDescription], paths: &[PathBuf]) {
539 StepDescription::run(v, self, paths);
542 /// Obtain a compiler at a given stage and for a given host. Explicitly does
543 /// not take `Compiler` since all `Compiler` instances are meant to be
544 /// obtained through this function, since it ensures that they are valid
545 /// (i.e., built and assembled).
546 pub fn compiler(&self, stage: u32, host: Interned<String>) -> Compiler {
547 self.ensure(compile::Assemble { target_compiler: Compiler { stage, host } })
550 /// Similar to `compiler`, except handles the full-bootstrap option to
551 /// silently use the stage1 compiler instead of a stage2 compiler if one is
554 /// Note that this does *not* have the side effect of creating
555 /// `compiler(stage, host)`, unlike `compiler` above which does have such
556 /// a side effect. The returned compiler here can only be used to compile
557 /// new artifacts, it can't be used to rely on the presence of a particular
560 /// See `force_use_stage1` for documentation on what each argument is.
564 host: Interned<String>,
565 target: Interned<String>,
567 if self.build.force_use_stage1(Compiler { stage, host }, target) {
568 self.compiler(1, self.config.build)
570 self.compiler(stage, host)
574 pub fn sysroot(&self, compiler: Compiler) -> Interned<PathBuf> {
575 self.ensure(compile::Sysroot { compiler })
578 /// Returns the libdir where the standard library and other artifacts are
579 /// found for a compiler's sysroot.
580 pub fn sysroot_libdir(
583 target: Interned<String>,
584 ) -> Interned<PathBuf> {
585 #[derive(Debug, Copy, Clone, Hash, PartialEq, Eq)]
588 target: Interned<String>,
590 impl Step for Libdir {
591 type Output = Interned<PathBuf>;
593 fn should_run(run: ShouldRun<'_>) -> ShouldRun<'_> {
597 fn run(self, builder: &Builder<'_>) -> Interned<PathBuf> {
598 let lib = builder.sysroot_libdir_relative(self.compiler);
599 let sysroot = builder
600 .sysroot(self.compiler)
605 let _ = fs::remove_dir_all(&sysroot);
606 t!(fs::create_dir_all(&sysroot));
607 INTERNER.intern_path(sysroot)
610 self.ensure(Libdir { compiler, target })
613 /// Returns the compiler's libdir where it stores the dynamic libraries that
614 /// it itself links against.
616 /// For example this returns `<sysroot>/lib` on Unix and `<sysroot>/bin` on
618 pub fn rustc_libdir(&self, compiler: Compiler) -> PathBuf {
619 if compiler.is_snapshot(self) {
620 self.rustc_snapshot_libdir()
622 match self.config.libdir_relative() {
623 Some(relative_libdir) if compiler.stage >= 1 => {
624 self.sysroot(compiler).join(relative_libdir)
626 _ => self.sysroot(compiler).join(libdir(&compiler.host)),
631 /// Returns the compiler's relative libdir where it stores the dynamic libraries that
632 /// it itself links against.
634 /// For example this returns `lib` on Unix and `bin` on
636 pub fn libdir_relative(&self, compiler: Compiler) -> &Path {
637 if compiler.is_snapshot(self) {
638 libdir(&self.config.build).as_ref()
640 match self.config.libdir_relative() {
641 Some(relative_libdir) if compiler.stage >= 1 => relative_libdir,
642 _ => libdir(&compiler.host).as_ref(),
647 /// Returns the compiler's relative libdir where the standard library and other artifacts are
648 /// found for a compiler's sysroot.
650 /// For example this returns `lib` on Unix and Windows.
651 pub fn sysroot_libdir_relative(&self, compiler: Compiler) -> &Path {
652 match self.config.libdir_relative() {
653 Some(relative_libdir) if compiler.stage >= 1 => relative_libdir,
654 _ => Path::new("lib"),
658 /// Adds the compiler's directory of dynamic libraries to `cmd`'s dynamic
659 /// library lookup path.
660 pub fn add_rustc_lib_path(&self, compiler: Compiler, cmd: &mut Cargo) {
661 // Windows doesn't need dylib path munging because the dlls for the
662 // compiler live next to the compiler and the system will find them
668 add_dylib_path(vec![self.rustc_libdir(compiler)], &mut cmd.command);
671 /// Gets a path to the compiler specified.
672 pub fn rustc(&self, compiler: Compiler) -> PathBuf {
673 if compiler.is_snapshot(self) {
674 self.initial_rustc.clone()
676 self.sysroot(compiler).join("bin").join(exe("rustc", &compiler.host))
680 pub fn rustdoc(&self, compiler: Compiler) -> PathBuf {
681 self.ensure(tool::Rustdoc { compiler })
684 pub fn rustdoc_cmd(&self, compiler: Compiler) -> Command {
685 let mut cmd = Command::new(&self.out.join("bootstrap/debug/rustdoc"));
686 cmd.env("RUSTC_STAGE", compiler.stage.to_string())
687 .env("RUSTC_SYSROOT", self.sysroot(compiler))
688 // Note that this is *not* the sysroot_libdir because rustdoc must be linked
689 // equivalently to rustc.
690 .env("RUSTDOC_LIBDIR", self.rustc_libdir(compiler))
691 .env("CFG_RELEASE_CHANNEL", &self.config.channel)
692 .env("RUSTDOC_REAL", self.rustdoc(compiler))
693 .env("RUSTDOC_CRATE_VERSION", self.rust_version())
694 .env("RUSTC_BOOTSTRAP", "1");
696 // Remove make-related flags that can cause jobserver problems.
697 cmd.env_remove("MAKEFLAGS");
698 cmd.env_remove("MFLAGS");
700 if let Some(linker) = self.linker(compiler.host, true) {
701 cmd.env("RUSTC_TARGET_LINKER", linker);
706 /// Return the path to `llvm-config` for the target, if it exists.
708 /// Note that this returns `None` if LLVM is disabled, or if we're in a
709 /// check build or dry-run, where there's no need to build all of LLVM.
710 fn llvm_config(&self, target: Interned<String>) -> Option<PathBuf> {
711 if self.config.llvm_enabled() && self.kind != Kind::Check && !self.config.dry_run {
712 let llvm_config = self.ensure(native::Llvm { target });
713 if llvm_config.is_file() {
714 return Some(llvm_config);
720 /// Prepares an invocation of `cargo` to be run.
722 /// This will create a `Command` that represents a pending execution of
723 /// Cargo. This cargo will be configured to use `compiler` as the actual
724 /// rustc compiler, its output will be scoped by `mode`'s output directory,
725 /// it will pass the `--target` flag for the specified `target`, and will be
726 /// executing the Cargo command `cmd`.
731 target: Interned<String>,
734 let mut cargo = Command::new(&self.initial_cargo);
735 let out_dir = self.stage_out(compiler, mode);
737 if cmd == "doc" || cmd == "rustdoc" {
738 let my_out = match mode {
739 // This is the intended out directory for compiler documentation.
740 Mode::Rustc | Mode::ToolRustc | Mode::Codegen => self.compiler_doc_out(target),
741 _ => self.crate_doc_out(target),
743 let rustdoc = self.rustdoc(compiler);
744 self.clear_if_dirty(&my_out, &rustdoc);
747 cargo.env("CARGO_TARGET_DIR", &out_dir).arg(cmd);
749 let profile_var = |name: &str| {
750 let profile = if self.config.rust_optimize { "RELEASE" } else { "DEV" };
751 format!("CARGO_PROFILE_{}_{}", profile, name)
754 // See comment in librustc_llvm/build.rs for why this is necessary, largely llvm-config
755 // needs to not accidentally link to libLLVM in stage0/lib.
756 cargo.env("REAL_LIBRARY_PATH_VAR", &util::dylib_path_var());
757 if let Some(e) = env::var_os(util::dylib_path_var()) {
758 cargo.env("REAL_LIBRARY_PATH", e);
761 if cmd != "install" {
762 cargo.arg("--target").arg(target);
764 assert_eq!(target, compiler.host);
767 // Set a flag for `check`/`clippy`/`fix`, so that certain build
768 // scripts can do less work (e.g. not building/requiring LLVM).
769 if cmd == "check" || cmd == "clippy" || cmd == "fix" {
770 cargo.env("RUST_CHECK", "1");
773 let stage = if compiler.stage == 0 && self.local_rebuild {
774 // Assume the local-rebuild rustc already has stage1 features.
780 let mut rustflags = Rustflags::new(&target);
782 if let Ok(s) = env::var("CARGOFLAGS_NOT_BOOTSTRAP") {
783 cargo.args(s.split_whitespace());
785 rustflags.env("RUSTFLAGS_NOT_BOOTSTRAP");
787 if let Ok(s) = env::var("CARGOFLAGS_BOOTSTRAP") {
788 cargo.args(s.split_whitespace());
790 rustflags.env("RUSTFLAGS_BOOTSTRAP");
791 rustflags.arg("--cfg=bootstrap");
794 if let Ok(s) = env::var("CARGOFLAGS") {
795 cargo.args(s.split_whitespace());
799 Mode::Std | Mode::ToolBootstrap | Mode::ToolStd => {}
800 Mode::Rustc | Mode::Codegen | Mode::ToolRustc => {
801 // Build proc macros both for the host and the target
802 if target != compiler.host && cmd != "check" {
803 cargo.arg("-Zdual-proc-macros");
804 rustflags.arg("-Zdual-proc-macros");
809 // This tells Cargo (and in turn, rustc) to output more complete
810 // dependency information. Most importantly for rustbuild, this
811 // includes sysroot artifacts, like libstd, which means that we don't
812 // need to track those in rustbuild (an error prone process!). This
813 // feature is currently unstable as there may be some bugs and such, but
814 // it represents a big improvement in rustbuild's reliability on
815 // rebuilds, so we're using it here.
817 // For some additional context, see #63470 (the PR originally adding
818 // this), as well as #63012 which is the tracking issue for this
819 // feature on the rustc side.
820 cargo.arg("-Zbinary-dep-depinfo");
822 cargo.arg("-j").arg(self.jobs().to_string());
823 // Remove make-related flags to ensure Cargo can correctly set things up
824 cargo.env_remove("MAKEFLAGS");
825 cargo.env_remove("MFLAGS");
827 // FIXME: Temporary fix for https://github.com/rust-lang/cargo/issues/3005
828 // Force cargo to output binaries with disambiguating hashes in the name
829 let mut metadata = if compiler.stage == 0 {
830 // Treat stage0 like a special channel, whether it's a normal prior-
831 // release rustc or a local rebuild with the same version, so we
832 // never mix these libraries by accident.
833 "bootstrap".to_string()
835 self.config.channel.to_string()
837 // We want to make sure that none of the dependencies between
838 // std/test/rustc unify with one another. This is done for weird linkage
839 // reasons but the gist of the problem is that if librustc, libtest, and
840 // libstd all depend on libc from crates.io (which they actually do) we
841 // want to make sure they all get distinct versions. Things get really
842 // weird if we try to unify all these dependencies right now, namely
843 // around how many times the library is linked in dynamic libraries and
844 // such. If rustc were a static executable or if we didn't ship dylibs
845 // this wouldn't be a problem, but we do, so it is. This is in general
846 // just here to make sure things build right. If you can remove this and
847 // things still build right, please do!
849 Mode::Std => metadata.push_str("std"),
850 // When we're building rustc tools, they're built with a search path
851 // that contains things built during the rustc build. For example,
852 // bitflags is built during the rustc build, and is a dependency of
853 // rustdoc as well. We're building rustdoc in a different target
854 // directory, though, which means that Cargo will rebuild the
855 // dependency. When we go on to build rustdoc, we'll look for
856 // bitflags, and find two different copies: one built during the
857 // rustc step and one that we just built. This isn't always a
858 // problem, somehow -- not really clear why -- but we know that this
860 Mode::ToolRustc => metadata.push_str("tool-rustc"),
863 cargo.env("__CARGO_DEFAULT_LIB_METADATA", &metadata);
866 rustflags.arg("-Zforce-unstable-if-unmarked");
869 rustflags.arg("-Zmacro-backtrace");
871 let want_rustdoc = self.doc_tests != DocTests::No;
873 // We synthetically interpret a stage0 compiler used to build tools as a
874 // "raw" compiler in that it's the exact snapshot we download. Normally
875 // the stage0 build means it uses libraries build by the stage0
876 // compiler, but for tools we just use the precompiled libraries that
878 let use_snapshot = mode == Mode::ToolBootstrap;
879 assert!(!use_snapshot || stage == 0 || self.local_rebuild);
881 let maybe_sysroot = self.sysroot(compiler);
882 let sysroot = if use_snapshot { self.rustc_snapshot_sysroot() } else { &maybe_sysroot };
883 let libdir = self.rustc_libdir(compiler);
885 // Clear the output directory if the real rustc we're using has changed;
886 // Cargo cannot detect this as it thinks rustc is bootstrap/debug/rustc.
888 // Avoid doing this during dry run as that usually means the relevant
889 // compiler is not yet linked/copied properly.
891 // Only clear out the directory if we're compiling std; otherwise, we
892 // should let Cargo take care of things for us (via depdep info)
893 if !self.config.dry_run && mode == Mode::Std && cmd == "build" {
894 self.clear_if_dirty(&out_dir, &self.rustc(compiler));
897 // Customize the compiler we're running. Specify the compiler to cargo
898 // as our shim and then pass it some various options used to configure
899 // how the actual compiler itself is called.
901 // These variables are primarily all read by
902 // src/bootstrap/bin/{rustc.rs,rustdoc.rs}
904 .env("RUSTBUILD_NATIVE_DIR", self.native_dir(target))
905 .env("RUSTC", self.out.join("bootstrap/debug/rustc"))
906 .env("RUSTC_REAL", self.rustc(compiler))
907 .env("RUSTC_STAGE", stage.to_string())
908 .env("RUSTC_DEBUG_ASSERTIONS", self.config.rust_debug_assertions.to_string())
909 .env("RUSTC_SYSROOT", &sysroot)
910 .env("RUSTC_LIBDIR", &libdir)
911 .env("RUSTDOC", self.out.join("bootstrap/debug/rustdoc"))
914 if cmd == "doc" || cmd == "rustdoc" || (cmd == "test" && want_rustdoc) {
915 self.rustdoc(compiler)
917 PathBuf::from("/path/to/nowhere/rustdoc/not/required")
920 .env("RUSTC_ERROR_METADATA_DST", self.extended_error_dir())
921 .env("RUSTC_BREAK_ON_ICE", "1");
923 // Dealing with rpath here is a little special, so let's go into some
924 // detail. First off, `-rpath` is a linker option on Unix platforms
925 // which adds to the runtime dynamic loader path when looking for
926 // dynamic libraries. We use this by default on Unix platforms to ensure
927 // that our nightlies behave the same on Windows, that is they work out
928 // of the box. This can be disabled, of course, but basically that's why
929 // we're gated on RUSTC_RPATH here.
931 // Ok, so the astute might be wondering "why isn't `-C rpath` used
932 // here?" and that is indeed a good question to task. This codegen
933 // option is the compiler's current interface to generating an rpath.
934 // Unfortunately it doesn't quite suffice for us. The flag currently
935 // takes no value as an argument, so the compiler calculates what it
936 // should pass to the linker as `-rpath`. This unfortunately is based on
937 // the **compile time** directory structure which when building with
938 // Cargo will be very different than the runtime directory structure.
940 // All that's a really long winded way of saying that if we use
941 // `-Crpath` then the executables generated have the wrong rpath of
942 // something like `$ORIGIN/deps` when in fact the way we distribute
943 // rustc requires the rpath to be `$ORIGIN/../lib`.
945 // So, all in all, to set up the correct rpath we pass the linker
946 // argument manually via `-C link-args=-Wl,-rpath,...`. Plus isn't it
947 // fun to pass a flag to a tool to pass a flag to pass a flag to a tool
948 // to change a flag in a binary?
949 if self.config.rust_rpath && util::use_host_linker(&target) {
950 let rpath = if target.contains("apple") {
951 // Note that we need to take one extra step on macOS to also pass
952 // `-Wl,-instal_name,@rpath/...` to get things to work right. To
953 // do that we pass a weird flag to the compiler to get it to do
954 // so. Note that this is definitely a hack, and we should likely
955 // flesh out rpath support more fully in the future.
956 rustflags.arg("-Zosx-rpath-install-name");
957 Some("-Wl,-rpath,@loader_path/../lib")
958 } else if !target.contains("windows") {
959 Some("-Wl,-rpath,$ORIGIN/../lib")
963 if let Some(rpath) = rpath {
964 rustflags.arg(&format!("-Clink-args={}", rpath));
968 // FIXME: Don't use LLD if we're compiling libtest, since it fails to link it.
969 // See https://github.com/rust-lang/rust/issues/68647.
970 let can_use_lld = mode != Mode::Std;
972 if let Some(host_linker) = self.linker(compiler.host, can_use_lld) {
973 cargo.env("RUSTC_HOST_LINKER", host_linker);
976 if let Some(target_linker) = self.linker(target, can_use_lld) {
977 let target = crate::envify(&target);
978 cargo.env(&format!("CARGO_TARGET_{}_LINKER", target), target_linker);
980 if !(["build", "check", "clippy", "fix", "rustc"].contains(&cmd)) && want_rustdoc {
981 cargo.env("RUSTDOC_LIBDIR", self.rustc_libdir(compiler));
984 let debuginfo_level = match mode {
985 Mode::Rustc | Mode::Codegen => self.config.rust_debuginfo_level_rustc,
986 Mode::Std => self.config.rust_debuginfo_level_std,
987 Mode::ToolBootstrap | Mode::ToolStd | Mode::ToolRustc => {
988 self.config.rust_debuginfo_level_tools
991 cargo.env(profile_var("DEBUG"), debuginfo_level.to_string());
994 cargo.env("RUSTC_FORCE_UNSTABLE", "1");
997 if let Some(x) = self.crt_static(target) {
999 rustflags.arg("-Ctarget-feature=+crt-static");
1001 rustflags.arg("-Ctarget-feature=-crt-static");
1005 if let Some(x) = self.crt_static(compiler.host) {
1006 cargo.env("RUSTC_HOST_CRT_STATIC", x.to_string());
1009 if let Some(map_to) = self.build.debuginfo_map_to(GitRepo::Rustc) {
1010 let map = format!("{}={}", self.build.src.display(), map_to);
1011 cargo.env("RUSTC_DEBUGINFO_MAP", map);
1013 // `rustc` needs to know the virtual `/rustc/$hash` we're mapping to,
1014 // in order to opportunistically reverse it later.
1015 cargo.env("CFG_VIRTUAL_RUST_SOURCE_BASE_DIR", map_to);
1018 // Enable usage of unstable features
1019 cargo.env("RUSTC_BOOTSTRAP", "1");
1020 self.add_rust_test_threads(&mut cargo);
1022 // Almost all of the crates that we compile as part of the bootstrap may
1023 // have a build script, including the standard library. To compile a
1024 // build script, however, it itself needs a standard library! This
1025 // introduces a bit of a pickle when we're compiling the standard
1028 // To work around this we actually end up using the snapshot compiler
1029 // (stage0) for compiling build scripts of the standard library itself.
1030 // The stage0 compiler is guaranteed to have a libstd available for use.
1032 // For other crates, however, we know that we've already got a standard
1033 // library up and running, so we can use the normal compiler to compile
1034 // build scripts in that situation.
1035 if mode == Mode::Std {
1037 .env("RUSTC_SNAPSHOT", &self.initial_rustc)
1038 .env("RUSTC_SNAPSHOT_LIBDIR", self.rustc_snapshot_libdir());
1041 .env("RUSTC_SNAPSHOT", self.rustc(compiler))
1042 .env("RUSTC_SNAPSHOT_LIBDIR", self.rustc_libdir(compiler));
1045 // Tools that use compiler libraries may inherit the `-lLLVM` link
1046 // requirement, but the `-L` library path is not propagated across
1047 // separate Cargo projects. We can add LLVM's library path to the
1048 // platform-specific environment variable as a workaround.
1049 if mode == Mode::ToolRustc {
1050 if let Some(llvm_config) = self.llvm_config(target) {
1051 let llvm_libdir = output(Command::new(&llvm_config).arg("--libdir"));
1052 add_link_lib_path(vec![llvm_libdir.trim().into()], &mut cargo);
1056 if self.config.incremental {
1057 cargo.env("CARGO_INCREMENTAL", "1");
1059 // Don't rely on any default setting for incr. comp. in Cargo
1060 cargo.env("CARGO_INCREMENTAL", "0");
1063 if let Some(ref on_fail) = self.config.on_fail {
1064 cargo.env("RUSTC_ON_FAIL", on_fail);
1067 if self.config.print_step_timings {
1068 cargo.env("RUSTC_PRINT_STEP_TIMINGS", "1");
1071 if self.config.backtrace_on_ice {
1072 cargo.env("RUSTC_BACKTRACE_ON_ICE", "1");
1075 cargo.env("RUSTC_VERBOSE", self.verbosity.to_string());
1077 if !mode.is_tool() {
1078 // When extending this list, add the new lints to the RUSTFLAGS of the
1079 // build_bootstrap function of src/bootstrap/bootstrap.py as well as
1080 // some code doesn't go through this `rustc` wrapper.
1081 rustflags.arg("-Wrust_2018_idioms");
1082 rustflags.arg("-Wunused_lifetimes");
1084 if self.config.deny_warnings {
1085 rustflags.arg("-Dwarnings");
1087 // FIXME(#58633) hide "unused attribute" errors in incremental
1088 // builds of the standard library, as the underlying checks are
1089 // not yet properly integrated with incremental recompilation.
1090 if mode == Mode::Std && compiler.stage == 0 && self.config.incremental {
1091 rustflags.arg("-Aunused-attributes");
1096 if let Mode::Rustc | Mode::Codegen = mode {
1097 rustflags.arg("-Zunstable-options");
1098 rustflags.arg("-Wrustc::internal");
1101 // Throughout the build Cargo can execute a number of build scripts
1102 // compiling C/C++ code and we need to pass compilers, archivers, flags, etc
1103 // obtained previously to those build scripts.
1104 // Build scripts use either the `cc` crate or `configure/make` so we pass
1105 // the options through environment variables that are fetched and understood by both.
1107 // FIXME: the guard against msvc shouldn't need to be here
1108 if target.contains("msvc") {
1109 if let Some(ref cl) = self.config.llvm_clang_cl {
1110 cargo.env("CC", cl).env("CXX", cl);
1113 let ccache = self.config.ccache.as_ref();
1114 let ccacheify = |s: &Path| {
1115 let ccache = match ccache {
1117 None => return s.display().to_string(),
1119 // FIXME: the cc-rs crate only recognizes the literal strings
1120 // `ccache` and `sccache` when doing caching compilations, so we
1121 // mirror that here. It should probably be fixed upstream to
1122 // accept a new env var or otherwise work with custom ccache
1125 "ccache" | "sccache" => format!("{} {}", ccache, s.display()),
1126 _ => s.display().to_string(),
1129 let cc = ccacheify(&self.cc(target));
1130 cargo.env(format!("CC_{}", target), &cc);
1132 let cflags = self.cflags(target, GitRepo::Rustc).join(" ");
1133 cargo.env(format!("CFLAGS_{}", target), cflags.clone());
1135 if let Some(ar) = self.ar(target) {
1136 let ranlib = format!("{} s", ar.display());
1137 cargo.env(format!("AR_{}", target), ar).env(format!("RANLIB_{}", target), ranlib);
1140 if let Ok(cxx) = self.cxx(target) {
1141 let cxx = ccacheify(&cxx);
1143 .env(format!("CXX_{}", target), &cxx)
1144 .env(format!("CXXFLAGS_{}", target), cflags);
1148 if mode == Mode::Std && self.config.extended && compiler.is_final_stage(self) {
1149 rustflags.arg("-Zsave-analysis");
1151 "RUST_SAVE_ANALYSIS_CONFIG",
1152 "{\"output_file\": null,\"full_docs\": false,\
1153 \"pub_only\": true,\"reachable_only\": false,\
1154 \"distro_crate\": true,\"signatures\": false,\"borrow_data\": false}",
1158 // If Control Flow Guard is enabled, pass the `control_flow_guard=checks` flag to rustc
1159 // when compiling the standard library, since this might be linked into the final outputs
1160 // produced by rustc. Since this mitigation is only available on Windows, only enable it
1161 // for the standard library in case the compiler is run on a non-Windows platform.
1162 // This is not needed for stage 0 artifacts because these will only be used for building
1163 // the stage 1 compiler.
1165 && mode == Mode::Std
1166 && self.config.control_flow_guard
1167 && compiler.stage >= 1
1169 rustflags.arg("-Zcontrol_flow_guard=checks");
1172 // For `cargo doc` invocations, make rustdoc print the Rust version into the docs
1173 cargo.env("RUSTDOC_CRATE_VERSION", self.rust_version());
1175 // Environment variables *required* throughout the build
1177 // FIXME: should update code to not require this env var
1178 cargo.env("CFG_COMPILER_HOST_TRIPLE", target);
1180 // Set this for all builds to make sure doc builds also get it.
1181 cargo.env("CFG_RELEASE_CHANNEL", &self.config.channel);
1183 // This one's a bit tricky. As of the time of this writing the compiler
1184 // links to the `winapi` crate on crates.io. This crate provides raw
1185 // bindings to Windows system functions, sort of like libc does for
1186 // Unix. This crate also, however, provides "import libraries" for the
1187 // MinGW targets. There's an import library per dll in the windows
1188 // distribution which is what's linked to. These custom import libraries
1189 // are used because the winapi crate can reference Windows functions not
1190 // present in the MinGW import libraries.
1192 // For example MinGW may ship libdbghelp.a, but it may not have
1193 // references to all the functions in the dbghelp dll. Instead the
1194 // custom import library for dbghelp in the winapi crates has all this
1197 // Unfortunately for us though the import libraries are linked by
1198 // default via `-ldylib=winapi_foo`. That is, they're linked with the
1199 // `dylib` type with a `winapi_` prefix (so the winapi ones don't
1200 // conflict with the system MinGW ones). This consequently means that
1201 // the binaries we ship of things like rustc_codegen_llvm (aka the rustc_codegen_llvm
1202 // DLL) when linked against *again*, for example with procedural macros
1203 // or plugins, will trigger the propagation logic of `-ldylib`, passing
1204 // `-lwinapi_foo` to the linker again. This isn't actually available in
1205 // our distribution, however, so the link fails.
1207 // To solve this problem we tell winapi to not use its bundled import
1208 // libraries. This means that it will link to the system MinGW import
1209 // libraries by default, and the `-ldylib=foo` directives will still get
1210 // passed to the final linker, but they'll look like `-lfoo` which can
1211 // be resolved because MinGW has the import library. The downside is we
1212 // don't get newer functions from Windows, but we don't use any of them
1214 if !mode.is_tool() {
1215 cargo.env("WINAPI_NO_BUNDLED_LIBRARIES", "1");
1218 for _ in 1..self.verbosity {
1222 match (mode, self.config.rust_codegen_units_std, self.config.rust_codegen_units) {
1223 (Mode::Std, Some(n), _) | (_, _, Some(n)) => {
1224 cargo.env(profile_var("CODEGEN_UNITS"), n.to_string());
1227 // Don't set anything
1231 if self.config.rust_optimize {
1232 // FIXME: cargo bench/install do not accept `--release`
1233 if cmd != "bench" && cmd != "install" {
1234 cargo.arg("--release");
1238 if self.config.locked_deps {
1239 cargo.arg("--locked");
1241 if self.config.vendor || self.is_sudo {
1242 cargo.arg("--frozen");
1245 // Try to use a sysroot-relative bindir, in case it was configured absolutely.
1246 cargo.env("RUSTC_INSTALL_BINDIR", self.config.bindir_relative());
1248 self.ci_env.force_coloring_in_ci(&mut cargo);
1250 // When we build Rust dylibs they're all intended for intermediate
1251 // usage, so make sure we pass the -Cprefer-dynamic flag instead of
1252 // linking all deps statically into the dylib.
1253 if let Mode::Std | Mode::Rustc | Mode::Codegen = mode {
1254 rustflags.arg("-Cprefer-dynamic");
1257 // When building incrementally we default to a lower ThinLTO import limit
1258 // (unless explicitly specified otherwise). This will produce a somewhat
1259 // slower code but give way better compile times.
1261 let limit = match self.config.rust_thin_lto_import_instr_limit {
1262 Some(limit) => Some(limit),
1263 None if self.config.incremental => Some(10),
1267 if let Some(limit) = limit {
1268 rustflags.arg(&format!("-Cllvm-args=-import-instr-limit={}", limit));
1272 Cargo { command: cargo, rustflags }
1275 /// Ensure that a given step is built, returning its output. This will
1276 /// cache the step, so it is safe (and good!) to call this as often as
1277 /// needed to ensure that all dependencies are built.
1278 pub fn ensure<S: Step>(&'a self, step: S) -> S::Output {
1280 let mut stack = self.stack.borrow_mut();
1281 for stack_step in stack.iter() {
1283 if stack_step.downcast_ref::<S>().map_or(true, |stack_step| *stack_step != step) {
1286 let mut out = String::new();
1287 out += &format!("\n\nCycle in build detected when adding {:?}\n", step);
1288 for el in stack.iter().rev() {
1289 out += &format!("\t{:?}\n", el);
1293 if let Some(out) = self.cache.get(&step) {
1294 self.verbose(&format!("{}c {:?}", " ".repeat(stack.len()), step));
1298 self.verbose(&format!("{}> {:?}", " ".repeat(stack.len()), step));
1299 stack.push(Box::new(step.clone()));
1303 let start = Instant::now();
1304 let zero = Duration::new(0, 0);
1305 let parent = self.time_spent_on_dependencies.replace(zero);
1306 let out = step.clone().run(self);
1307 let dur = start.elapsed();
1308 let deps = self.time_spent_on_dependencies.replace(parent + dur);
1312 if self.config.print_step_timings && dur > Duration::from_millis(100) {
1313 println!("[TIMING] {:?} -- {}.{:03}", step, dur.as_secs(), dur.subsec_millis());
1317 let mut stack = self.stack.borrow_mut();
1318 let cur_step = stack.pop().expect("step stack empty");
1319 assert_eq!(cur_step.downcast_ref(), Some(&step));
1321 self.verbose(&format!("{}< {:?}", " ".repeat(self.stack.borrow().len()), step));
1322 self.cache.put(step, out.clone());
1331 struct Rustflags(String);
1334 fn new(target: &str) -> Rustflags {
1335 let mut ret = Rustflags(String::new());
1337 // Inherit `RUSTFLAGS` by default ...
1338 ret.env("RUSTFLAGS");
1340 // ... and also handle target-specific env RUSTFLAGS if they're
1342 let target_specific = format!("CARGO_TARGET_{}_RUSTFLAGS", crate::envify(target));
1343 ret.env(&target_specific);
1348 fn env(&mut self, env: &str) {
1349 if let Ok(s) = env::var(env) {
1350 for part in s.split_whitespace() {
1356 fn arg(&mut self, arg: &str) -> &mut Self {
1357 assert_eq!(arg.split_whitespace().count(), 1);
1358 if !self.0.is_empty() {
1359 self.0.push_str(" ");
1361 self.0.push_str(arg);
1369 rustflags: Rustflags,
1373 pub fn rustflag(&mut self, arg: &str) -> &mut Cargo {
1374 self.rustflags.arg(arg);
1378 pub fn arg(&mut self, arg: impl AsRef<OsStr>) -> &mut Cargo {
1379 self.command.arg(arg.as_ref());
1383 pub fn args<I, S>(&mut self, args: I) -> &mut Cargo
1385 I: IntoIterator<Item = S>,
1389 self.arg(arg.as_ref());
1394 pub fn env(&mut self, key: impl AsRef<OsStr>, value: impl AsRef<OsStr>) -> &mut Cargo {
1395 self.command.env(key.as_ref(), value.as_ref());
1400 impl From<Cargo> for Command {
1401 fn from(mut cargo: Cargo) -> Command {
1402 cargo.command.env("RUSTFLAGS", &cargo.rustflags.0);