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, Mode, GitRepo};
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
128 .unwrap_or(&builder.build.src)
130 PathSet::Suite(path) => PathBuf::from(path),
135 impl StepDescription {
136 fn from<S: Step>() -> StepDescription {
139 only_hosts: S::ONLY_HOSTS,
140 should_run: S::should_run,
141 make_run: S::make_run,
142 name: std::any::type_name::<S>(),
146 fn maybe_run(&self, builder: &Builder<'_>, pathset: &PathSet) {
147 if builder.config.exclude.iter().any(|e| pathset.has(e)) {
148 eprintln!("Skipping {:?} because it is excluded", pathset);
150 } else if !builder.config.exclude.is_empty() {
152 "{:?} not skipped for {:?} -- not in {:?}",
153 pathset, self.name, builder.config.exclude
156 let hosts = &builder.hosts;
158 // Determine the targets participating in this rule.
159 let targets = if self.only_hosts {
160 if builder.config.skip_only_host_steps {
161 return; // don't run anything
170 for target in targets {
171 let run = RunConfig {
173 path: pathset.path(builder),
177 (self.make_run)(run);
182 fn run(v: &[StepDescription], builder: &Builder<'_>, paths: &[PathBuf]) {
185 .map(|desc| (desc.should_run)(ShouldRun::new(builder)))
186 .collect::<Vec<_>>();
188 // sanity checks on rules
189 for (desc, should_run) in v.iter().zip(&should_runs) {
191 !should_run.paths.is_empty(),
192 "{:?} should have at least one pathset",
197 if paths.is_empty() {
198 for (desc, should_run) in v.iter().zip(should_runs) {
199 if desc.default && should_run.is_really_default {
200 for pathset in &should_run.paths {
201 desc.maybe_run(builder, pathset);
207 // strip CurDir prefix if present
208 let path = match path.strip_prefix(".") {
213 let mut attempted_run = false;
214 for (desc, should_run) in v.iter().zip(&should_runs) {
215 if let Some(suite) = should_run.is_suite_path(path) {
216 attempted_run = true;
217 desc.maybe_run(builder, suite);
218 } else if let Some(pathset) = should_run.pathset_for_path(path) {
219 attempted_run = true;
220 desc.maybe_run(builder, pathset);
225 panic!("Error: no rules matched {}.", path.display());
233 pub struct ShouldRun<'a> {
234 pub builder: &'a Builder<'a>,
235 // use a BTreeSet to maintain sort order
236 paths: BTreeSet<PathSet>,
238 // If this is a default rule, this is an additional constraint placed on
239 // its run. Generally something like compiler docs being enabled.
240 is_really_default: bool,
243 impl<'a> ShouldRun<'a> {
244 fn new(builder: &'a Builder<'_>) -> ShouldRun<'a> {
247 paths: BTreeSet::new(),
248 is_really_default: true, // by default no additional conditions
252 pub fn default_condition(mut self, cond: bool) -> Self {
253 self.is_really_default = cond;
257 // Unlike `krate` this will create just one pathset. As such, it probably shouldn't actually
258 // ever be used, but as we transition to having all rules properly handle passing krate(...) by
259 // actually doing something different for every crate passed.
260 pub fn all_krates(mut self, name: &str) -> Self {
261 let mut set = BTreeSet::new();
262 for krate in self.builder.in_tree_crates(name) {
263 set.insert(PathBuf::from(&krate.path));
265 self.paths.insert(PathSet::Set(set));
269 pub fn krate(mut self, name: &str) -> Self {
270 for krate in self.builder.in_tree_crates(name) {
271 self.paths.insert(PathSet::one(&krate.path));
276 // single, non-aliased path
277 pub fn path(self, path: &str) -> Self {
281 // multiple aliases for the same job
282 pub fn paths(mut self, paths: &[&str]) -> Self {
284 .insert(PathSet::Set(paths.iter().map(PathBuf::from).collect()));
288 pub fn is_suite_path(&self, path: &Path) -> Option<&PathSet> {
289 self.paths.iter().find(|pathset| match pathset {
290 PathSet::Suite(p) => path.starts_with(p),
291 PathSet::Set(_) => false,
295 pub fn suite_path(mut self, suite: &str) -> Self {
296 self.paths.insert(PathSet::Suite(PathBuf::from(suite)));
300 // allows being more explicit about why should_run in Step returns the value passed to it
301 pub fn never(mut self) -> ShouldRun<'a> {
302 self.paths.insert(PathSet::empty());
306 fn pathset_for_path(&self, path: &Path) -> Option<&PathSet> {
307 self.paths.iter().find(|pathset| pathset.has(path))
311 #[derive(Copy, Clone, PartialEq, Eq, Debug)]
325 impl<'a> Builder<'a> {
326 fn get_step_descriptions(kind: Kind) -> Vec<StepDescription> {
327 macro_rules! describe {
328 ($($rule:ty),+ $(,)?) => {{
329 vec![$(StepDescription::from::<$rule>()),+]
333 Kind::Build => describe!(
336 compile::StartupObjects,
340 tool::UnstableBookGen,
345 tool::RemoteTestServer,
346 tool::RemoteTestClient,
357 Kind::Check | Kind::Clippy | Kind::Fix | Kind::Format => describe!(
362 Kind::Test => describe!(
363 crate::toolstate::ToolStateCheck,
368 test::RunPassValgrind,
379 test::RunPassValgrindPretty,
389 test::RunMakeFullDeps,
403 test::CompiletestTest,
405 test::RustdocJSNotStd,
408 // Run bootstrap close to the end as it's unlikely to fail
410 // Run run-make last, since these won't pass without make on Windows
413 Kind::Bench => describe!(test::Crate, test::CrateLibrustc),
414 Kind::Doc => describe!(
416 doc::UnstableBookGen,
432 Kind::Dist => describe!(
437 dist::DebuggerScripts,
442 dist::PlainSourceTarball,
453 Kind::Install => describe!(
468 pub fn get_help(build: &Build, subcommand: &str) -> Option<String> {
469 let kind = match subcommand {
470 "build" => Kind::Build,
472 "test" => Kind::Test,
473 "bench" => Kind::Bench,
474 "dist" => Kind::Dist,
475 "install" => Kind::Install,
479 let builder = Builder {
481 top_stage: build.config.stage.unwrap_or(2),
484 stack: RefCell::new(Vec::new()),
485 time_spent_on_dependencies: Cell::new(Duration::new(0, 0)),
489 let builder = &builder;
490 let mut should_run = ShouldRun::new(builder);
491 for desc in Builder::get_step_descriptions(builder.kind) {
492 should_run = (desc.should_run)(should_run);
494 let mut help = String::from("Available paths:\n");
495 for pathset in should_run.paths {
496 if let PathSet::Set(set) = pathset {
497 set.iter().for_each(|path| {
499 format!(" ./x.py {} {}\n", subcommand, path.display()).as_str(),
507 pub fn new(build: &Build) -> Builder<'_> {
508 let (kind, paths) = match build.config.cmd {
509 Subcommand::Build { ref paths } => (Kind::Build, &paths[..]),
510 Subcommand::Check { ref paths } => (Kind::Check, &paths[..]),
511 Subcommand::Clippy { ref paths } => (Kind::Clippy, &paths[..]),
512 Subcommand::Fix { ref paths } => (Kind::Fix, &paths[..]),
513 Subcommand::Doc { ref paths } => (Kind::Doc, &paths[..]),
514 Subcommand::Test { ref paths, .. } => (Kind::Test, &paths[..]),
515 Subcommand::Bench { ref paths, .. } => (Kind::Bench, &paths[..]),
516 Subcommand::Dist { ref paths } => (Kind::Dist, &paths[..]),
517 Subcommand::Install { ref paths } => (Kind::Install, &paths[..]),
518 Subcommand::Format { .. } | Subcommand::Clean { .. } => panic!(),
521 let builder = Builder {
523 top_stage: build.config.stage.unwrap_or(2),
526 stack: RefCell::new(Vec::new()),
527 time_spent_on_dependencies: Cell::new(Duration::new(0, 0)),
528 paths: paths.to_owned(),
534 pub fn execute_cli(&self) {
535 self.run_step_descriptions(&Builder::get_step_descriptions(self.kind), &self.paths);
538 pub fn default_doc(&self, paths: Option<&[PathBuf]>) {
539 let paths = paths.unwrap_or(&[]);
540 self.run_step_descriptions(&Builder::get_step_descriptions(Kind::Doc), paths);
543 fn run_step_descriptions(&self, v: &[StepDescription], paths: &[PathBuf]) {
544 StepDescription::run(v, self, paths);
547 /// Obtain a compiler at a given stage and for a given host. Explicitly does
548 /// not take `Compiler` since all `Compiler` instances are meant to be
549 /// obtained through this function, since it ensures that they are valid
550 /// (i.e., built and assembled).
551 pub fn compiler(&self, stage: u32, host: Interned<String>) -> Compiler {
552 self.ensure(compile::Assemble {
553 target_compiler: Compiler { stage, host },
557 /// Similar to `compiler`, except handles the full-bootstrap option to
558 /// silently use the stage1 compiler instead of a stage2 compiler if one is
561 /// Note that this does *not* have the side effect of creating
562 /// `compiler(stage, host)`, unlike `compiler` above which does have such
563 /// a side effect. The returned compiler here can only be used to compile
564 /// new artifacts, it can't be used to rely on the presence of a particular
567 /// See `force_use_stage1` for documentation on what each argument is.
571 host: Interned<String>,
572 target: Interned<String>,
574 if self.build.force_use_stage1(Compiler { stage, host }, target) {
575 self.compiler(1, self.config.build)
577 self.compiler(stage, host)
581 pub fn sysroot(&self, compiler: Compiler) -> Interned<PathBuf> {
582 self.ensure(compile::Sysroot { compiler })
585 /// Returns the libdir where the standard library and other artifacts are
586 /// found for a compiler's sysroot.
587 pub fn sysroot_libdir(
590 target: Interned<String>,
591 ) -> Interned<PathBuf> {
592 #[derive(Debug, Copy, Clone, Hash, PartialEq, Eq)]
595 target: Interned<String>,
597 impl Step for Libdir {
598 type Output = Interned<PathBuf>;
600 fn should_run(run: ShouldRun<'_>) -> ShouldRun<'_> {
604 fn run(self, builder: &Builder<'_>) -> Interned<PathBuf> {
605 let lib = builder.sysroot_libdir_relative(self.compiler);
606 let sysroot = builder
607 .sysroot(self.compiler)
612 let _ = fs::remove_dir_all(&sysroot);
613 t!(fs::create_dir_all(&sysroot));
614 INTERNER.intern_path(sysroot)
617 self.ensure(Libdir { compiler, target })
620 /// Returns the compiler's libdir where it stores the dynamic libraries that
621 /// it itself links against.
623 /// For example this returns `<sysroot>/lib` on Unix and `<sysroot>/bin` on
625 pub fn rustc_libdir(&self, compiler: Compiler) -> PathBuf {
626 if compiler.is_snapshot(self) {
627 self.rustc_snapshot_libdir()
629 match self.config.libdir_relative() {
630 Some(relative_libdir) if compiler.stage >= 1
631 => self.sysroot(compiler).join(relative_libdir),
632 _ => self.sysroot(compiler).join(libdir(&compiler.host))
637 /// Returns the compiler's relative libdir where it stores the dynamic libraries that
638 /// it itself links against.
640 /// For example this returns `lib` on Unix and `bin` on
642 pub fn libdir_relative(&self, compiler: Compiler) -> &Path {
643 if compiler.is_snapshot(self) {
644 libdir(&self.config.build).as_ref()
646 match self.config.libdir_relative() {
647 Some(relative_libdir) if compiler.stage >= 1
649 _ => libdir(&compiler.host).as_ref()
654 /// Returns the compiler's relative libdir where the standard library and other artifacts are
655 /// found for a compiler's sysroot.
657 /// For example this returns `lib` on Unix and Windows.
658 pub fn sysroot_libdir_relative(&self, compiler: Compiler) -> &Path {
659 match self.config.libdir_relative() {
660 Some(relative_libdir) if compiler.stage >= 1
662 _ => Path::new("lib")
666 /// Adds the compiler's directory of dynamic libraries to `cmd`'s dynamic
667 /// library lookup path.
668 pub fn add_rustc_lib_path(&self, compiler: Compiler, cmd: &mut Cargo) {
669 // Windows doesn't need dylib path munging because the dlls for the
670 // compiler live next to the compiler and the system will find them
676 add_lib_path(vec![self.rustc_libdir(compiler)], &mut cmd.command);
679 /// Gets a path to the compiler specified.
680 pub fn rustc(&self, compiler: Compiler) -> PathBuf {
681 if compiler.is_snapshot(self) {
682 self.initial_rustc.clone()
684 self.sysroot(compiler)
686 .join(exe("rustc", &compiler.host))
690 pub fn rustdoc(&self, compiler: Compiler) -> PathBuf {
691 self.ensure(tool::Rustdoc { compiler })
694 pub fn rustdoc_cmd(&self, compiler: Compiler) -> Command {
695 let mut cmd = Command::new(&self.out.join("bootstrap/debug/rustdoc"));
696 cmd.env("RUSTC_STAGE", compiler.stage.to_string())
697 .env("RUSTC_SYSROOT", self.sysroot(compiler))
698 // Note that this is *not* the sysroot_libdir because rustdoc must be linked
699 // equivalently to rustc.
700 .env("RUSTDOC_LIBDIR", self.rustc_libdir(compiler))
701 .env("CFG_RELEASE_CHANNEL", &self.config.channel)
702 .env("RUSTDOC_REAL", self.rustdoc(compiler))
703 .env("RUSTDOC_CRATE_VERSION", self.rust_version())
704 .env("RUSTC_BOOTSTRAP", "1");
706 // Remove make-related flags that can cause jobserver problems.
707 cmd.env_remove("MAKEFLAGS");
708 cmd.env_remove("MFLAGS");
710 if let Some(linker) = self.linker(compiler.host) {
711 cmd.env("RUSTC_TARGET_LINKER", linker);
716 /// Prepares an invocation of `cargo` to be run.
718 /// This will create a `Command` that represents a pending execution of
719 /// Cargo. This cargo will be configured to use `compiler` as the actual
720 /// rustc compiler, its output will be scoped by `mode`'s output directory,
721 /// it will pass the `--target` flag for the specified `target`, and will be
722 /// executing the Cargo command `cmd`.
727 target: Interned<String>,
730 let mut cargo = Command::new(&self.initial_cargo);
731 let out_dir = self.stage_out(compiler, mode);
733 if cmd == "doc" || cmd == "rustdoc" {
734 let my_out = match mode {
735 // This is the intended out directory for compiler documentation.
736 Mode::Rustc | Mode::ToolRustc | Mode::Codegen => self.compiler_doc_out(target),
737 _ => self.crate_doc_out(target),
739 let rustdoc = self.rustdoc(compiler);
740 self.clear_if_dirty(&my_out, &rustdoc);
744 .env("CARGO_TARGET_DIR", out_dir)
746 .arg("-Zconfig-profile");
748 let profile_var = |name: &str| {
749 let profile = if self.config.rust_optimize {
754 format!("CARGO_PROFILE_{}_{}", profile, name)
757 // See comment in librustc_llvm/build.rs for why this is necessary, largely llvm-config
758 // needs to not accidentally link to libLLVM in stage0/lib.
759 cargo.env("REAL_LIBRARY_PATH_VAR", &util::dylib_path_var());
760 if let Some(e) = env::var_os(util::dylib_path_var()) {
761 cargo.env("REAL_LIBRARY_PATH", e);
764 if cmd != "install" {
765 cargo.arg("--target")
768 assert_eq!(target, compiler.host);
771 // Set a flag for `check`/`clippy`/`fix`, so that certain build
772 // scripts can do less work (e.g. not building/requiring LLVM).
773 if cmd == "check" || cmd == "clippy" || cmd == "fix" {
774 cargo.env("RUST_CHECK", "1");
778 if compiler.stage == 0 && self.local_rebuild {
779 // Assume the local-rebuild rustc already has stage1 features.
782 stage = compiler.stage;
785 let mut rustflags = Rustflags::new(&target);
787 if let Ok(s) = env::var("CARGOFLAGS_NOT_BOOTSTRAP") {
788 cargo.args(s.split_whitespace());
790 rustflags.env("RUSTFLAGS_NOT_BOOTSTRAP");
792 if let Ok(s) = env::var("CARGOFLAGS_BOOTSTRAP") {
793 cargo.args(s.split_whitespace());
795 rustflags.env("RUSTFLAGS_BOOTSTRAP");
796 rustflags.arg("--cfg=bootstrap");
799 if let Ok(s) = env::var("CARGOFLAGS") {
800 cargo.args(s.split_whitespace());
804 Mode::Std | Mode::ToolBootstrap | Mode::ToolStd => {},
805 Mode::Rustc | Mode::Codegen | Mode::ToolRustc => {
806 // Build proc macros both for the host and the target
807 if target != compiler.host && cmd != "check" {
808 cargo.arg("-Zdual-proc-macros");
809 rustflags.arg("-Zdual-proc-macros");
814 // This tells Cargo (and in turn, rustc) to output more complete
815 // dependency information. Most importantly for rustbuild, this
816 // includes sysroot artifacts, like libstd, which means that we don't
817 // need to track those in rustbuild (an error prone process!). This
818 // feature is currently unstable as there may be some bugs and such, but
819 // it represents a big improvement in rustbuild's reliability on
820 // rebuilds, so we're using it here.
822 // For some additional context, see #63470 (the PR originally adding
823 // this), as well as #63012 which is the tracking issue for this
824 // feature on the rustc side.
825 cargo.arg("-Zbinary-dep-depinfo");
827 cargo.arg("-j").arg(self.jobs().to_string());
828 // Remove make-related flags to ensure Cargo can correctly set things up
829 cargo.env_remove("MAKEFLAGS");
830 cargo.env_remove("MFLAGS");
832 // FIXME: Temporary fix for https://github.com/rust-lang/cargo/issues/3005
833 // Force cargo to output binaries with disambiguating hashes in the name
834 let mut metadata = if compiler.stage == 0 {
835 // Treat stage0 like a special channel, whether it's a normal prior-
836 // release rustc or a local rebuild with the same version, so we
837 // never mix these libraries by accident.
838 "bootstrap".to_string()
840 self.config.channel.to_string()
842 // We want to make sure that none of the dependencies between
843 // std/test/rustc unify with one another. This is done for weird linkage
844 // reasons but the gist of the problem is that if librustc, libtest, and
845 // libstd all depend on libc from crates.io (which they actually do) we
846 // want to make sure they all get distinct versions. Things get really
847 // weird if we try to unify all these dependencies right now, namely
848 // around how many times the library is linked in dynamic libraries and
849 // such. If rustc were a static executable or if we didn't ship dylibs
850 // this wouldn't be a problem, but we do, so it is. This is in general
851 // just here to make sure things build right. If you can remove this and
852 // things still build right, please do!
854 Mode::Std => metadata.push_str("std"),
855 // When we're building rustc tools, they're built with a search path
856 // that contains things built during the rustc build. For example,
857 // bitflags is built during the rustc build, and is a dependency of
858 // rustdoc as well. We're building rustdoc in a different target
859 // directory, though, which means that Cargo will rebuild the
860 // dependency. When we go on to build rustdoc, we'll look for
861 // bitflags, and find two different copies: one built during the
862 // rustc step and one that we just built. This isn't always a
863 // problem, somehow -- not really clear why -- but we know that this
865 Mode::ToolRustc => metadata.push_str("tool-rustc"),
868 cargo.env("__CARGO_DEFAULT_LIB_METADATA", &metadata);
871 rustflags.arg("-Zforce-unstable-if-unmarked");
874 rustflags.arg("-Zexternal-macro-backtrace");
876 let want_rustdoc = self.doc_tests != DocTests::No;
878 // We synthetically interpret a stage0 compiler used to build tools as a
879 // "raw" compiler in that it's the exact snapshot we download. Normally
880 // the stage0 build means it uses libraries build by the stage0
881 // compiler, but for tools we just use the precompiled libraries that
883 let use_snapshot = mode == Mode::ToolBootstrap;
884 assert!(!use_snapshot || stage == 0 || self.local_rebuild);
886 let maybe_sysroot = self.sysroot(compiler);
887 let sysroot = if use_snapshot {
888 self.rustc_snapshot_sysroot()
892 let libdir = self.rustc_libdir(compiler);
894 // Customize the compiler we're running. Specify the compiler to cargo
895 // as our shim and then pass it some various options used to configure
896 // how the actual compiler itself is called.
898 // These variables are primarily all read by
899 // src/bootstrap/bin/{rustc.rs,rustdoc.rs}
901 .env("RUSTBUILD_NATIVE_DIR", self.native_dir(target))
902 .env("RUSTC", self.out.join("bootstrap/debug/rustc"))
903 .env("RUSTC_REAL", self.rustc(compiler))
904 .env("RUSTC_STAGE", stage.to_string())
906 "RUSTC_DEBUG_ASSERTIONS",
907 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") {
952 // Note that we need to take one extra step on macOS to also pass
953 // `-Wl,-instal_name,@rpath/...` to get things to work right. To
954 // do that we pass a weird flag to the compiler to get it to do
955 // so. Note that this is definitely a hack, and we should likely
956 // flesh out rpath support more fully in the future.
957 rustflags.arg("-Zosx-rpath-install-name");
958 Some("-Wl,-rpath,@loader_path/../lib")
959 } else if !target.contains("windows") {
960 Some("-Wl,-rpath,$ORIGIN/../lib")
964 if let Some(rpath) = rpath {
965 rustflags.arg(&format!("-Clink-args={}", rpath));
969 if let Some(host_linker) = self.linker(compiler.host) {
970 cargo.env("RUSTC_HOST_LINKER", host_linker);
972 if let Some(target_linker) = self.linker(target) {
973 let target = crate::envify(&target);
974 cargo.env(&format!("CARGO_TARGET_{}_LINKER", target), target_linker);
976 if !(["build", "check", "clippy", "fix", "rustc"].contains(&cmd)) && want_rustdoc {
977 cargo.env("RUSTDOC_LIBDIR", self.rustc_libdir(compiler));
980 let debuginfo_level = match mode {
981 Mode::Rustc | Mode::Codegen => self.config.rust_debuginfo_level_rustc,
982 Mode::Std => self.config.rust_debuginfo_level_std,
983 Mode::ToolBootstrap | Mode::ToolStd |
984 Mode::ToolRustc => self.config.rust_debuginfo_level_tools,
986 cargo.env(profile_var("DEBUG"), debuginfo_level.to_string());
989 cargo.env("RUSTC_FORCE_UNSTABLE", "1");
992 if let Some(x) = self.crt_static(target) {
994 rustflags.arg("-Ctarget-feature=+crt-static");
996 rustflags.arg("-Ctarget-feature=-crt-static");
1000 if let Some(x) = self.crt_static(compiler.host) {
1001 cargo.env("RUSTC_HOST_CRT_STATIC", x.to_string());
1004 if let Some(map) = self.build.debuginfo_map(GitRepo::Rustc) {
1005 cargo.env("RUSTC_DEBUGINFO_MAP", map);
1008 // Enable usage of unstable features
1009 cargo.env("RUSTC_BOOTSTRAP", "1");
1010 self.add_rust_test_threads(&mut cargo);
1012 // Almost all of the crates that we compile as part of the bootstrap may
1013 // have a build script, including the standard library. To compile a
1014 // build script, however, it itself needs a standard library! This
1015 // introduces a bit of a pickle when we're compiling the standard
1018 // To work around this we actually end up using the snapshot compiler
1019 // (stage0) for compiling build scripts of the standard library itself.
1020 // The stage0 compiler is guaranteed to have a libstd available for use.
1022 // For other crates, however, we know that we've already got a standard
1023 // library up and running, so we can use the normal compiler to compile
1024 // build scripts in that situation.
1025 if mode == Mode::Std {
1027 .env("RUSTC_SNAPSHOT", &self.initial_rustc)
1028 .env("RUSTC_SNAPSHOT_LIBDIR", self.rustc_snapshot_libdir());
1031 .env("RUSTC_SNAPSHOT", self.rustc(compiler))
1032 .env("RUSTC_SNAPSHOT_LIBDIR", self.rustc_libdir(compiler));
1035 if self.config.incremental {
1036 cargo.env("CARGO_INCREMENTAL", "1");
1038 // Don't rely on any default setting for incr. comp. in Cargo
1039 cargo.env("CARGO_INCREMENTAL", "0");
1042 if let Some(ref on_fail) = self.config.on_fail {
1043 cargo.env("RUSTC_ON_FAIL", on_fail);
1046 if self.config.print_step_timings {
1047 cargo.env("RUSTC_PRINT_STEP_TIMINGS", "1");
1050 if self.config.backtrace_on_ice {
1051 cargo.env("RUSTC_BACKTRACE_ON_ICE", "1");
1054 cargo.env("RUSTC_VERBOSE", self.verbosity.to_string());
1056 if !mode.is_tool() {
1057 // When extending this list, add the new lints to the RUSTFLAGS of the
1058 // build_bootstrap function of src/bootstrap/bootstrap.py as well as
1059 // some code doesn't go through this `rustc` wrapper.
1060 rustflags.arg("-Wrust_2018_idioms");
1061 rustflags.arg("-Wunused_lifetimes");
1063 if self.config.deny_warnings {
1064 rustflags.arg("-Dwarnings");
1068 if let Mode::Rustc | Mode::Codegen = mode {
1069 rustflags.arg("-Zunstable-options");
1070 rustflags.arg("-Wrustc::internal");
1073 // Throughout the build Cargo can execute a number of build scripts
1074 // compiling C/C++ code and we need to pass compilers, archivers, flags, etc
1075 // obtained previously to those build scripts.
1076 // Build scripts use either the `cc` crate or `configure/make` so we pass
1077 // the options through environment variables that are fetched and understood by both.
1079 // FIXME: the guard against msvc shouldn't need to be here
1080 if target.contains("msvc") {
1081 if let Some(ref cl) = self.config.llvm_clang_cl {
1082 cargo.env("CC", cl).env("CXX", cl);
1085 let ccache = self.config.ccache.as_ref();
1086 let ccacheify = |s: &Path| {
1087 let ccache = match ccache {
1089 None => return s.display().to_string(),
1091 // FIXME: the cc-rs crate only recognizes the literal strings
1092 // `ccache` and `sccache` when doing caching compilations, so we
1093 // mirror that here. It should probably be fixed upstream to
1094 // accept a new env var or otherwise work with custom ccache
1097 "ccache" | "sccache" => format!("{} {}", ccache, s.display()),
1098 _ => s.display().to_string(),
1101 let cc = ccacheify(&self.cc(target));
1102 cargo.env(format!("CC_{}", target), &cc);
1104 let cflags = self.cflags(target, GitRepo::Rustc).join(" ");
1106 .env(format!("CFLAGS_{}", target), cflags.clone());
1108 if let Some(ar) = self.ar(target) {
1109 let ranlib = format!("{} s", ar.display());
1111 .env(format!("AR_{}", target), ar)
1112 .env(format!("RANLIB_{}", target), ranlib);
1115 if let Ok(cxx) = self.cxx(target) {
1116 let cxx = ccacheify(&cxx);
1118 .env(format!("CXX_{}", target), &cxx)
1119 .env(format!("CXXFLAGS_{}", target), cflags);
1123 if mode == Mode::Std
1124 && self.config.extended
1125 && compiler.is_final_stage(self)
1127 rustflags.arg("-Zsave-analysis");
1128 cargo.env("RUST_SAVE_ANALYSIS_CONFIG",
1129 "{\"output_file\": null,\"full_docs\": false,\
1130 \"pub_only\": true,\"reachable_only\": false,\
1131 \"distro_crate\": true,\"signatures\": false,\"borrow_data\": false}");
1134 // For `cargo doc` invocations, make rustdoc print the Rust version into the docs
1135 cargo.env("RUSTDOC_CRATE_VERSION", self.rust_version());
1137 // Environment variables *required* throughout the build
1139 // FIXME: should update code to not require this env var
1140 cargo.env("CFG_COMPILER_HOST_TRIPLE", target);
1142 // Set this for all builds to make sure doc builds also get it.
1143 cargo.env("CFG_RELEASE_CHANNEL", &self.config.channel);
1145 // This one's a bit tricky. As of the time of this writing the compiler
1146 // links to the `winapi` crate on crates.io. This crate provides raw
1147 // bindings to Windows system functions, sort of like libc does for
1148 // Unix. This crate also, however, provides "import libraries" for the
1149 // MinGW targets. There's an import library per dll in the windows
1150 // distribution which is what's linked to. These custom import libraries
1151 // are used because the winapi crate can reference Windows functions not
1152 // present in the MinGW import libraries.
1154 // For example MinGW may ship libdbghelp.a, but it may not have
1155 // references to all the functions in the dbghelp dll. Instead the
1156 // custom import library for dbghelp in the winapi crates has all this
1159 // Unfortunately for us though the import libraries are linked by
1160 // default via `-ldylib=winapi_foo`. That is, they're linked with the
1161 // `dylib` type with a `winapi_` prefix (so the winapi ones don't
1162 // conflict with the system MinGW ones). This consequently means that
1163 // the binaries we ship of things like rustc_codegen_llvm (aka the rustc_codegen_llvm
1164 // DLL) when linked against *again*, for example with procedural macros
1165 // or plugins, will trigger the propagation logic of `-ldylib`, passing
1166 // `-lwinapi_foo` to the linker again. This isn't actually available in
1167 // our distribution, however, so the link fails.
1169 // To solve this problem we tell winapi to not use its bundled import
1170 // libraries. This means that it will link to the system MinGW import
1171 // libraries by default, and the `-ldylib=foo` directives will still get
1172 // passed to the final linker, but they'll look like `-lfoo` which can
1173 // be resolved because MinGW has the import library. The downside is we
1174 // don't get newer functions from Windows, but we don't use any of them
1176 if !mode.is_tool() {
1177 cargo.env("WINAPI_NO_BUNDLED_LIBRARIES", "1");
1180 for _ in 1..self.verbosity {
1184 match (mode, self.config.rust_codegen_units_std, self.config.rust_codegen_units) {
1185 (Mode::Std, Some(n), _) |
1186 (_, _, Some(n)) => {
1187 cargo.env(profile_var("CODEGEN_UNITS"), n.to_string());
1190 // Don't set anything
1194 if self.config.rust_optimize {
1195 // FIXME: cargo bench/install do not accept `--release`
1196 if cmd != "bench" && cmd != "install" {
1197 cargo.arg("--release");
1201 if self.config.locked_deps {
1202 cargo.arg("--locked");
1204 if self.config.vendor || self.is_sudo {
1205 cargo.arg("--frozen");
1208 // Try to use a sysroot-relative bindir, in case it was configured absolutely.
1209 cargo.env("RUSTC_INSTALL_BINDIR", self.config.bindir_relative());
1211 self.ci_env.force_coloring_in_ci(&mut cargo);
1213 // When we build Rust dylibs they're all intended for intermediate
1214 // usage, so make sure we pass the -Cprefer-dynamic flag instead of
1215 // linking all deps statically into the dylib.
1216 if let Mode::Std | Mode::Rustc | Mode::Codegen = mode {
1217 rustflags.arg("-Cprefer-dynamic");
1226 /// Ensure that a given step is built, returning its output. This will
1227 /// cache the step, so it is safe (and good!) to call this as often as
1228 /// needed to ensure that all dependencies are built.
1229 pub fn ensure<S: Step>(&'a self, step: S) -> S::Output {
1231 let mut stack = self.stack.borrow_mut();
1232 for stack_step in stack.iter() {
1235 .downcast_ref::<S>()
1236 .map_or(true, |stack_step| *stack_step != step)
1240 let mut out = String::new();
1241 out += &format!("\n\nCycle in build detected when adding {:?}\n", step);
1242 for el in stack.iter().rev() {
1243 out += &format!("\t{:?}\n", el);
1247 if let Some(out) = self.cache.get(&step) {
1248 self.verbose(&format!("{}c {:?}", " ".repeat(stack.len()), step));
1252 self.verbose(&format!("{}> {:?}", " ".repeat(stack.len()), step));
1253 stack.push(Box::new(step.clone()));
1257 let start = Instant::now();
1258 let zero = Duration::new(0, 0);
1259 let parent = self.time_spent_on_dependencies.replace(zero);
1260 let out = step.clone().run(self);
1261 let dur = start.elapsed();
1262 let deps = self.time_spent_on_dependencies.replace(parent + dur);
1266 if self.config.print_step_timings && dur > Duration::from_millis(100) {
1268 "[TIMING] {:?} -- {}.{:03}",
1271 dur.subsec_nanos() / 1_000_000
1276 let mut stack = self.stack.borrow_mut();
1277 let cur_step = stack.pop().expect("step stack empty");
1278 assert_eq!(cur_step.downcast_ref(), Some(&step));
1280 self.verbose(&format!(
1282 " ".repeat(self.stack.borrow().len()),
1285 self.cache.put(step, out.clone());
1294 struct Rustflags(String);
1297 fn new(target: &str) -> Rustflags {
1298 let mut ret = Rustflags(String::new());
1300 // Inherit `RUSTFLAGS` by default ...
1301 ret.env("RUSTFLAGS");
1303 // ... and also handle target-specific env RUSTFLAGS if they're
1305 let target_specific = format!("CARGO_TARGET_{}_RUSTFLAGS", crate::envify(target));
1306 ret.env(&target_specific);
1311 fn env(&mut self, env: &str) {
1312 if let Ok(s) = env::var(env) {
1313 for part in s.split_whitespace() {
1319 fn arg(&mut self, arg: &str) -> &mut Self {
1320 assert_eq!(arg.split_whitespace().count(), 1);
1321 if self.0.len() > 0 {
1322 self.0.push_str(" ");
1324 self.0.push_str(arg);
1332 rustflags: Rustflags,
1336 pub fn rustflag(&mut self, arg: &str) -> &mut Cargo {
1337 self.rustflags.arg(arg);
1341 pub fn arg(&mut self, arg: impl AsRef<OsStr>) -> &mut Cargo {
1342 self.command.arg(arg.as_ref());
1346 pub fn args<I, S>(&mut self, args: I) -> &mut Cargo
1347 where I: IntoIterator<Item=S>, S: AsRef<OsStr>
1350 self.arg(arg.as_ref());
1355 pub fn env(&mut self, key: impl AsRef<OsStr>, value: impl AsRef<OsStr>) -> &mut Cargo {
1356 self.command.env(key.as_ref(), value.as_ref());
1361 impl From<Cargo> for Command {
1362 fn from(mut cargo: Cargo) -> Command {
1363 cargo.command.env("RUSTFLAGS", &cargo.rustflags.0);