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)]
324 impl<'a> Builder<'a> {
325 fn get_step_descriptions(kind: Kind) -> Vec<StepDescription> {
326 macro_rules! describe {
327 ($($rule:ty),+ $(,)?) => {{
328 vec![$(StepDescription::from::<$rule>()),+]
332 Kind::Build => describe!(
335 compile::StartupObjects,
339 tool::UnstableBookGen,
344 tool::RemoteTestServer,
345 tool::RemoteTestClient,
356 Kind::Check | Kind::Clippy | Kind::Fix => describe!(
361 Kind::Test => describe!(
362 crate::toolstate::ToolStateCheck,
367 test::RunPassValgrind,
378 test::RunPassValgrindPretty,
388 test::RunMakeFullDeps,
402 test::CompiletestTest,
404 test::RustdocJSNotStd,
407 // Run bootstrap close to the end as it's unlikely to fail
409 // Run run-make last, since these won't pass without make on Windows
412 Kind::Bench => describe!(test::Crate, test::CrateLibrustc),
413 Kind::Doc => describe!(
415 doc::UnstableBookGen,
431 Kind::Dist => describe!(
436 dist::DebuggerScripts,
441 dist::PlainSourceTarball,
452 Kind::Install => describe!(
467 pub fn get_help(build: &Build, subcommand: &str) -> Option<String> {
468 let kind = match subcommand {
469 "build" => Kind::Build,
471 "test" => Kind::Test,
472 "bench" => Kind::Bench,
473 "dist" => Kind::Dist,
474 "install" => Kind::Install,
478 let builder = Builder {
480 top_stage: build.config.stage.unwrap_or(2),
483 stack: RefCell::new(Vec::new()),
484 time_spent_on_dependencies: Cell::new(Duration::new(0, 0)),
488 let builder = &builder;
489 let mut should_run = ShouldRun::new(builder);
490 for desc in Builder::get_step_descriptions(builder.kind) {
491 should_run = (desc.should_run)(should_run);
493 let mut help = String::from("Available paths:\n");
494 for pathset in should_run.paths {
495 if let PathSet::Set(set) = pathset {
496 set.iter().for_each(|path| {
498 format!(" ./x.py {} {}\n", subcommand, path.display()).as_str(),
506 pub fn new(build: &Build) -> Builder<'_> {
507 let (kind, paths) = match build.config.cmd {
508 Subcommand::Build { ref paths } => (Kind::Build, &paths[..]),
509 Subcommand::Check { ref paths } => (Kind::Check, &paths[..]),
510 Subcommand::Clippy { ref paths } => (Kind::Clippy, &paths[..]),
511 Subcommand::Fix { ref paths } => (Kind::Fix, &paths[..]),
512 Subcommand::Doc { ref paths } => (Kind::Doc, &paths[..]),
513 Subcommand::Test { ref paths, .. } => (Kind::Test, &paths[..]),
514 Subcommand::Bench { ref paths, .. } => (Kind::Bench, &paths[..]),
515 Subcommand::Dist { ref paths } => (Kind::Dist, &paths[..]),
516 Subcommand::Install { ref paths } => (Kind::Install, &paths[..]),
517 Subcommand::Clean { .. } => panic!(),
520 let builder = Builder {
522 top_stage: build.config.stage.unwrap_or(2),
525 stack: RefCell::new(Vec::new()),
526 time_spent_on_dependencies: Cell::new(Duration::new(0, 0)),
527 paths: paths.to_owned(),
533 pub fn execute_cli(&self) {
534 self.run_step_descriptions(&Builder::get_step_descriptions(self.kind), &self.paths);
537 pub fn default_doc(&self, paths: Option<&[PathBuf]>) {
538 let paths = paths.unwrap_or(&[]);
539 self.run_step_descriptions(&Builder::get_step_descriptions(Kind::Doc), paths);
542 fn run_step_descriptions(&self, v: &[StepDescription], paths: &[PathBuf]) {
543 StepDescription::run(v, self, paths);
546 /// Obtain a compiler at a given stage and for a given host. Explicitly does
547 /// not take `Compiler` since all `Compiler` instances are meant to be
548 /// obtained through this function, since it ensures that they are valid
549 /// (i.e., built and assembled).
550 pub fn compiler(&self, stage: u32, host: Interned<String>) -> Compiler {
551 self.ensure(compile::Assemble {
552 target_compiler: Compiler { stage, host },
556 /// Similar to `compiler`, except handles the full-bootstrap option to
557 /// silently use the stage1 compiler instead of a stage2 compiler if one is
560 /// Note that this does *not* have the side effect of creating
561 /// `compiler(stage, host)`, unlike `compiler` above which does have such
562 /// a side effect. The returned compiler here can only be used to compile
563 /// new artifacts, it can't be used to rely on the presence of a particular
566 /// See `force_use_stage1` for documentation on what each argument is.
570 host: Interned<String>,
571 target: Interned<String>,
573 if self.build.force_use_stage1(Compiler { stage, host }, target) {
574 self.compiler(1, self.config.build)
576 self.compiler(stage, host)
580 pub fn sysroot(&self, compiler: Compiler) -> Interned<PathBuf> {
581 self.ensure(compile::Sysroot { compiler })
584 /// Returns the libdir where the standard library and other artifacts are
585 /// found for a compiler's sysroot.
586 pub fn sysroot_libdir(
589 target: Interned<String>,
590 ) -> Interned<PathBuf> {
591 #[derive(Debug, Copy, Clone, Hash, PartialEq, Eq)]
594 target: Interned<String>,
596 impl Step for Libdir {
597 type Output = Interned<PathBuf>;
599 fn should_run(run: ShouldRun<'_>) -> ShouldRun<'_> {
603 fn run(self, builder: &Builder<'_>) -> Interned<PathBuf> {
604 let lib = builder.sysroot_libdir_relative(self.compiler);
605 let sysroot = builder
606 .sysroot(self.compiler)
611 let _ = fs::remove_dir_all(&sysroot);
612 t!(fs::create_dir_all(&sysroot));
613 INTERNER.intern_path(sysroot)
616 self.ensure(Libdir { compiler, target })
619 /// Returns the compiler's libdir where it stores the dynamic libraries that
620 /// it itself links against.
622 /// For example this returns `<sysroot>/lib` on Unix and `<sysroot>/bin` on
624 pub fn rustc_libdir(&self, compiler: Compiler) -> PathBuf {
625 if compiler.is_snapshot(self) {
626 self.rustc_snapshot_libdir()
628 match self.config.libdir_relative() {
629 Some(relative_libdir) if compiler.stage >= 1
630 => self.sysroot(compiler).join(relative_libdir),
631 _ => self.sysroot(compiler).join(libdir(&compiler.host))
636 /// Returns the compiler's relative libdir where it stores the dynamic libraries that
637 /// it itself links against.
639 /// For example this returns `lib` on Unix and `bin` on
641 pub fn libdir_relative(&self, compiler: Compiler) -> &Path {
642 if compiler.is_snapshot(self) {
643 libdir(&self.config.build).as_ref()
645 match self.config.libdir_relative() {
646 Some(relative_libdir) if compiler.stage >= 1
648 _ => libdir(&compiler.host).as_ref()
653 /// Returns the compiler's relative libdir where the standard library and other artifacts are
654 /// found for a compiler's sysroot.
656 /// For example this returns `lib` on Unix and Windows.
657 pub fn sysroot_libdir_relative(&self, compiler: Compiler) -> &Path {
658 match self.config.libdir_relative() {
659 Some(relative_libdir) if compiler.stage >= 1
661 _ => Path::new("lib")
665 /// Adds the compiler's directory of dynamic libraries to `cmd`'s dynamic
666 /// library lookup path.
667 pub fn add_rustc_lib_path(&self, compiler: Compiler, cmd: &mut Cargo) {
668 // Windows doesn't need dylib path munging because the dlls for the
669 // compiler live next to the compiler and the system will find them
675 add_lib_path(vec![self.rustc_libdir(compiler)], &mut cmd.command);
678 /// Gets a path to the compiler specified.
679 pub fn rustc(&self, compiler: Compiler) -> PathBuf {
680 if compiler.is_snapshot(self) {
681 self.initial_rustc.clone()
683 self.sysroot(compiler)
685 .join(exe("rustc", &compiler.host))
689 pub fn rustdoc(&self, compiler: Compiler) -> PathBuf {
690 self.ensure(tool::Rustdoc { compiler })
693 pub fn rustdoc_cmd(&self, compiler: Compiler) -> Command {
694 let mut cmd = Command::new(&self.out.join("bootstrap/debug/rustdoc"));
695 cmd.env("RUSTC_STAGE", compiler.stage.to_string())
696 .env("RUSTC_SYSROOT", self.sysroot(compiler))
697 // Note that this is *not* the sysroot_libdir because rustdoc must be linked
698 // equivalently to rustc.
699 .env("RUSTDOC_LIBDIR", self.rustc_libdir(compiler))
700 .env("CFG_RELEASE_CHANNEL", &self.config.channel)
701 .env("RUSTDOC_REAL", self.rustdoc(compiler))
702 .env("RUSTDOC_CRATE_VERSION", self.rust_version())
703 .env("RUSTC_BOOTSTRAP", "1");
705 // Remove make-related flags that can cause jobserver problems.
706 cmd.env_remove("MAKEFLAGS");
707 cmd.env_remove("MFLAGS");
709 if let Some(linker) = self.linker(compiler.host) {
710 cmd.env("RUSTC_TARGET_LINKER", linker);
715 /// Prepares an invocation of `cargo` to be run.
717 /// This will create a `Command` that represents a pending execution of
718 /// Cargo. This cargo will be configured to use `compiler` as the actual
719 /// rustc compiler, its output will be scoped by `mode`'s output directory,
720 /// it will pass the `--target` flag for the specified `target`, and will be
721 /// executing the Cargo command `cmd`.
726 target: Interned<String>,
729 let mut cargo = Command::new(&self.initial_cargo);
730 let out_dir = self.stage_out(compiler, mode);
732 if cmd == "doc" || cmd == "rustdoc" {
733 let my_out = match mode {
734 // This is the intended out directory for compiler documentation.
735 Mode::Rustc | Mode::ToolRustc | Mode::Codegen => self.compiler_doc_out(target),
736 _ => self.crate_doc_out(target),
738 let rustdoc = self.rustdoc(compiler);
739 self.clear_if_dirty(&my_out, &rustdoc);
743 .env("CARGO_TARGET_DIR", out_dir)
745 .arg("-Zconfig-profile");
747 let profile_var = |name: &str| {
748 let profile = if self.config.rust_optimize {
753 format!("CARGO_PROFILE_{}_{}", profile, name)
756 // See comment in librustc_llvm/build.rs for why this is necessary, largely llvm-config
757 // needs to not accidentally link to libLLVM in stage0/lib.
758 cargo.env("REAL_LIBRARY_PATH_VAR", &util::dylib_path_var());
759 if let Some(e) = env::var_os(util::dylib_path_var()) {
760 cargo.env("REAL_LIBRARY_PATH", e);
763 if cmd != "install" {
764 cargo.arg("--target")
767 assert_eq!(target, compiler.host);
770 // Set a flag for `check`/`clippy`/`fix`, so that certain build
771 // scripts can do less work (e.g. not building/requiring LLVM).
772 if cmd == "check" || cmd == "clippy" || cmd == "fix" {
773 cargo.env("RUST_CHECK", "1");
777 if compiler.stage == 0 && self.local_rebuild {
778 // Assume the local-rebuild rustc already has stage1 features.
781 stage = compiler.stage;
784 let mut rustflags = Rustflags::new(&target);
786 if let Ok(s) = env::var("CARGOFLAGS_NOT_BOOTSTRAP") {
787 cargo.args(s.split_whitespace());
789 rustflags.env("RUSTFLAGS_NOT_BOOTSTRAP");
791 if let Ok(s) = env::var("CARGOFLAGS_BOOTSTRAP") {
792 cargo.args(s.split_whitespace());
794 rustflags.env("RUSTFLAGS_BOOTSTRAP");
795 rustflags.arg("--cfg=bootstrap");
798 if let Ok(s) = env::var("CARGOFLAGS") {
799 cargo.args(s.split_whitespace());
803 Mode::Std | Mode::ToolBootstrap | Mode::ToolStd => {},
804 Mode::Rustc | Mode::Codegen | Mode::ToolRustc => {
805 // Build proc macros both for the host and the target
806 if target != compiler.host && cmd != "check" {
807 cargo.arg("-Zdual-proc-macros");
808 rustflags.arg("-Zdual-proc-macros");
813 // This tells Cargo (and in turn, rustc) to output more complete
814 // dependency information. Most importantly for rustbuild, this
815 // includes sysroot artifacts, like libstd, which means that we don't
816 // need to track those in rustbuild (an error prone process!). This
817 // feature is currently unstable as there may be some bugs and such, but
818 // it represents a big improvement in rustbuild's reliability on
819 // rebuilds, so we're using it here.
821 // For some additional context, see #63470 (the PR originally adding
822 // this), as well as #63012 which is the tracking issue for this
823 // feature on the rustc side.
824 cargo.arg("-Zbinary-dep-depinfo");
826 cargo.arg("-j").arg(self.jobs().to_string());
827 // Remove make-related flags to ensure Cargo can correctly set things up
828 cargo.env_remove("MAKEFLAGS");
829 cargo.env_remove("MFLAGS");
831 // FIXME: Temporary fix for https://github.com/rust-lang/cargo/issues/3005
832 // Force cargo to output binaries with disambiguating hashes in the name
833 let mut metadata = if compiler.stage == 0 {
834 // Treat stage0 like a special channel, whether it's a normal prior-
835 // release rustc or a local rebuild with the same version, so we
836 // never mix these libraries by accident.
837 "bootstrap".to_string()
839 self.config.channel.to_string()
841 // We want to make sure that none of the dependencies between
842 // std/test/rustc unify with one another. This is done for weird linkage
843 // reasons but the gist of the problem is that if librustc, libtest, and
844 // libstd all depend on libc from crates.io (which they actually do) we
845 // want to make sure they all get distinct versions. Things get really
846 // weird if we try to unify all these dependencies right now, namely
847 // around how many times the library is linked in dynamic libraries and
848 // such. If rustc were a static executable or if we didn't ship dylibs
849 // this wouldn't be a problem, but we do, so it is. This is in general
850 // just here to make sure things build right. If you can remove this and
851 // things still build right, please do!
853 Mode::Std => metadata.push_str("std"),
854 // When we're building rustc tools, they're built with a search path
855 // that contains things built during the rustc build. For example,
856 // bitflags is built during the rustc build, and is a dependency of
857 // rustdoc as well. We're building rustdoc in a different target
858 // directory, though, which means that Cargo will rebuild the
859 // dependency. When we go on to build rustdoc, we'll look for
860 // bitflags, and find two different copies: one built during the
861 // rustc step and one that we just built. This isn't always a
862 // problem, somehow -- not really clear why -- but we know that this
864 Mode::ToolRustc => metadata.push_str("tool-rustc"),
867 cargo.env("__CARGO_DEFAULT_LIB_METADATA", &metadata);
870 rustflags.arg("-Zforce-unstable-if-unmarked");
873 rustflags.arg("-Zexternal-macro-backtrace");
875 let want_rustdoc = self.doc_tests != DocTests::No;
877 // We synthetically interpret a stage0 compiler used to build tools as a
878 // "raw" compiler in that it's the exact snapshot we download. Normally
879 // the stage0 build means it uses libraries build by the stage0
880 // compiler, but for tools we just use the precompiled libraries that
882 let use_snapshot = mode == Mode::ToolBootstrap;
883 assert!(!use_snapshot || stage == 0 || self.local_rebuild);
885 let maybe_sysroot = self.sysroot(compiler);
886 let sysroot = if use_snapshot {
887 self.rustc_snapshot_sysroot()
891 let libdir = self.rustc_libdir(compiler);
893 // Customize the compiler we're running. Specify the compiler to cargo
894 // as our shim and then pass it some various options used to configure
895 // how the actual compiler itself is called.
897 // These variables are primarily all read by
898 // src/bootstrap/bin/{rustc.rs,rustdoc.rs}
900 .env("RUSTBUILD_NATIVE_DIR", self.native_dir(target))
901 .env("RUSTC", self.out.join("bootstrap/debug/rustc"))
902 .env("RUSTC_REAL", self.rustc(compiler))
903 .env("RUSTC_STAGE", stage.to_string())
905 "RUSTC_DEBUG_ASSERTIONS",
906 self.config.rust_debug_assertions.to_string(),
908 .env("RUSTC_SYSROOT", &sysroot)
909 .env("RUSTC_LIBDIR", &libdir)
910 .env("RUSTDOC", self.out.join("bootstrap/debug/rustdoc"))
913 if cmd == "doc" || cmd == "rustdoc" || (cmd == "test" && want_rustdoc) {
914 self.rustdoc(compiler)
916 PathBuf::from("/path/to/nowhere/rustdoc/not/required")
919 .env("RUSTC_ERROR_METADATA_DST", self.extended_error_dir())
920 .env("RUSTC_BREAK_ON_ICE", "1");
922 // Dealing with rpath here is a little special, so let's go into some
923 // detail. First off, `-rpath` is a linker option on Unix platforms
924 // which adds to the runtime dynamic loader path when looking for
925 // dynamic libraries. We use this by default on Unix platforms to ensure
926 // that our nightlies behave the same on Windows, that is they work out
927 // of the box. This can be disabled, of course, but basically that's why
928 // we're gated on RUSTC_RPATH here.
930 // Ok, so the astute might be wondering "why isn't `-C rpath` used
931 // here?" and that is indeed a good question to task. This codegen
932 // option is the compiler's current interface to generating an rpath.
933 // Unfortunately it doesn't quite suffice for us. The flag currently
934 // takes no value as an argument, so the compiler calculates what it
935 // should pass to the linker as `-rpath`. This unfortunately is based on
936 // the **compile time** directory structure which when building with
937 // Cargo will be very different than the runtime directory structure.
939 // All that's a really long winded way of saying that if we use
940 // `-Crpath` then the executables generated have the wrong rpath of
941 // something like `$ORIGIN/deps` when in fact the way we distribute
942 // rustc requires the rpath to be `$ORIGIN/../lib`.
944 // So, all in all, to set up the correct rpath we pass the linker
945 // argument manually via `-C link-args=-Wl,-rpath,...`. Plus isn't it
946 // fun to pass a flag to a tool to pass a flag to pass a flag to a tool
947 // to change a flag in a binary?
948 if self.config.rust_rpath && util::use_host_linker(&target) {
949 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 if let Some(host_linker) = self.linker(compiler.host) {
969 cargo.env("RUSTC_HOST_LINKER", host_linker);
971 if let Some(target_linker) = self.linker(target) {
972 let target = crate::envify(&target);
973 cargo.env(&format!("CARGO_TARGET_{}_LINKER", target), target_linker);
975 if !(["build", "check", "clippy", "fix", "rustc"].contains(&cmd)) && want_rustdoc {
976 cargo.env("RUSTDOC_LIBDIR", self.rustc_libdir(compiler));
979 let debuginfo_level = match mode {
980 Mode::Rustc | Mode::Codegen => self.config.rust_debuginfo_level_rustc,
981 Mode::Std => self.config.rust_debuginfo_level_std,
982 Mode::ToolBootstrap | Mode::ToolStd |
983 Mode::ToolRustc => self.config.rust_debuginfo_level_tools,
985 cargo.env(profile_var("DEBUG"), debuginfo_level.to_string());
988 cargo.env("RUSTC_FORCE_UNSTABLE", "1");
991 if let Some(x) = self.crt_static(target) {
993 rustflags.arg("-Ctarget-feature=+crt-static");
995 rustflags.arg("-Ctarget-feature=-crt-static");
999 if let Some(x) = self.crt_static(compiler.host) {
1000 cargo.env("RUSTC_HOST_CRT_STATIC", x.to_string());
1003 if let Some(map) = self.build.debuginfo_map(GitRepo::Rustc) {
1004 cargo.env("RUSTC_DEBUGINFO_MAP", map);
1007 // Enable usage of unstable features
1008 cargo.env("RUSTC_BOOTSTRAP", "1");
1009 self.add_rust_test_threads(&mut cargo);
1011 // Almost all of the crates that we compile as part of the bootstrap may
1012 // have a build script, including the standard library. To compile a
1013 // build script, however, it itself needs a standard library! This
1014 // introduces a bit of a pickle when we're compiling the standard
1017 // To work around this we actually end up using the snapshot compiler
1018 // (stage0) for compiling build scripts of the standard library itself.
1019 // The stage0 compiler is guaranteed to have a libstd available for use.
1021 // For other crates, however, we know that we've already got a standard
1022 // library up and running, so we can use the normal compiler to compile
1023 // build scripts in that situation.
1024 if mode == Mode::Std {
1026 .env("RUSTC_SNAPSHOT", &self.initial_rustc)
1027 .env("RUSTC_SNAPSHOT_LIBDIR", self.rustc_snapshot_libdir());
1030 .env("RUSTC_SNAPSHOT", self.rustc(compiler))
1031 .env("RUSTC_SNAPSHOT_LIBDIR", self.rustc_libdir(compiler));
1034 if self.config.incremental {
1035 cargo.env("CARGO_INCREMENTAL", "1");
1037 // Don't rely on any default setting for incr. comp. in Cargo
1038 cargo.env("CARGO_INCREMENTAL", "0");
1041 if let Some(ref on_fail) = self.config.on_fail {
1042 cargo.env("RUSTC_ON_FAIL", on_fail);
1045 if self.config.print_step_timings {
1046 cargo.env("RUSTC_PRINT_STEP_TIMINGS", "1");
1049 if self.config.backtrace_on_ice {
1050 cargo.env("RUSTC_BACKTRACE_ON_ICE", "1");
1053 cargo.env("RUSTC_VERBOSE", self.verbosity.to_string());
1055 if !mode.is_tool() {
1056 // When extending this list, add the new lints to the RUSTFLAGS of the
1057 // build_bootstrap function of src/bootstrap/bootstrap.py as well as
1058 // some code doesn't go through this `rustc` wrapper.
1059 rustflags.arg("-Wrust_2018_idioms");
1060 rustflags.arg("-Wunused_lifetimes");
1062 if self.config.deny_warnings {
1063 rustflags.arg("-Dwarnings");
1067 if let Mode::Rustc | Mode::Codegen = mode {
1068 rustflags.arg("-Zunstable-options");
1069 rustflags.arg("-Wrustc::internal");
1072 // Throughout the build Cargo can execute a number of build scripts
1073 // compiling C/C++ code and we need to pass compilers, archivers, flags, etc
1074 // obtained previously to those build scripts.
1075 // Build scripts use either the `cc` crate or `configure/make` so we pass
1076 // the options through environment variables that are fetched and understood by both.
1078 // FIXME: the guard against msvc shouldn't need to be here
1079 if target.contains("msvc") {
1080 if let Some(ref cl) = self.config.llvm_clang_cl {
1081 cargo.env("CC", cl).env("CXX", cl);
1084 let ccache = self.config.ccache.as_ref();
1085 let ccacheify = |s: &Path| {
1086 let ccache = match ccache {
1088 None => return s.display().to_string(),
1090 // FIXME: the cc-rs crate only recognizes the literal strings
1091 // `ccache` and `sccache` when doing caching compilations, so we
1092 // mirror that here. It should probably be fixed upstream to
1093 // accept a new env var or otherwise work with custom ccache
1096 "ccache" | "sccache" => format!("{} {}", ccache, s.display()),
1097 _ => s.display().to_string(),
1100 let cc = ccacheify(&self.cc(target));
1101 cargo.env(format!("CC_{}", target), &cc);
1103 let cflags = self.cflags(target, GitRepo::Rustc).join(" ");
1105 .env(format!("CFLAGS_{}", target), cflags.clone());
1107 if let Some(ar) = self.ar(target) {
1108 let ranlib = format!("{} s", ar.display());
1110 .env(format!("AR_{}", target), ar)
1111 .env(format!("RANLIB_{}", target), ranlib);
1114 if let Ok(cxx) = self.cxx(target) {
1115 let cxx = ccacheify(&cxx);
1117 .env(format!("CXX_{}", target), &cxx)
1118 .env(format!("CXXFLAGS_{}", target), cflags);
1122 if mode == Mode::Std
1123 && self.config.extended
1124 && compiler.is_final_stage(self)
1126 rustflags.arg("-Zsave-analysis");
1127 cargo.env("RUST_SAVE_ANALYSIS_CONFIG",
1128 "{\"output_file\": null,\"full_docs\": false,\
1129 \"pub_only\": true,\"reachable_only\": false,\
1130 \"distro_crate\": true,\"signatures\": false,\"borrow_data\": false}");
1133 // For `cargo doc` invocations, make rustdoc print the Rust version into the docs
1134 cargo.env("RUSTDOC_CRATE_VERSION", self.rust_version());
1136 // Environment variables *required* throughout the build
1138 // FIXME: should update code to not require this env var
1139 cargo.env("CFG_COMPILER_HOST_TRIPLE", target);
1141 // Set this for all builds to make sure doc builds also get it.
1142 cargo.env("CFG_RELEASE_CHANNEL", &self.config.channel);
1144 // This one's a bit tricky. As of the time of this writing the compiler
1145 // links to the `winapi` crate on crates.io. This crate provides raw
1146 // bindings to Windows system functions, sort of like libc does for
1147 // Unix. This crate also, however, provides "import libraries" for the
1148 // MinGW targets. There's an import library per dll in the windows
1149 // distribution which is what's linked to. These custom import libraries
1150 // are used because the winapi crate can reference Windows functions not
1151 // present in the MinGW import libraries.
1153 // For example MinGW may ship libdbghelp.a, but it may not have
1154 // references to all the functions in the dbghelp dll. Instead the
1155 // custom import library for dbghelp in the winapi crates has all this
1158 // Unfortunately for us though the import libraries are linked by
1159 // default via `-ldylib=winapi_foo`. That is, they're linked with the
1160 // `dylib` type with a `winapi_` prefix (so the winapi ones don't
1161 // conflict with the system MinGW ones). This consequently means that
1162 // the binaries we ship of things like rustc_codegen_llvm (aka the rustc_codegen_llvm
1163 // DLL) when linked against *again*, for example with procedural macros
1164 // or plugins, will trigger the propagation logic of `-ldylib`, passing
1165 // `-lwinapi_foo` to the linker again. This isn't actually available in
1166 // our distribution, however, so the link fails.
1168 // To solve this problem we tell winapi to not use its bundled import
1169 // libraries. This means that it will link to the system MinGW import
1170 // libraries by default, and the `-ldylib=foo` directives will still get
1171 // passed to the final linker, but they'll look like `-lfoo` which can
1172 // be resolved because MinGW has the import library. The downside is we
1173 // don't get newer functions from Windows, but we don't use any of them
1175 if !mode.is_tool() {
1176 cargo.env("WINAPI_NO_BUNDLED_LIBRARIES", "1");
1179 for _ in 1..self.verbosity {
1183 match (mode, self.config.rust_codegen_units_std, self.config.rust_codegen_units) {
1184 (Mode::Std, Some(n), _) |
1185 (_, _, Some(n)) => {
1186 cargo.env(profile_var("CODEGEN_UNITS"), n.to_string());
1189 // Don't set anything
1193 if self.config.rust_optimize {
1194 // FIXME: cargo bench/install do not accept `--release`
1195 if cmd != "bench" && cmd != "install" {
1196 cargo.arg("--release");
1200 if self.config.locked_deps {
1201 cargo.arg("--locked");
1203 if self.config.vendor || self.is_sudo {
1204 cargo.arg("--frozen");
1207 // Try to use a sysroot-relative bindir, in case it was configured absolutely.
1208 cargo.env("RUSTC_INSTALL_BINDIR", self.config.bindir_relative());
1210 self.ci_env.force_coloring_in_ci(&mut cargo);
1212 // When we build Rust dylibs they're all intended for intermediate
1213 // usage, so make sure we pass the -Cprefer-dynamic flag instead of
1214 // linking all deps statically into the dylib.
1215 if let Mode::Std | Mode::Rustc | Mode::Codegen = mode {
1216 rustflags.arg("-Cprefer-dynamic");
1225 /// Ensure that a given step is built, returning its output. This will
1226 /// cache the step, so it is safe (and good!) to call this as often as
1227 /// needed to ensure that all dependencies are built.
1228 pub fn ensure<S: Step>(&'a self, step: S) -> S::Output {
1230 let mut stack = self.stack.borrow_mut();
1231 for stack_step in stack.iter() {
1234 .downcast_ref::<S>()
1235 .map_or(true, |stack_step| *stack_step != step)
1239 let mut out = String::new();
1240 out += &format!("\n\nCycle in build detected when adding {:?}\n", step);
1241 for el in stack.iter().rev() {
1242 out += &format!("\t{:?}\n", el);
1246 if let Some(out) = self.cache.get(&step) {
1247 self.verbose(&format!("{}c {:?}", " ".repeat(stack.len()), step));
1251 self.verbose(&format!("{}> {:?}", " ".repeat(stack.len()), step));
1252 stack.push(Box::new(step.clone()));
1256 let start = Instant::now();
1257 let zero = Duration::new(0, 0);
1258 let parent = self.time_spent_on_dependencies.replace(zero);
1259 let out = step.clone().run(self);
1260 let dur = start.elapsed();
1261 let deps = self.time_spent_on_dependencies.replace(parent + dur);
1265 if self.config.print_step_timings && dur > Duration::from_millis(100) {
1267 "[TIMING] {:?} -- {}.{:03}",
1270 dur.subsec_nanos() / 1_000_000
1275 let mut stack = self.stack.borrow_mut();
1276 let cur_step = stack.pop().expect("step stack empty");
1277 assert_eq!(cur_step.downcast_ref(), Some(&step));
1279 self.verbose(&format!(
1281 " ".repeat(self.stack.borrow().len()),
1284 self.cache.put(step, out.clone());
1293 struct Rustflags(String);
1296 fn new(target: &str) -> Rustflags {
1297 let mut ret = Rustflags(String::new());
1299 // Inherit `RUSTFLAGS` by default ...
1300 ret.env("RUSTFLAGS");
1302 // ... and also handle target-specific env RUSTFLAGS if they're
1304 let target_specific = format!("CARGO_TARGET_{}_RUSTFLAGS", crate::envify(target));
1305 ret.env(&target_specific);
1310 fn env(&mut self, env: &str) {
1311 if let Ok(s) = env::var(env) {
1312 for part in s.split_whitespace() {
1318 fn arg(&mut self, arg: &str) -> &mut Self {
1319 assert_eq!(arg.split_whitespace().count(), 1);
1320 if self.0.len() > 0 {
1321 self.0.push_str(" ");
1323 self.0.push_str(arg);
1331 rustflags: Rustflags,
1335 pub fn rustflag(&mut self, arg: &str) -> &mut Cargo {
1336 self.rustflags.arg(arg);
1340 pub fn arg(&mut self, arg: impl AsRef<OsStr>) -> &mut Cargo {
1341 self.command.arg(arg.as_ref());
1345 pub fn args<I, S>(&mut self, args: I) -> &mut Cargo
1346 where I: IntoIterator<Item=S>, S: AsRef<OsStr>
1349 self.arg(arg.as_ref());
1354 pub fn env(&mut self, key: impl AsRef<OsStr>, value: impl AsRef<OsStr>) -> &mut Cargo {
1355 self.command.env(key.as_ref(), value.as_ref());
1360 impl From<Cargo> for Command {
1361 fn from(mut cargo: Cargo) -> Command {
1362 cargo.command.env("RUSTFLAGS", &cargo.rustflags.0);