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};
16 use crate::cache::{Cache, Interned, INTERNER};
21 use crate::flags::Subcommand;
26 use crate::util::{self, add_lib_path, exe, libdir};
27 use crate::{Build, DocTests, GitRepo, Mode};
29 pub use crate::Compiler;
31 pub struct Builder<'a> {
36 stack: RefCell<Vec<Box<dyn Any>>>,
37 time_spent_on_dependencies: Cell<Duration>,
38 pub paths: Vec<PathBuf>,
41 impl<'a> Deref for Builder<'a> {
44 fn deref(&self) -> &Self::Target {
49 pub trait Step: 'static + Clone + Debug + PartialEq + Eq + Hash {
50 /// `PathBuf` when directories are created or to return a `Compiler` once
51 /// it's been assembled.
54 const DEFAULT: bool = false;
56 /// If true, then this rule should be skipped if --target was specified, but --host was not
57 const ONLY_HOSTS: bool = false;
59 /// Primary function to execute this rule. Can call `builder.ensure()`
60 /// with other steps to run those.
61 fn run(self, builder: &Builder<'_>) -> Self::Output;
63 /// When bootstrap is passed a set of paths, this controls whether this rule
64 /// will execute. However, it does not get called in a "default" context
65 /// when we are not passed any paths; in that case, `make_run` is called
67 fn should_run(run: ShouldRun<'_>) -> ShouldRun<'_>;
69 /// Builds up a "root" rule, either as a default rule or from a path passed
72 /// When path is `None`, we are executing in a context where no paths were
73 /// passed. When `./x.py build` is run, for example, this rule could get
74 /// called if it is in the correct list below with a path of `None`.
75 fn make_run(_run: RunConfig<'_>) {
76 // It is reasonable to not have an implementation of make_run for rules
77 // who do not want to get called from the root context. This means that
78 // they are likely dependencies (e.g., sysroot creation) or similar, and
79 // as such calling them from ./x.py isn't logical.
84 pub struct RunConfig<'a> {
85 pub builder: &'a Builder<'a>,
86 pub host: Interned<String>,
87 pub target: Interned<String>,
91 struct StepDescription {
94 should_run: fn(ShouldRun<'_>) -> ShouldRun<'_>,
95 make_run: fn(RunConfig<'_>),
99 #[derive(Debug, Clone, PartialOrd, Ord, PartialEq, Eq)]
101 Set(BTreeSet<PathBuf>),
106 fn empty() -> PathSet {
107 PathSet::Set(BTreeSet::new())
110 fn one<P: Into<PathBuf>>(path: P) -> PathSet {
111 let mut set = BTreeSet::new();
112 set.insert(path.into());
116 fn has(&self, needle: &Path) -> bool {
118 PathSet::Set(set) => set.iter().any(|p| p.ends_with(needle)),
119 PathSet::Suite(suite) => suite.ends_with(needle),
123 fn path(&self, builder: &Builder<'_>) -> PathBuf {
125 PathSet::Set(set) => set.iter().next().unwrap_or(&builder.build.src).to_path_buf(),
126 PathSet::Suite(path) => PathBuf::from(path),
131 impl StepDescription {
132 fn from<S: Step>() -> StepDescription {
135 only_hosts: S::ONLY_HOSTS,
136 should_run: S::should_run,
137 make_run: S::make_run,
138 name: std::any::type_name::<S>(),
142 fn maybe_run(&self, builder: &Builder<'_>, pathset: &PathSet) {
143 if builder.config.exclude.iter().any(|e| pathset.has(e)) {
144 eprintln!("Skipping {:?} because it is excluded", pathset);
146 } else if !builder.config.exclude.is_empty() {
148 "{:?} not skipped for {:?} -- not in {:?}",
149 pathset, self.name, builder.config.exclude
152 let hosts = &builder.hosts;
154 // Determine the targets participating in this rule.
155 let targets = if self.only_hosts {
156 if builder.config.skip_only_host_steps {
157 return; // don't run anything
166 for target in targets {
167 let run = RunConfig {
169 path: pathset.path(builder),
173 (self.make_run)(run);
178 fn run(v: &[StepDescription], builder: &Builder<'_>, paths: &[PathBuf]) {
180 v.iter().map(|desc| (desc.should_run)(ShouldRun::new(builder))).collect::<Vec<_>>();
182 // sanity checks on rules
183 for (desc, should_run) in v.iter().zip(&should_runs) {
185 !should_run.paths.is_empty(),
186 "{:?} should have at least one pathset",
191 if paths.is_empty() {
192 for (desc, should_run) in v.iter().zip(should_runs) {
193 if desc.default && should_run.is_really_default {
194 for pathset in &should_run.paths {
195 desc.maybe_run(builder, pathset);
201 // strip CurDir prefix if present
202 let path = match path.strip_prefix(".") {
207 let mut attempted_run = false;
208 for (desc, should_run) in v.iter().zip(&should_runs) {
209 if let Some(suite) = should_run.is_suite_path(path) {
210 attempted_run = true;
211 desc.maybe_run(builder, suite);
212 } else if let Some(pathset) = should_run.pathset_for_path(path) {
213 attempted_run = true;
214 desc.maybe_run(builder, pathset);
219 panic!("Error: no rules matched {}.", path.display());
227 pub struct ShouldRun<'a> {
228 pub builder: &'a Builder<'a>,
229 // use a BTreeSet to maintain sort order
230 paths: BTreeSet<PathSet>,
232 // If this is a default rule, this is an additional constraint placed on
233 // its run. Generally something like compiler docs being enabled.
234 is_really_default: bool,
237 impl<'a> ShouldRun<'a> {
238 fn new(builder: &'a Builder<'_>) -> ShouldRun<'a> {
241 paths: BTreeSet::new(),
242 is_really_default: true, // by default no additional conditions
246 pub fn default_condition(mut self, cond: bool) -> Self {
247 self.is_really_default = cond;
251 // Unlike `krate` this will create just one pathset. As such, it probably shouldn't actually
252 // ever be used, but as we transition to having all rules properly handle passing krate(...) by
253 // actually doing something different for every crate passed.
254 pub fn all_krates(mut self, name: &str) -> Self {
255 let mut set = BTreeSet::new();
256 for krate in self.builder.in_tree_crates(name) {
257 set.insert(PathBuf::from(&krate.path));
259 self.paths.insert(PathSet::Set(set));
263 pub fn krate(mut self, name: &str) -> Self {
264 for krate in self.builder.in_tree_crates(name) {
265 self.paths.insert(PathSet::one(&krate.path));
270 // single, non-aliased path
271 pub fn path(self, path: &str) -> Self {
275 // multiple aliases for the same job
276 pub fn paths(mut self, paths: &[&str]) -> Self {
277 self.paths.insert(PathSet::Set(paths.iter().map(PathBuf::from).collect()));
281 pub fn is_suite_path(&self, path: &Path) -> Option<&PathSet> {
282 self.paths.iter().find(|pathset| match pathset {
283 PathSet::Suite(p) => path.starts_with(p),
284 PathSet::Set(_) => false,
288 pub fn suite_path(mut self, suite: &str) -> Self {
289 self.paths.insert(PathSet::Suite(PathBuf::from(suite)));
293 // allows being more explicit about why should_run in Step returns the value passed to it
294 pub fn never(mut self) -> ShouldRun<'a> {
295 self.paths.insert(PathSet::empty());
299 fn pathset_for_path(&self, path: &Path) -> Option<&PathSet> {
300 self.paths.iter().find(|pathset| pathset.has(path))
304 #[derive(Copy, Clone, PartialEq, Eq, Debug)]
318 impl<'a> Builder<'a> {
319 fn get_step_descriptions(kind: Kind) -> Vec<StepDescription> {
320 macro_rules! describe {
321 ($($rule:ty),+ $(,)?) => {{
322 vec![$(StepDescription::from::<$rule>()),+]
326 Kind::Build => describe!(
329 compile::StartupObjects,
333 tool::UnstableBookGen,
338 tool::RemoteTestServer,
339 tool::RemoteTestClient,
350 Kind::Check | Kind::Clippy | Kind::Fix | Kind::Format => {
351 describe!(check::Std, check::Rustc, check::Rustdoc)
353 Kind::Test => describe!(
354 crate::toolstate::ToolStateCheck,
359 test::RunPassValgrind,
370 test::RunPassValgrindPretty,
380 test::RunMakeFullDeps,
394 test::CompiletestTest,
396 test::RustdocJSNotStd,
399 // Run bootstrap close to the end as it's unlikely to fail
401 // Run run-make last, since these won't pass without make on Windows
404 Kind::Bench => describe!(test::Crate, test::CrateLibrustc),
405 Kind::Doc => describe!(
407 doc::UnstableBookGen,
423 Kind::Dist => describe!(
428 dist::DebuggerScripts,
433 dist::PlainSourceTarball,
444 Kind::Install => describe!(
459 pub fn get_help(build: &Build, subcommand: &str) -> Option<String> {
460 let kind = match subcommand {
461 "build" => Kind::Build,
463 "test" => Kind::Test,
464 "bench" => Kind::Bench,
465 "dist" => Kind::Dist,
466 "install" => Kind::Install,
470 let builder = Builder {
472 top_stage: build.config.stage.unwrap_or(2),
475 stack: RefCell::new(Vec::new()),
476 time_spent_on_dependencies: Cell::new(Duration::new(0, 0)),
480 let builder = &builder;
481 let mut should_run = ShouldRun::new(builder);
482 for desc in Builder::get_step_descriptions(builder.kind) {
483 should_run = (desc.should_run)(should_run);
485 let mut help = String::from("Available paths:\n");
486 for pathset in should_run.paths {
487 if let PathSet::Set(set) = pathset {
488 set.iter().for_each(|path| {
490 format!(" ./x.py {} {}\n", subcommand, path.display()).as_str(),
498 pub fn new(build: &Build) -> Builder<'_> {
499 let (kind, paths) = match build.config.cmd {
500 Subcommand::Build { ref paths } => (Kind::Build, &paths[..]),
501 Subcommand::Check { ref paths } => (Kind::Check, &paths[..]),
502 Subcommand::Clippy { ref paths } => (Kind::Clippy, &paths[..]),
503 Subcommand::Fix { ref paths } => (Kind::Fix, &paths[..]),
504 Subcommand::Doc { ref paths } => (Kind::Doc, &paths[..]),
505 Subcommand::Test { ref paths, .. } => (Kind::Test, &paths[..]),
506 Subcommand::Bench { ref paths, .. } => (Kind::Bench, &paths[..]),
507 Subcommand::Dist { ref paths } => (Kind::Dist, &paths[..]),
508 Subcommand::Install { ref paths } => (Kind::Install, &paths[..]),
509 Subcommand::Format { .. } | Subcommand::Clean { .. } => panic!(),
512 let builder = Builder {
514 top_stage: build.config.stage.unwrap_or(2),
517 stack: RefCell::new(Vec::new()),
518 time_spent_on_dependencies: Cell::new(Duration::new(0, 0)),
519 paths: paths.to_owned(),
525 pub fn execute_cli(&self) {
526 self.run_step_descriptions(&Builder::get_step_descriptions(self.kind), &self.paths);
529 pub fn default_doc(&self, paths: Option<&[PathBuf]>) {
530 let paths = paths.unwrap_or(&[]);
531 self.run_step_descriptions(&Builder::get_step_descriptions(Kind::Doc), paths);
534 fn run_step_descriptions(&self, v: &[StepDescription], paths: &[PathBuf]) {
535 StepDescription::run(v, self, paths);
538 /// Obtain a compiler at a given stage and for a given host. Explicitly does
539 /// not take `Compiler` since all `Compiler` instances are meant to be
540 /// obtained through this function, since it ensures that they are valid
541 /// (i.e., built and assembled).
542 pub fn compiler(&self, stage: u32, host: Interned<String>) -> Compiler {
543 self.ensure(compile::Assemble { target_compiler: Compiler { stage, host } })
546 /// Similar to `compiler`, except handles the full-bootstrap option to
547 /// silently use the stage1 compiler instead of a stage2 compiler if one is
550 /// Note that this does *not* have the side effect of creating
551 /// `compiler(stage, host)`, unlike `compiler` above which does have such
552 /// a side effect. The returned compiler here can only be used to compile
553 /// new artifacts, it can't be used to rely on the presence of a particular
556 /// See `force_use_stage1` for documentation on what each argument is.
560 host: Interned<String>,
561 target: Interned<String>,
563 if self.build.force_use_stage1(Compiler { stage, host }, target) {
564 self.compiler(1, self.config.build)
566 self.compiler(stage, host)
570 pub fn sysroot(&self, compiler: Compiler) -> Interned<PathBuf> {
571 self.ensure(compile::Sysroot { compiler })
574 /// Returns the libdir where the standard library and other artifacts are
575 /// found for a compiler's sysroot.
576 pub fn sysroot_libdir(
579 target: Interned<String>,
580 ) -> Interned<PathBuf> {
581 #[derive(Debug, Copy, Clone, Hash, PartialEq, Eq)]
584 target: Interned<String>,
586 impl Step for Libdir {
587 type Output = Interned<PathBuf>;
589 fn should_run(run: ShouldRun<'_>) -> ShouldRun<'_> {
593 fn run(self, builder: &Builder<'_>) -> Interned<PathBuf> {
594 let lib = builder.sysroot_libdir_relative(self.compiler);
595 let sysroot = builder
596 .sysroot(self.compiler)
601 let _ = fs::remove_dir_all(&sysroot);
602 t!(fs::create_dir_all(&sysroot));
603 INTERNER.intern_path(sysroot)
606 self.ensure(Libdir { compiler, target })
609 /// Returns the compiler's libdir where it stores the dynamic libraries that
610 /// it itself links against.
612 /// For example this returns `<sysroot>/lib` on Unix and `<sysroot>/bin` on
614 pub fn rustc_libdir(&self, compiler: Compiler) -> PathBuf {
615 if compiler.is_snapshot(self) {
616 self.rustc_snapshot_libdir()
618 match self.config.libdir_relative() {
619 Some(relative_libdir) if compiler.stage >= 1 => {
620 self.sysroot(compiler).join(relative_libdir)
622 _ => self.sysroot(compiler).join(libdir(&compiler.host)),
627 /// Returns the compiler's relative libdir where it stores the dynamic libraries that
628 /// it itself links against.
630 /// For example this returns `lib` on Unix and `bin` on
632 pub fn libdir_relative(&self, compiler: Compiler) -> &Path {
633 if compiler.is_snapshot(self) {
634 libdir(&self.config.build).as_ref()
636 match self.config.libdir_relative() {
637 Some(relative_libdir) if compiler.stage >= 1 => relative_libdir,
638 _ => libdir(&compiler.host).as_ref(),
643 /// Returns the compiler's relative libdir where the standard library and other artifacts are
644 /// found for a compiler's sysroot.
646 /// For example this returns `lib` on Unix and Windows.
647 pub fn sysroot_libdir_relative(&self, compiler: Compiler) -> &Path {
648 match self.config.libdir_relative() {
649 Some(relative_libdir) if compiler.stage >= 1 => relative_libdir,
650 _ => Path::new("lib"),
654 /// Adds the compiler's directory of dynamic libraries to `cmd`'s dynamic
655 /// library lookup path.
656 pub fn add_rustc_lib_path(&self, compiler: Compiler, cmd: &mut Cargo) {
657 // Windows doesn't need dylib path munging because the dlls for the
658 // compiler live next to the compiler and the system will find them
664 add_lib_path(vec![self.rustc_libdir(compiler)], &mut cmd.command);
667 /// Gets a path to the compiler specified.
668 pub fn rustc(&self, compiler: Compiler) -> PathBuf {
669 if compiler.is_snapshot(self) {
670 self.initial_rustc.clone()
672 self.sysroot(compiler).join("bin").join(exe("rustc", &compiler.host))
676 pub fn rustdoc(&self, compiler: Compiler) -> PathBuf {
677 self.ensure(tool::Rustdoc { compiler })
680 pub fn rustdoc_cmd(&self, compiler: Compiler) -> Command {
681 let mut cmd = Command::new(&self.out.join("bootstrap/debug/rustdoc"));
682 cmd.env("RUSTC_STAGE", compiler.stage.to_string())
683 .env("RUSTC_SYSROOT", self.sysroot(compiler))
684 // Note that this is *not* the sysroot_libdir because rustdoc must be linked
685 // equivalently to rustc.
686 .env("RUSTDOC_LIBDIR", self.rustc_libdir(compiler))
687 .env("CFG_RELEASE_CHANNEL", &self.config.channel)
688 .env("RUSTDOC_REAL", self.rustdoc(compiler))
689 .env("RUSTDOC_CRATE_VERSION", self.rust_version())
690 .env("RUSTC_BOOTSTRAP", "1");
692 // Remove make-related flags that can cause jobserver problems.
693 cmd.env_remove("MAKEFLAGS");
694 cmd.env_remove("MFLAGS");
696 if let Some(linker) = self.linker(compiler.host) {
697 cmd.env("RUSTC_TARGET_LINKER", linker);
702 /// Prepares an invocation of `cargo` to be run.
704 /// This will create a `Command` that represents a pending execution of
705 /// Cargo. This cargo will be configured to use `compiler` as the actual
706 /// rustc compiler, its output will be scoped by `mode`'s output directory,
707 /// it will pass the `--target` flag for the specified `target`, and will be
708 /// executing the Cargo command `cmd`.
713 target: Interned<String>,
716 let mut cargo = Command::new(&self.initial_cargo);
717 let out_dir = self.stage_out(compiler, mode);
719 if cmd == "doc" || cmd == "rustdoc" {
720 let my_out = match mode {
721 // This is the intended out directory for compiler documentation.
722 Mode::Rustc | Mode::ToolRustc | Mode::Codegen => self.compiler_doc_out(target),
723 _ => self.crate_doc_out(target),
725 let rustdoc = self.rustdoc(compiler);
726 self.clear_if_dirty(&my_out, &rustdoc);
729 cargo.env("CARGO_TARGET_DIR", &out_dir).arg(cmd).arg("-Zconfig-profile");
731 let profile_var = |name: &str| {
732 let profile = if self.config.rust_optimize { "RELEASE" } else { "DEV" };
733 format!("CARGO_PROFILE_{}_{}", profile, name)
736 // See comment in librustc_llvm/build.rs for why this is necessary, largely llvm-config
737 // needs to not accidentally link to libLLVM in stage0/lib.
738 cargo.env("REAL_LIBRARY_PATH_VAR", &util::dylib_path_var());
739 if let Some(e) = env::var_os(util::dylib_path_var()) {
740 cargo.env("REAL_LIBRARY_PATH", e);
743 if cmd != "install" {
744 cargo.arg("--target").arg(target);
746 assert_eq!(target, compiler.host);
749 // Set a flag for `check`/`clippy`/`fix`, so that certain build
750 // scripts can do less work (e.g. not building/requiring LLVM).
751 if cmd == "check" || cmd == "clippy" || cmd == "fix" {
752 cargo.env("RUST_CHECK", "1");
756 if compiler.stage == 0 && self.local_rebuild {
757 // Assume the local-rebuild rustc already has stage1 features.
760 stage = compiler.stage;
763 let mut rustflags = Rustflags::new(&target);
765 if let Ok(s) = env::var("CARGOFLAGS_NOT_BOOTSTRAP") {
766 cargo.args(s.split_whitespace());
768 rustflags.env("RUSTFLAGS_NOT_BOOTSTRAP");
770 if let Ok(s) = env::var("CARGOFLAGS_BOOTSTRAP") {
771 cargo.args(s.split_whitespace());
773 rustflags.env("RUSTFLAGS_BOOTSTRAP");
774 rustflags.arg("--cfg=bootstrap");
777 if let Ok(s) = env::var("CARGOFLAGS") {
778 cargo.args(s.split_whitespace());
782 Mode::Std | Mode::ToolBootstrap | Mode::ToolStd => {}
783 Mode::Rustc | Mode::Codegen | Mode::ToolRustc => {
784 // Build proc macros both for the host and the target
785 if target != compiler.host && cmd != "check" {
786 cargo.arg("-Zdual-proc-macros");
787 rustflags.arg("-Zdual-proc-macros");
792 // This tells Cargo (and in turn, rustc) to output more complete
793 // dependency information. Most importantly for rustbuild, this
794 // includes sysroot artifacts, like libstd, which means that we don't
795 // need to track those in rustbuild (an error prone process!). This
796 // feature is currently unstable as there may be some bugs and such, but
797 // it represents a big improvement in rustbuild's reliability on
798 // rebuilds, so we're using it here.
800 // For some additional context, see #63470 (the PR originally adding
801 // this), as well as #63012 which is the tracking issue for this
802 // feature on the rustc side.
803 cargo.arg("-Zbinary-dep-depinfo");
805 cargo.arg("-j").arg(self.jobs().to_string());
806 // Remove make-related flags to ensure Cargo can correctly set things up
807 cargo.env_remove("MAKEFLAGS");
808 cargo.env_remove("MFLAGS");
810 // FIXME: Temporary fix for https://github.com/rust-lang/cargo/issues/3005
811 // Force cargo to output binaries with disambiguating hashes in the name
812 let mut metadata = if compiler.stage == 0 {
813 // Treat stage0 like a special channel, whether it's a normal prior-
814 // release rustc or a local rebuild with the same version, so we
815 // never mix these libraries by accident.
816 "bootstrap".to_string()
818 self.config.channel.to_string()
820 // We want to make sure that none of the dependencies between
821 // std/test/rustc unify with one another. This is done for weird linkage
822 // reasons but the gist of the problem is that if librustc, libtest, and
823 // libstd all depend on libc from crates.io (which they actually do) we
824 // want to make sure they all get distinct versions. Things get really
825 // weird if we try to unify all these dependencies right now, namely
826 // around how many times the library is linked in dynamic libraries and
827 // such. If rustc were a static executable or if we didn't ship dylibs
828 // this wouldn't be a problem, but we do, so it is. This is in general
829 // just here to make sure things build right. If you can remove this and
830 // things still build right, please do!
832 Mode::Std => metadata.push_str("std"),
833 // When we're building rustc tools, they're built with a search path
834 // that contains things built during the rustc build. For example,
835 // bitflags is built during the rustc build, and is a dependency of
836 // rustdoc as well. We're building rustdoc in a different target
837 // directory, though, which means that Cargo will rebuild the
838 // dependency. When we go on to build rustdoc, we'll look for
839 // bitflags, and find two different copies: one built during the
840 // rustc step and one that we just built. This isn't always a
841 // problem, somehow -- not really clear why -- but we know that this
843 Mode::ToolRustc => metadata.push_str("tool-rustc"),
846 cargo.env("__CARGO_DEFAULT_LIB_METADATA", &metadata);
849 rustflags.arg("-Zforce-unstable-if-unmarked");
852 rustflags.arg("-Zexternal-macro-backtrace");
854 let want_rustdoc = self.doc_tests != DocTests::No;
856 // We synthetically interpret a stage0 compiler used to build tools as a
857 // "raw" compiler in that it's the exact snapshot we download. Normally
858 // the stage0 build means it uses libraries build by the stage0
859 // compiler, but for tools we just use the precompiled libraries that
861 let use_snapshot = mode == Mode::ToolBootstrap;
862 assert!(!use_snapshot || stage == 0 || self.local_rebuild);
864 let maybe_sysroot = self.sysroot(compiler);
865 let sysroot = if use_snapshot { self.rustc_snapshot_sysroot() } else { &maybe_sysroot };
866 let libdir = self.rustc_libdir(compiler);
868 // Clear the output directory if the real rustc we're using has changed;
869 // Cargo cannot detect this as it thinks rustc is bootstrap/debug/rustc.
871 // Avoid doing this during dry run as that usually means the relevant
872 // compiler is not yet linked/copied properly.
874 // Only clear out the directory if we're compiling std; otherwise, we
875 // should let Cargo take care of things for us (via depdep info)
876 if !self.config.dry_run && mode == Mode::ToolStd && cmd == "build" {
877 self.clear_if_dirty(&out_dir, &self.rustc(compiler));
880 // Customize the compiler we're running. Specify the compiler to cargo
881 // as our shim and then pass it some various options used to configure
882 // how the actual compiler itself is called.
884 // These variables are primarily all read by
885 // src/bootstrap/bin/{rustc.rs,rustdoc.rs}
887 .env("RUSTBUILD_NATIVE_DIR", self.native_dir(target))
888 .env("RUSTC", self.out.join("bootstrap/debug/rustc"))
889 .env("RUSTC_REAL", self.rustc(compiler))
890 .env("RUSTC_STAGE", stage.to_string())
891 .env("RUSTC_DEBUG_ASSERTIONS", self.config.rust_debug_assertions.to_string())
892 .env("RUSTC_SYSROOT", &sysroot)
893 .env("RUSTC_LIBDIR", &libdir)
894 .env("RUSTDOC", self.out.join("bootstrap/debug/rustdoc"))
897 if cmd == "doc" || cmd == "rustdoc" || (cmd == "test" && want_rustdoc) {
898 self.rustdoc(compiler)
900 PathBuf::from("/path/to/nowhere/rustdoc/not/required")
903 .env("RUSTC_ERROR_METADATA_DST", self.extended_error_dir())
904 .env("RUSTC_BREAK_ON_ICE", "1");
906 // Dealing with rpath here is a little special, so let's go into some
907 // detail. First off, `-rpath` is a linker option on Unix platforms
908 // which adds to the runtime dynamic loader path when looking for
909 // dynamic libraries. We use this by default on Unix platforms to ensure
910 // that our nightlies behave the same on Windows, that is they work out
911 // of the box. This can be disabled, of course, but basically that's why
912 // we're gated on RUSTC_RPATH here.
914 // Ok, so the astute might be wondering "why isn't `-C rpath` used
915 // here?" and that is indeed a good question to task. This codegen
916 // option is the compiler's current interface to generating an rpath.
917 // Unfortunately it doesn't quite suffice for us. The flag currently
918 // takes no value as an argument, so the compiler calculates what it
919 // should pass to the linker as `-rpath`. This unfortunately is based on
920 // the **compile time** directory structure which when building with
921 // Cargo will be very different than the runtime directory structure.
923 // All that's a really long winded way of saying that if we use
924 // `-Crpath` then the executables generated have the wrong rpath of
925 // something like `$ORIGIN/deps` when in fact the way we distribute
926 // rustc requires the rpath to be `$ORIGIN/../lib`.
928 // So, all in all, to set up the correct rpath we pass the linker
929 // argument manually via `-C link-args=-Wl,-rpath,...`. Plus isn't it
930 // fun to pass a flag to a tool to pass a flag to pass a flag to a tool
931 // to change a flag in a binary?
932 if self.config.rust_rpath && util::use_host_linker(&target) {
933 let rpath = if target.contains("apple") {
934 // Note that we need to take one extra step on macOS to also pass
935 // `-Wl,-instal_name,@rpath/...` to get things to work right. To
936 // do that we pass a weird flag to the compiler to get it to do
937 // so. Note that this is definitely a hack, and we should likely
938 // flesh out rpath support more fully in the future.
939 rustflags.arg("-Zosx-rpath-install-name");
940 Some("-Wl,-rpath,@loader_path/../lib")
941 } else if !target.contains("windows") {
942 Some("-Wl,-rpath,$ORIGIN/../lib")
946 if let Some(rpath) = rpath {
947 rustflags.arg(&format!("-Clink-args={}", rpath));
951 if let Some(host_linker) = self.linker(compiler.host) {
952 cargo.env("RUSTC_HOST_LINKER", host_linker);
954 if let Some(target_linker) = self.linker(target) {
955 let target = crate::envify(&target);
956 cargo.env(&format!("CARGO_TARGET_{}_LINKER", target), target_linker);
958 if !(["build", "check", "clippy", "fix", "rustc"].contains(&cmd)) && want_rustdoc {
959 cargo.env("RUSTDOC_LIBDIR", self.rustc_libdir(compiler));
962 let debuginfo_level = match mode {
963 Mode::Rustc | Mode::Codegen => self.config.rust_debuginfo_level_rustc,
964 Mode::Std => self.config.rust_debuginfo_level_std,
965 Mode::ToolBootstrap | Mode::ToolStd | Mode::ToolRustc => {
966 self.config.rust_debuginfo_level_tools
969 cargo.env(profile_var("DEBUG"), debuginfo_level.to_string());
972 cargo.env("RUSTC_FORCE_UNSTABLE", "1");
975 if let Some(x) = self.crt_static(target) {
977 rustflags.arg("-Ctarget-feature=+crt-static");
979 rustflags.arg("-Ctarget-feature=-crt-static");
983 if let Some(x) = self.crt_static(compiler.host) {
984 cargo.env("RUSTC_HOST_CRT_STATIC", x.to_string());
987 if let Some(map) = self.build.debuginfo_map(GitRepo::Rustc) {
988 cargo.env("RUSTC_DEBUGINFO_MAP", map);
991 // Enable usage of unstable features
992 cargo.env("RUSTC_BOOTSTRAP", "1");
993 self.add_rust_test_threads(&mut cargo);
995 // Almost all of the crates that we compile as part of the bootstrap may
996 // have a build script, including the standard library. To compile a
997 // build script, however, it itself needs a standard library! This
998 // introduces a bit of a pickle when we're compiling the standard
1001 // To work around this we actually end up using the snapshot compiler
1002 // (stage0) for compiling build scripts of the standard library itself.
1003 // The stage0 compiler is guaranteed to have a libstd available for use.
1005 // For other crates, however, we know that we've already got a standard
1006 // library up and running, so we can use the normal compiler to compile
1007 // build scripts in that situation.
1008 if mode == Mode::Std {
1010 .env("RUSTC_SNAPSHOT", &self.initial_rustc)
1011 .env("RUSTC_SNAPSHOT_LIBDIR", self.rustc_snapshot_libdir());
1014 .env("RUSTC_SNAPSHOT", self.rustc(compiler))
1015 .env("RUSTC_SNAPSHOT_LIBDIR", self.rustc_libdir(compiler));
1018 if self.config.incremental {
1019 cargo.env("CARGO_INCREMENTAL", "1");
1021 // Don't rely on any default setting for incr. comp. in Cargo
1022 cargo.env("CARGO_INCREMENTAL", "0");
1025 if let Some(ref on_fail) = self.config.on_fail {
1026 cargo.env("RUSTC_ON_FAIL", on_fail);
1029 if self.config.print_step_timings {
1030 cargo.env("RUSTC_PRINT_STEP_TIMINGS", "1");
1033 if self.config.backtrace_on_ice {
1034 cargo.env("RUSTC_BACKTRACE_ON_ICE", "1");
1037 cargo.env("RUSTC_VERBOSE", self.verbosity.to_string());
1039 if !mode.is_tool() {
1040 // When extending this list, add the new lints to the RUSTFLAGS of the
1041 // build_bootstrap function of src/bootstrap/bootstrap.py as well as
1042 // some code doesn't go through this `rustc` wrapper.
1043 rustflags.arg("-Wrust_2018_idioms");
1044 rustflags.arg("-Wunused_lifetimes");
1046 if self.config.deny_warnings {
1047 rustflags.arg("-Dwarnings");
1051 if let Mode::Rustc | Mode::Codegen = mode {
1052 rustflags.arg("-Zunstable-options");
1053 rustflags.arg("-Wrustc::internal");
1056 // Throughout the build Cargo can execute a number of build scripts
1057 // compiling C/C++ code and we need to pass compilers, archivers, flags, etc
1058 // obtained previously to those build scripts.
1059 // Build scripts use either the `cc` crate or `configure/make` so we pass
1060 // the options through environment variables that are fetched and understood by both.
1062 // FIXME: the guard against msvc shouldn't need to be here
1063 if target.contains("msvc") {
1064 if let Some(ref cl) = self.config.llvm_clang_cl {
1065 cargo.env("CC", cl).env("CXX", cl);
1068 let ccache = self.config.ccache.as_ref();
1069 let ccacheify = |s: &Path| {
1070 let ccache = match ccache {
1072 None => return s.display().to_string(),
1074 // FIXME: the cc-rs crate only recognizes the literal strings
1075 // `ccache` and `sccache` when doing caching compilations, so we
1076 // mirror that here. It should probably be fixed upstream to
1077 // accept a new env var or otherwise work with custom ccache
1080 "ccache" | "sccache" => format!("{} {}", ccache, s.display()),
1081 _ => s.display().to_string(),
1084 let cc = ccacheify(&self.cc(target));
1085 cargo.env(format!("CC_{}", target), &cc);
1087 let cflags = self.cflags(target, GitRepo::Rustc).join(" ");
1088 cargo.env(format!("CFLAGS_{}", target), cflags.clone());
1090 if let Some(ar) = self.ar(target) {
1091 let ranlib = format!("{} s", ar.display());
1092 cargo.env(format!("AR_{}", target), ar).env(format!("RANLIB_{}", target), ranlib);
1095 if let Ok(cxx) = self.cxx(target) {
1096 let cxx = ccacheify(&cxx);
1098 .env(format!("CXX_{}", target), &cxx)
1099 .env(format!("CXXFLAGS_{}", target), cflags);
1103 if mode == Mode::Std && self.config.extended && compiler.is_final_stage(self) {
1104 rustflags.arg("-Zsave-analysis");
1106 "RUST_SAVE_ANALYSIS_CONFIG",
1107 "{\"output_file\": null,\"full_docs\": false,\
1108 \"pub_only\": true,\"reachable_only\": false,\
1109 \"distro_crate\": true,\"signatures\": false,\"borrow_data\": false}",
1113 // For `cargo doc` invocations, make rustdoc print the Rust version into the docs
1114 cargo.env("RUSTDOC_CRATE_VERSION", self.rust_version());
1116 // Environment variables *required* throughout the build
1118 // FIXME: should update code to not require this env var
1119 cargo.env("CFG_COMPILER_HOST_TRIPLE", target);
1121 // Set this for all builds to make sure doc builds also get it.
1122 cargo.env("CFG_RELEASE_CHANNEL", &self.config.channel);
1124 // This one's a bit tricky. As of the time of this writing the compiler
1125 // links to the `winapi` crate on crates.io. This crate provides raw
1126 // bindings to Windows system functions, sort of like libc does for
1127 // Unix. This crate also, however, provides "import libraries" for the
1128 // MinGW targets. There's an import library per dll in the windows
1129 // distribution which is what's linked to. These custom import libraries
1130 // are used because the winapi crate can reference Windows functions not
1131 // present in the MinGW import libraries.
1133 // For example MinGW may ship libdbghelp.a, but it may not have
1134 // references to all the functions in the dbghelp dll. Instead the
1135 // custom import library for dbghelp in the winapi crates has all this
1138 // Unfortunately for us though the import libraries are linked by
1139 // default via `-ldylib=winapi_foo`. That is, they're linked with the
1140 // `dylib` type with a `winapi_` prefix (so the winapi ones don't
1141 // conflict with the system MinGW ones). This consequently means that
1142 // the binaries we ship of things like rustc_codegen_llvm (aka the rustc_codegen_llvm
1143 // DLL) when linked against *again*, for example with procedural macros
1144 // or plugins, will trigger the propagation logic of `-ldylib`, passing
1145 // `-lwinapi_foo` to the linker again. This isn't actually available in
1146 // our distribution, however, so the link fails.
1148 // To solve this problem we tell winapi to not use its bundled import
1149 // libraries. This means that it will link to the system MinGW import
1150 // libraries by default, and the `-ldylib=foo` directives will still get
1151 // passed to the final linker, but they'll look like `-lfoo` which can
1152 // be resolved because MinGW has the import library. The downside is we
1153 // don't get newer functions from Windows, but we don't use any of them
1155 if !mode.is_tool() {
1156 cargo.env("WINAPI_NO_BUNDLED_LIBRARIES", "1");
1159 for _ in 1..self.verbosity {
1163 match (mode, self.config.rust_codegen_units_std, self.config.rust_codegen_units) {
1164 (Mode::Std, Some(n), _) | (_, _, Some(n)) => {
1165 cargo.env(profile_var("CODEGEN_UNITS"), n.to_string());
1168 // Don't set anything
1172 if self.config.rust_optimize {
1173 // FIXME: cargo bench/install do not accept `--release`
1174 if cmd != "bench" && cmd != "install" {
1175 cargo.arg("--release");
1179 if self.config.locked_deps {
1180 cargo.arg("--locked");
1182 if self.config.vendor || self.is_sudo {
1183 cargo.arg("--frozen");
1186 // Try to use a sysroot-relative bindir, in case it was configured absolutely.
1187 cargo.env("RUSTC_INSTALL_BINDIR", self.config.bindir_relative());
1189 self.ci_env.force_coloring_in_ci(&mut cargo);
1191 // When we build Rust dylibs they're all intended for intermediate
1192 // usage, so make sure we pass the -Cprefer-dynamic flag instead of
1193 // linking all deps statically into the dylib.
1194 if let Mode::Std | Mode::Rustc | Mode::Codegen = mode {
1195 rustflags.arg("-Cprefer-dynamic");
1198 // When building incrementally we default to a lower ThinLTO import limit
1199 // (unless explicitly specified otherwise). This will produce a somewhat
1200 // slower code but give way better compile times.
1202 let limit = match self.config.rust_thin_lto_import_instr_limit {
1203 Some(limit) => Some(limit),
1204 None if self.config.incremental => Some(10),
1208 if let Some(limit) = limit {
1209 rustflags.arg(&format!("-Cllvm-args=-import-instr-limit={}", limit));
1213 Cargo { command: cargo, rustflags }
1216 /// Ensure that a given step is built, returning its output. This will
1217 /// cache the step, so it is safe (and good!) to call this as often as
1218 /// needed to ensure that all dependencies are built.
1219 pub fn ensure<S: Step>(&'a self, step: S) -> S::Output {
1221 let mut stack = self.stack.borrow_mut();
1222 for stack_step in stack.iter() {
1224 if stack_step.downcast_ref::<S>().map_or(true, |stack_step| *stack_step != step) {
1227 let mut out = String::new();
1228 out += &format!("\n\nCycle in build detected when adding {:?}\n", step);
1229 for el in stack.iter().rev() {
1230 out += &format!("\t{:?}\n", el);
1234 if let Some(out) = self.cache.get(&step) {
1235 self.verbose(&format!("{}c {:?}", " ".repeat(stack.len()), step));
1239 self.verbose(&format!("{}> {:?}", " ".repeat(stack.len()), step));
1240 stack.push(Box::new(step.clone()));
1244 let start = Instant::now();
1245 let zero = Duration::new(0, 0);
1246 let parent = self.time_spent_on_dependencies.replace(zero);
1247 let out = step.clone().run(self);
1248 let dur = start.elapsed();
1249 let deps = self.time_spent_on_dependencies.replace(parent + dur);
1253 if self.config.print_step_timings && dur > Duration::from_millis(100) {
1255 "[TIMING] {:?} -- {}.{:03}",
1258 dur.subsec_nanos() / 1_000_000
1263 let mut stack = self.stack.borrow_mut();
1264 let cur_step = stack.pop().expect("step stack empty");
1265 assert_eq!(cur_step.downcast_ref(), Some(&step));
1267 self.verbose(&format!("{}< {:?}", " ".repeat(self.stack.borrow().len()), step));
1268 self.cache.put(step, out.clone());
1277 struct Rustflags(String);
1280 fn new(target: &str) -> Rustflags {
1281 let mut ret = Rustflags(String::new());
1283 // Inherit `RUSTFLAGS` by default ...
1284 ret.env("RUSTFLAGS");
1286 // ... and also handle target-specific env RUSTFLAGS if they're
1288 let target_specific = format!("CARGO_TARGET_{}_RUSTFLAGS", crate::envify(target));
1289 ret.env(&target_specific);
1294 fn env(&mut self, env: &str) {
1295 if let Ok(s) = env::var(env) {
1296 for part in s.split_whitespace() {
1302 fn arg(&mut self, arg: &str) -> &mut Self {
1303 assert_eq!(arg.split_whitespace().count(), 1);
1304 if self.0.len() > 0 {
1305 self.0.push_str(" ");
1307 self.0.push_str(arg);
1315 rustflags: Rustflags,
1319 pub fn rustflag(&mut self, arg: &str) -> &mut Cargo {
1320 self.rustflags.arg(arg);
1324 pub fn arg(&mut self, arg: impl AsRef<OsStr>) -> &mut Cargo {
1325 self.command.arg(arg.as_ref());
1329 pub fn args<I, S>(&mut self, args: I) -> &mut Cargo
1331 I: IntoIterator<Item = S>,
1335 self.arg(arg.as_ref());
1340 pub fn env(&mut self, key: impl AsRef<OsStr>, value: impl AsRef<OsStr>) -> &mut Cargo {
1341 self.command.env(key.as_ref(), value.as_ref());
1346 impl From<Cargo> for Command {
1347 fn from(mut cargo: Cargo) -> Command {
1348 cargo.command.env("RUSTFLAGS", &cargo.rustflags.0);