1 // Copyright 2017 The Rust Project Developers. See the COPYRIGHT
2 // file at the top-level directory of this distribution and at
3 // http://rust-lang.org/COPYRIGHT.
5 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
6 // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
7 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
8 // option. This file may not be copied, modified, or distributed
9 // except according to those terms.
12 use std::cell::{Cell, RefCell};
13 use std::collections::BTreeSet;
19 use std::path::{Path, PathBuf};
20 use std::process::Command;
21 use std::time::{Instant, Duration};
22 use std::collections::HashMap;
27 use util::{exe, libdir, add_lib_path};
29 use cache::{INTERNER, Interned, Cache};
32 use flags::Subcommand;
40 use petgraph::graph::NodeIndex;
42 pub struct Builder<'a> {
47 stack: RefCell<Vec<Box<Any>>>,
48 time_spent_on_dependencies: Cell<Duration>,
49 pub paths: Vec<PathBuf>,
50 graph_nodes: RefCell<HashMap<String, NodeIndex>>,
51 graph: RefCell<Graph<String, bool>>,
52 parent: Cell<Option<NodeIndex>>,
55 impl<'a> Deref for Builder<'a> {
58 fn deref(&self) -> &Self::Target {
63 pub trait Step: 'static + Clone + Debug + PartialEq + Eq + Hash {
64 /// `PathBuf` when directories are created or to return a `Compiler` once
65 /// it's been assembled.
68 const DEFAULT: bool = false;
70 /// Run this rule for all hosts without cross compiling.
71 const ONLY_HOSTS: bool = false;
73 /// Primary function to execute this rule. Can call `builder.ensure(...)`
74 /// with other steps to run those.
75 fn run(self, builder: &Builder) -> Self::Output;
77 /// When bootstrap is passed a set of paths, this controls whether this rule
78 /// will execute. However, it does not get called in a "default" context
79 /// when we are not passed any paths; in that case, make_run is called
81 fn should_run(run: ShouldRun) -> ShouldRun;
83 /// Build up a "root" rule, either as a default rule or from a path passed
86 /// When path is `None`, we are executing in a context where no paths were
87 /// passed. When `./x.py build` is run, for example, this rule could get
88 /// called if it is in the correct list below with a path of `None`.
89 fn make_run(_run: RunConfig) {
90 // It is reasonable to not have an implementation of make_run for rules
91 // who do not want to get called from the root context. This means that
92 // they are likely dependencies (e.g., sysroot creation) or similar, and
93 // as such calling them from ./x.py isn't logical.
98 pub struct RunConfig<'a> {
99 pub builder: &'a Builder<'a>,
100 pub host: Interned<String>,
101 pub target: Interned<String>,
105 struct StepDescription {
108 should_run: fn(ShouldRun) -> ShouldRun,
109 make_run: fn(RunConfig),
113 #[derive(Debug, Clone, PartialOrd, Ord, PartialEq, Eq)]
115 set: BTreeSet<PathBuf>,
119 fn empty() -> PathSet {
120 PathSet { set: BTreeSet::new() }
123 fn one<P: Into<PathBuf>>(path: P) -> PathSet {
124 let mut set = BTreeSet::new();
125 set.insert(path.into());
129 fn has(&self, needle: &Path) -> bool {
130 self.set.iter().any(|p| p.ends_with(needle))
133 fn path(&self, builder: &Builder) -> PathBuf {
134 self.set.iter().next().unwrap_or(&builder.build.src).to_path_buf()
138 impl StepDescription {
139 fn from<S: Step>() -> StepDescription {
142 only_hosts: S::ONLY_HOSTS,
143 should_run: S::should_run,
144 make_run: S::make_run,
145 name: unsafe { ::std::intrinsics::type_name::<S>() },
149 fn maybe_run(&self, builder: &Builder, pathset: &PathSet) {
150 if builder.config.exclude.iter().any(|e| pathset.has(e)) {
151 eprintln!("Skipping {:?} because it is excluded", pathset);
153 } else if !builder.config.exclude.is_empty() {
154 eprintln!("{:?} not skipped for {:?} -- not in {:?}", pathset,
155 self.name, builder.config.exclude);
157 let build = builder.build;
158 let hosts = &build.hosts;
160 // Determine the targets participating in this rule.
161 let targets = if self.only_hosts {
162 if !build.config.run_host_only {
163 return; // don't run anything
172 for target in targets {
173 let run = RunConfig {
175 path: pathset.path(builder),
179 (self.make_run)(run);
184 fn run(v: &[StepDescription], builder: &Builder, paths: &[PathBuf]) {
185 let should_runs = v.iter().map(|desc| {
186 (desc.should_run)(ShouldRun::new(builder))
187 }).collect::<Vec<_>>();
189 // sanity checks on rules
190 for (desc, should_run) in v.iter().zip(&should_runs) {
191 assert!(!should_run.paths.is_empty(),
192 "{:?} should have at least one pathset", desc.name);
195 if paths.is_empty() {
196 for (desc, should_run) in v.iter().zip(should_runs) {
197 if desc.default && should_run.is_really_default {
198 for pathset in &should_run.paths {
199 desc.maybe_run(builder, pathset);
205 let mut attempted_run = false;
206 for (desc, should_run) in v.iter().zip(&should_runs) {
207 if let Some(pathset) = should_run.pathset_for_path(path) {
208 attempted_run = true;
209 desc.maybe_run(builder, pathset);
214 panic!("Error: no rules matched {}.", path.display());
222 pub struct ShouldRun<'a> {
223 pub builder: &'a Builder<'a>,
224 // use a BTreeSet to maintain sort order
225 paths: BTreeSet<PathSet>,
227 // If this is a default rule, this is an additional constraint placed on
228 // its run. Generally something like compiler docs being enabled.
229 is_really_default: bool,
232 impl<'a> ShouldRun<'a> {
233 fn new(builder: &'a Builder) -> ShouldRun<'a> {
236 paths: BTreeSet::new(),
237 is_really_default: true, // by default no additional conditions
241 pub fn default_condition(mut self, cond: bool) -> Self {
242 self.is_really_default = cond;
246 // Unlike `krate` this will create just one pathset. As such, it probably shouldn't actually
247 // ever be used, but as we transition to having all rules properly handle passing krate(...) by
248 // actually doing something different for every crate passed.
249 pub fn all_krates(mut self, name: &str) -> Self {
250 let mut set = BTreeSet::new();
251 for krate in self.builder.in_tree_crates(name) {
252 set.insert(PathBuf::from(&krate.path));
254 self.paths.insert(PathSet { set });
258 pub fn krate(mut self, name: &str) -> Self {
259 for krate in self.builder.in_tree_crates(name) {
260 self.paths.insert(PathSet::one(&krate.path));
265 // single, non-aliased path
266 pub fn path(self, path: &str) -> Self {
270 // multiple aliases for the same job
271 pub fn paths(mut self, paths: &[&str]) -> Self {
272 self.paths.insert(PathSet {
273 set: paths.iter().map(PathBuf::from).collect(),
278 // allows being more explicit about why should_run in Step returns the value passed to it
279 pub fn never(mut self) -> ShouldRun<'a> {
280 self.paths.insert(PathSet::empty());
284 fn pathset_for_path(&self, path: &Path) -> Option<&PathSet> {
285 self.paths.iter().find(|pathset| pathset.has(path))
289 #[derive(Copy, Clone, PartialEq, Eq, Debug)]
300 impl<'a> Builder<'a> {
301 fn get_step_descriptions(kind: Kind) -> Vec<StepDescription> {
302 macro_rules! describe {
303 ($($rule:ty),+ $(,)*) => {{
304 vec![$(StepDescription::from::<$rule>()),+]
308 Kind::Build => describe!(compile::Std, compile::Test, compile::Rustc,
309 compile::StartupObjects, tool::BuildManifest, tool::Rustbook, tool::ErrorIndex,
310 tool::UnstableBookGen, tool::Tidy, tool::Linkchecker, tool::CargoTest,
311 tool::Compiletest, tool::RemoteTestServer, tool::RemoteTestClient,
312 tool::RustInstaller, tool::Cargo, tool::Rls, tool::Rustdoc, tool::Clippy,
313 native::Llvm, tool::Rustfmt, tool::Miri, native::Lld),
314 Kind::Check => describe!(check::Std, check::Test, check::Rustc),
315 Kind::Test => describe!(test::Tidy, test::Bootstrap, test::Ui, test::RunPass,
316 test::CompileFail, test::ParseFail, test::RunFail, test::RunPassValgrind,
317 test::MirOpt, test::Codegen, test::CodegenUnits, test::Incremental, test::Debuginfo,
318 test::UiFullDeps, test::RunPassFullDeps, test::RunFailFullDeps,
319 test::CompileFailFullDeps, test::IncrementalFullDeps, test::Rustdoc, test::Pretty,
320 test::RunPassPretty, test::RunFailPretty, test::RunPassValgrindPretty,
321 test::RunPassFullDepsPretty, test::RunFailFullDepsPretty,
322 test::Crate, test::CrateLibrustc, test::CrateRustdoc, test::Linkcheck,
323 test::Cargotest, test::Cargo, test::Rls, test::ErrorIndex, test::Distcheck,
324 test::RunMakeFullDeps,
325 test::Nomicon, test::Reference, test::RustdocBook, test::RustByExample,
326 test::TheBook, test::UnstableBook,
327 test::Rustfmt, test::Miri, test::Clippy, test::RustdocJS, test::RustdocTheme,
328 // Run run-make last, since these won't pass without make on Windows
330 Kind::Bench => describe!(test::Crate, test::CrateLibrustc),
331 Kind::Doc => describe!(doc::UnstableBook, doc::UnstableBookGen, doc::TheBook,
332 doc::Standalone, doc::Std, doc::Test, doc::WhitelistedRustc, doc::Rustc,
333 doc::ErrorIndex, doc::Nomicon, doc::Reference, doc::Rustdoc, doc::RustByExample,
335 Kind::Dist => describe!(dist::Docs, dist::RustcDocs, dist::Mingw, dist::Rustc,
336 dist::DebuggerScripts, dist::Std, dist::Analysis, dist::Src,
337 dist::PlainSourceTarball, dist::Cargo, dist::Rls, dist::Rustfmt, dist::Extended,
339 Kind::Install => describe!(install::Docs, install::Std, install::Cargo, install::Rls,
340 install::Rustfmt, install::Analysis, install::Src, install::Rustc),
344 pub fn get_help(build: &Build, subcommand: &str) -> Option<String> {
345 let kind = match subcommand {
346 "build" => Kind::Build,
348 "test" => Kind::Test,
349 "bench" => Kind::Bench,
350 "dist" => Kind::Dist,
351 "install" => Kind::Install,
355 let builder = Builder {
357 top_stage: build.config.stage.unwrap_or(2),
360 stack: RefCell::new(Vec::new()),
361 time_spent_on_dependencies: Cell::new(Duration::new(0, 0)),
363 graph_nodes: RefCell::new(HashMap::new()),
364 graph: RefCell::new(Graph::new()),
365 parent: Cell::new(None),
368 let builder = &builder;
369 let mut should_run = ShouldRun::new(builder);
370 for desc in Builder::get_step_descriptions(builder.kind) {
371 should_run = (desc.should_run)(should_run);
373 let mut help = String::from("Available paths:\n");
374 for pathset in should_run.paths {
375 for path in pathset.set {
376 help.push_str(format!(" ./x.py {} {}\n", subcommand, path.display()).as_str());
382 pub fn new(build: &Build) -> Builder {
383 let (kind, paths) = match build.config.cmd {
384 Subcommand::Build { ref paths } => (Kind::Build, &paths[..]),
385 Subcommand::Check { ref paths } => (Kind::Check, &paths[..]),
386 Subcommand::Doc { ref paths } => (Kind::Doc, &paths[..]),
387 Subcommand::Test { ref paths, .. } => (Kind::Test, &paths[..]),
388 Subcommand::Bench { ref paths, .. } => (Kind::Bench, &paths[..]),
389 Subcommand::Dist { ref paths } => (Kind::Dist, &paths[..]),
390 Subcommand::Install { ref paths } => (Kind::Install, &paths[..]),
391 Subcommand::Clean { .. } => panic!(),
394 let builder = Builder {
396 top_stage: build.config.stage.unwrap_or(2),
399 stack: RefCell::new(Vec::new()),
400 time_spent_on_dependencies: Cell::new(Duration::new(0, 0)),
401 paths: paths.to_owned(),
402 graph_nodes: RefCell::new(HashMap::new()),
403 graph: RefCell::new(Graph::new()),
404 parent: Cell::new(None),
407 if kind == Kind::Dist {
408 assert!(!builder.config.test_miri, "Do not distribute with miri enabled.\n\
409 The distributed libraries would include all MIR (increasing binary size).
410 The distributed MIR would include validation statements.");
416 pub fn execute_cli(&self) -> Graph<String, bool> {
417 self.run_step_descriptions(&Builder::get_step_descriptions(self.kind), &self.paths);
418 self.graph.borrow().clone()
421 pub fn default_doc(&self, paths: Option<&[PathBuf]>) {
422 let paths = paths.unwrap_or(&[]);
423 self.run_step_descriptions(&Builder::get_step_descriptions(Kind::Doc), paths);
426 fn run_step_descriptions(&self, v: &[StepDescription], paths: &[PathBuf]) {
427 StepDescription::run(v, self, paths);
430 /// Obtain a compiler at a given stage and for a given host. Explicitly does
431 /// not take `Compiler` since all `Compiler` instances are meant to be
432 /// obtained through this function, since it ensures that they are valid
433 /// (i.e., built and assembled).
434 pub fn compiler(&self, stage: u32, host: Interned<String>) -> Compiler {
435 self.ensure(compile::Assemble { target_compiler: Compiler { stage, host } })
438 pub fn sysroot(&self, compiler: Compiler) -> Interned<PathBuf> {
439 self.ensure(compile::Sysroot { compiler })
442 /// Returns the libdir where the standard library and other artifacts are
443 /// found for a compiler's sysroot.
444 pub fn sysroot_libdir(
445 &self, compiler: Compiler, target: Interned<String>
446 ) -> Interned<PathBuf> {
447 #[derive(Debug, Copy, Clone, Hash, PartialEq, Eq)]
450 target: Interned<String>,
452 impl Step for Libdir {
453 type Output = Interned<PathBuf>;
455 fn should_run(run: ShouldRun) -> ShouldRun {
459 fn run(self, builder: &Builder) -> Interned<PathBuf> {
460 let compiler = self.compiler;
461 let config = &builder.build.config;
462 let lib = if compiler.stage >= 1 && config.libdir_relative().is_some() {
463 builder.build.config.libdir_relative().unwrap()
467 let sysroot = builder.sysroot(self.compiler).join(lib)
468 .join("rustlib").join(self.target).join("lib");
469 let _ = fs::remove_dir_all(&sysroot);
470 t!(fs::create_dir_all(&sysroot));
471 INTERNER.intern_path(sysroot)
474 self.ensure(Libdir { compiler, target })
477 pub fn sysroot_codegen_backends(&self, compiler: Compiler) -> PathBuf {
478 self.sysroot_libdir(compiler, compiler.host)
479 .with_file_name(self.build.config.rust_codegen_backends_dir.clone())
482 /// Returns the compiler's libdir where it stores the dynamic libraries that
483 /// it itself links against.
485 /// For example this returns `<sysroot>/lib` on Unix and `<sysroot>/bin` on
487 pub fn rustc_libdir(&self, compiler: Compiler) -> PathBuf {
488 if compiler.is_snapshot(self) {
489 self.build.rustc_snapshot_libdir()
491 self.sysroot(compiler).join(libdir(&compiler.host))
495 /// Adds the compiler's directory of dynamic libraries to `cmd`'s dynamic
496 /// library lookup path.
497 pub fn add_rustc_lib_path(&self, compiler: Compiler, cmd: &mut Command) {
498 // Windows doesn't need dylib path munging because the dlls for the
499 // compiler live next to the compiler and the system will find them
505 add_lib_path(vec![self.rustc_libdir(compiler)], cmd);
508 /// Get a path to the compiler specified.
509 pub fn rustc(&self, compiler: Compiler) -> PathBuf {
510 if compiler.is_snapshot(self) {
511 self.initial_rustc.clone()
513 self.sysroot(compiler).join("bin").join(exe("rustc", &compiler.host))
517 pub fn rustdoc(&self, host: Interned<String>) -> PathBuf {
518 self.ensure(tool::Rustdoc { host })
521 pub fn rustdoc_cmd(&self, host: Interned<String>) -> Command {
522 let mut cmd = Command::new(&self.out.join("bootstrap/debug/rustdoc"));
523 let compiler = self.compiler(self.top_stage, host);
524 cmd.env("RUSTC_STAGE", compiler.stage.to_string())
525 .env("RUSTC_SYSROOT", self.sysroot(compiler))
526 .env("RUSTDOC_LIBDIR", self.sysroot_libdir(compiler, self.build.build))
527 .env("CFG_RELEASE_CHANNEL", &self.build.config.channel)
528 .env("RUSTDOC_REAL", self.rustdoc(host))
529 .env("RUSTDOC_CRATE_VERSION", self.build.rust_version())
530 .env("RUSTC_BOOTSTRAP", "1");
531 if let Some(linker) = self.build.linker(host) {
532 cmd.env("RUSTC_TARGET_LINKER", linker);
537 /// Prepares an invocation of `cargo` to be run.
539 /// This will create a `Command` that represents a pending execution of
540 /// Cargo. This cargo will be configured to use `compiler` as the actual
541 /// rustc compiler, its output will be scoped by `mode`'s output directory,
542 /// it will pass the `--target` flag for the specified `target`, and will be
543 /// executing the Cargo command `cmd`.
547 target: Interned<String>,
548 cmd: &str) -> Command {
549 let mut cargo = Command::new(&self.initial_cargo);
550 let out_dir = self.stage_out(compiler, mode);
551 cargo.env("CARGO_TARGET_DIR", out_dir)
556 // If we were invoked from `make` then that's already got a jobserver
557 // set up for us so no need to tell Cargo about jobs all over again.
558 if env::var_os("MAKEFLAGS").is_none() && env::var_os("MFLAGS").is_none() {
559 cargo.arg("-j").arg(self.jobs().to_string());
562 // FIXME: Temporary fix for https://github.com/rust-lang/cargo/issues/3005
563 // Force cargo to output binaries with disambiguating hashes in the name
564 cargo.env("__CARGO_DEFAULT_LIB_METADATA", &self.config.channel);
567 if compiler.stage == 0 && self.local_rebuild {
568 // Assume the local-rebuild rustc already has stage1 features.
571 stage = compiler.stage;
574 let mut extra_args = env::var(&format!("RUSTFLAGS_STAGE_{}", stage)).unwrap_or_default();
576 let s = env::var("RUSTFLAGS_STAGE_NOT_0").unwrap_or_default();
577 if !extra_args.is_empty() {
578 extra_args.push_str(" ");
580 extra_args.push_str(&s);
583 if !extra_args.is_empty() {
584 cargo.env("RUSTFLAGS",
585 format!("{} {}", env::var("RUSTFLAGS").unwrap_or_default(), extra_args));
588 // Customize the compiler we're running. Specify the compiler to cargo
589 // as our shim and then pass it some various options used to configure
590 // how the actual compiler itself is called.
592 // These variables are primarily all read by
593 // src/bootstrap/bin/{rustc.rs,rustdoc.rs}
594 cargo.env("RUSTBUILD_NATIVE_DIR", self.native_dir(target))
595 .env("RUSTC", self.out.join("bootstrap/debug/rustc"))
596 .env("RUSTC_REAL", self.rustc(compiler))
597 .env("RUSTC_STAGE", stage.to_string())
598 .env("RUSTC_DEBUG_ASSERTIONS",
599 self.config.rust_debug_assertions.to_string())
600 .env("RUSTC_SYSROOT", self.sysroot(compiler))
601 .env("RUSTC_LIBDIR", self.rustc_libdir(compiler))
602 .env("RUSTC_RPATH", self.config.rust_rpath.to_string())
603 .env("RUSTDOC", self.out.join("bootstrap/debug/rustdoc"))
604 .env("RUSTDOC_REAL", if cmd == "doc" || cmd == "test" {
605 self.rustdoc(compiler.host)
607 PathBuf::from("/path/to/nowhere/rustdoc/not/required")
609 .env("TEST_MIRI", self.config.test_miri.to_string())
610 .env("RUSTC_ERROR_METADATA_DST", self.extended_error_dir());
612 if let Some(host_linker) = self.build.linker(compiler.host) {
613 cargo.env("RUSTC_HOST_LINKER", host_linker);
615 if let Some(target_linker) = self.build.linker(target) {
616 cargo.env("RUSTC_TARGET_LINKER", target_linker);
618 if let Some(ref error_format) = self.config.rustc_error_format {
619 cargo.env("RUSTC_ERROR_FORMAT", error_format);
621 if cmd != "build" && cmd != "check" {
622 cargo.env("RUSTDOC_LIBDIR", self.rustc_libdir(self.compiler(2, self.build.build)));
625 if mode == Mode::Tool {
626 // Tools like cargo and rls don't get debuginfo by default right now, but this can be
627 // enabled in the config. Adding debuginfo makes them several times larger.
628 if self.config.rust_debuginfo_tools {
629 cargo.env("RUSTC_DEBUGINFO", self.config.rust_debuginfo.to_string());
630 cargo.env("RUSTC_DEBUGINFO_LINES", self.config.rust_debuginfo_lines.to_string());
633 cargo.env("RUSTC_DEBUGINFO", self.config.rust_debuginfo.to_string());
634 cargo.env("RUSTC_DEBUGINFO_LINES", self.config.rust_debuginfo_lines.to_string());
635 cargo.env("RUSTC_FORCE_UNSTABLE", "1");
637 // Currently the compiler depends on crates from crates.io, and
638 // then other crates can depend on the compiler (e.g. proc-macro
639 // crates). Let's say, for example that rustc itself depends on the
640 // bitflags crate. If an external crate then depends on the
641 // bitflags crate as well, we need to make sure they don't
642 // conflict, even if they pick the same version of bitflags. We'll
643 // want to make sure that e.g. a plugin and rustc each get their
644 // own copy of bitflags.
646 // Cargo ensures that this works in general through the -C metadata
647 // flag. This flag will frob the symbols in the binary to make sure
648 // they're different, even though the source code is the exact
649 // same. To solve this problem for the compiler we extend Cargo's
650 // already-passed -C metadata flag with our own. Our rustc.rs
651 // wrapper around the actual rustc will detect -C metadata being
652 // passed and frob it with this extra string we're passing in.
653 cargo.env("RUSTC_METADATA_SUFFIX", "rustc");
656 if let Some(x) = self.crt_static(target) {
657 cargo.env("RUSTC_CRT_STATIC", x.to_string());
660 // Enable usage of unstable features
661 cargo.env("RUSTC_BOOTSTRAP", "1");
662 self.add_rust_test_threads(&mut cargo);
664 // Almost all of the crates that we compile as part of the bootstrap may
665 // have a build script, including the standard library. To compile a
666 // build script, however, it itself needs a standard library! This
667 // introduces a bit of a pickle when we're compiling the standard
670 // To work around this we actually end up using the snapshot compiler
671 // (stage0) for compiling build scripts of the standard library itself.
672 // The stage0 compiler is guaranteed to have a libstd available for use.
674 // For other crates, however, we know that we've already got a standard
675 // library up and running, so we can use the normal compiler to compile
676 // build scripts in that situation.
678 // If LLVM support is disabled we need to use the snapshot compiler to compile
679 // build scripts, as the new compiler doesn't support executables.
680 if mode == Mode::Libstd || !self.build.config.llvm_enabled {
681 cargo.env("RUSTC_SNAPSHOT", &self.initial_rustc)
682 .env("RUSTC_SNAPSHOT_LIBDIR", self.rustc_snapshot_libdir());
684 cargo.env("RUSTC_SNAPSHOT", self.rustc(compiler))
685 .env("RUSTC_SNAPSHOT_LIBDIR", self.rustc_libdir(compiler));
688 // Ignore incremental modes except for stage0, since we're
689 // not guaranteeing correctness across builds if the compiler
690 // is changing under your feet.`
691 if self.config.incremental && compiler.stage == 0 {
692 cargo.env("CARGO_INCREMENTAL", "1");
695 if let Some(ref on_fail) = self.config.on_fail {
696 cargo.env("RUSTC_ON_FAIL", on_fail);
699 if self.config.print_step_timings {
700 cargo.env("RUSTC_PRINT_STEP_TIMINGS", "1");
703 cargo.env("RUSTC_VERBOSE", format!("{}", self.verbosity));
705 // in std, we want to avoid denying warnings for stage 0 as that makes cfg's painful.
706 if self.config.deny_warnings && !(mode == Mode::Libstd && stage == 0) {
707 cargo.env("RUSTC_DENY_WARNINGS", "1");
710 // Throughout the build Cargo can execute a number of build scripts
711 // compiling C/C++ code and we need to pass compilers, archivers, flags, etc
712 // obtained previously to those build scripts.
713 // Build scripts use either the `cc` crate or `configure/make` so we pass
714 // the options through environment variables that are fetched and understood by both.
716 // FIXME: the guard against msvc shouldn't need to be here
717 if !target.contains("msvc") {
718 let ccache = self.config.ccache.as_ref();
719 let ccacheify = |s: &Path| {
720 let ccache = match ccache {
722 None => return s.display().to_string(),
724 // FIXME: the cc-rs crate only recognizes the literal strings
725 // `ccache` and `sccache` when doing caching compilations, so we
726 // mirror that here. It should probably be fixed upstream to
727 // accept a new env var or otherwise work with custom ccache
730 "ccache" | "sccache" => format!("{} {}", ccache, s.display()),
731 _ => s.display().to_string(),
734 let cc = ccacheify(&self.cc(target));
735 cargo.env(format!("CC_{}", target), &cc)
738 let cflags = self.cflags(target).join(" ");
739 cargo.env(format!("CFLAGS_{}", target), cflags.clone())
740 .env("CFLAGS", cflags.clone());
742 if let Some(ar) = self.ar(target) {
743 let ranlib = format!("{} s", ar.display());
744 cargo.env(format!("AR_{}", target), ar)
746 .env(format!("RANLIB_{}", target), ranlib.clone())
747 .env("RANLIB", ranlib);
750 if let Ok(cxx) = self.cxx(target) {
751 let cxx = ccacheify(&cxx);
752 cargo.env(format!("CXX_{}", target), &cxx)
754 .env(format!("CXXFLAGS_{}", target), cflags.clone())
755 .env("CXXFLAGS", cflags);
759 if mode == Mode::Libstd && self.config.extended && compiler.is_final_stage(self) {
760 cargo.env("RUSTC_SAVE_ANALYSIS", "api".to_string());
763 // For `cargo doc` invocations, make rustdoc print the Rust version into the docs
764 cargo.env("RUSTDOC_CRATE_VERSION", self.build.rust_version());
766 // Environment variables *required* throughout the build
768 // FIXME: should update code to not require this env var
769 cargo.env("CFG_COMPILER_HOST_TRIPLE", target);
771 // Set this for all builds to make sure doc builds also get it.
772 cargo.env("CFG_RELEASE_CHANNEL", &self.build.config.channel);
774 // This one's a bit tricky. As of the time of this writing the compiler
775 // links to the `winapi` crate on crates.io. This crate provides raw
776 // bindings to Windows system functions, sort of like libc does for
777 // Unix. This crate also, however, provides "import libraries" for the
778 // MinGW targets. There's an import library per dll in the windows
779 // distribution which is what's linked to. These custom import libraries
780 // are used because the winapi crate can reference Windows functions not
781 // present in the MinGW import libraries.
783 // For example MinGW may ship libdbghelp.a, but it may not have
784 // references to all the functions in the dbghelp dll. Instead the
785 // custom import library for dbghelp in the winapi crates has all this
788 // Unfortunately for us though the import libraries are linked by
789 // default via `-ldylib=winapi_foo`. That is, they're linked with the
790 // `dylib` type with a `winapi_` prefix (so the winapi ones don't
791 // conflict with the system MinGW ones). This consequently means that
792 // the binaries we ship of things like rustc_trans (aka the rustc_trans
793 // DLL) when linked against *again*, for example with procedural macros
794 // or plugins, will trigger the propagation logic of `-ldylib`, passing
795 // `-lwinapi_foo` to the linker again. This isn't actually available in
796 // our distribution, however, so the link fails.
798 // To solve this problem we tell winapi to not use its bundled import
799 // libraries. This means that it will link to the system MinGW import
800 // libraries by default, and the `-ldylib=foo` directives will still get
801 // passed to the final linker, but they'll look like `-lfoo` which can
802 // be resolved because MinGW has the import library. The downside is we
803 // don't get newer functions from Windows, but we don't use any of them
805 if mode != Mode::Tool {
806 cargo.env("WINAPI_NO_BUNDLED_LIBRARIES", "1");
809 for _ in 1..self.verbosity {
813 // This must be kept before the thinlto check, as we set codegen units
814 // to 1 forcibly there.
815 if let Some(n) = self.config.rust_codegen_units {
816 cargo.env("RUSTC_CODEGEN_UNITS", n.to_string());
819 if self.config.rust_optimize {
820 // FIXME: cargo bench does not accept `--release`
822 cargo.arg("--release");
826 if self.config.locked_deps {
827 cargo.arg("--locked");
829 if self.config.vendor || self.is_sudo {
830 cargo.arg("--frozen");
833 self.ci_env.force_coloring_in_ci(&mut cargo);
838 /// Ensure that a given step is built, returning it's output. This will
839 /// cache the step, so it is safe (and good!) to call this as often as
840 /// needed to ensure that all dependencies are built.
841 pub fn ensure<S: Step>(&'a self, step: S) -> S::Output {
843 let mut stack = self.stack.borrow_mut();
844 for stack_step in stack.iter() {
846 if stack_step.downcast_ref::<S>().map_or(true, |stack_step| *stack_step != step) {
849 let mut out = String::new();
850 out += &format!("\n\nCycle in build detected when adding {:?}\n", step);
851 for el in stack.iter().rev() {
852 out += &format!("\t{:?}\n", el);
856 if let Some(out) = self.cache.get(&step) {
857 self.build.verbose(&format!("{}c {:?}", " ".repeat(stack.len()), step));
860 let mut graph = self.graph.borrow_mut();
861 let parent = self.parent.get();
862 let us = *self.graph_nodes.borrow_mut()
863 .entry(format!("{:?}", step))
864 .or_insert_with(|| graph.add_node(format!("{:?}", step)));
865 if let Some(parent) = parent {
866 graph.add_edge(parent, us, false);
872 self.build.verbose(&format!("{}> {:?}", " ".repeat(stack.len()), step));
873 stack.push(Box::new(step.clone()));
876 let prev_parent = self.parent.get();
879 let mut graph = self.graph.borrow_mut();
880 let parent = self.parent.get();
881 let us = *self.graph_nodes.borrow_mut()
882 .entry(format!("{:?}", step))
883 .or_insert_with(|| graph.add_node(format!("{:?}", step)));
884 self.parent.set(Some(us));
885 if let Some(parent) = parent {
886 graph.add_edge(parent, us, true);
891 let start = Instant::now();
892 let zero = Duration::new(0, 0);
893 let parent = self.time_spent_on_dependencies.replace(zero);
894 let out = step.clone().run(self);
895 let dur = start.elapsed();
896 let deps = self.time_spent_on_dependencies.replace(parent + dur);
900 self.parent.set(prev_parent);
902 if self.build.config.print_step_timings && dur > Duration::from_millis(100) {
903 println!("[TIMING] {:?} -- {}.{:03}",
906 dur.subsec_nanos() / 1_000_000);
910 let mut stack = self.stack.borrow_mut();
911 let cur_step = stack.pop().expect("step stack empty");
912 assert_eq!(cur_step.downcast_ref(), Some(&step));
914 self.build.verbose(&format!("{}< {:?}", " ".repeat(self.stack.borrow().len()), step));
915 self.cache.put(step, out.clone());
926 fn configure(host: &[&str], target: &[&str]) -> Config {
927 let mut config = Config::default_opts();
928 // don't save toolstates
929 config.save_toolstates = None;
930 config.run_host_only = true;
931 config.dry_run = true;
932 // try to avoid spurious failures in dist where we create/delete each others file
933 let dir = config.out.join("tmp-rustbuild-tests")
934 .join(&thread::current().name().unwrap_or("unknown").replace(":", "-"));
935 t!(fs::create_dir_all(&dir));
937 config.build = INTERNER.intern_str("A");
938 config.hosts = vec![config.build].clone().into_iter()
939 .chain(host.iter().map(|s| INTERNER.intern_str(s))).collect::<Vec<_>>();
940 config.targets = config.hosts.clone().into_iter()
941 .chain(target.iter().map(|s| INTERNER.intern_str(s))).collect::<Vec<_>>();
945 fn first<A, B>(v: Vec<(A, B)>) -> Vec<A> {
946 v.into_iter().map(|(a, _)| a).collect::<Vec<_>>()
951 let build = Build::new(configure(&[], &[]));
952 let mut builder = Builder::new(&build);
953 builder.run_step_descriptions(&Builder::get_step_descriptions(Kind::Dist), &[]);
955 let a = INTERNER.intern_str("A");
957 assert_eq!(first(builder.cache.all::<dist::Docs>()), &[
958 dist::Docs { stage: 2, host: a },
960 assert_eq!(first(builder.cache.all::<dist::Mingw>()), &[
961 dist::Mingw { host: a },
963 assert_eq!(first(builder.cache.all::<dist::Rustc>()), &[
964 dist::Rustc { compiler: Compiler { host: a, stage: 2 } },
966 assert_eq!(first(builder.cache.all::<dist::Std>()), &[
968 compiler: Compiler { host: a, stage: 2 },
972 assert_eq!(first(builder.cache.all::<dist::Src>()), &[dist::Src]);
976 fn dist_with_targets() {
977 let build = Build::new(configure(&[], &["B"]));
978 let mut builder = Builder::new(&build);
979 builder.run_step_descriptions(&Builder::get_step_descriptions(Kind::Dist), &[]);
981 let a = INTERNER.intern_str("A");
982 let b = INTERNER.intern_str("B");
984 assert_eq!(first(builder.cache.all::<dist::Docs>()), &[
985 dist::Docs { stage: 2, host: a },
986 dist::Docs { stage: 2, host: b },
988 assert_eq!(first(builder.cache.all::<dist::Mingw>()), &[
989 dist::Mingw { host: a },
990 dist::Mingw { host: b },
992 assert_eq!(first(builder.cache.all::<dist::Rustc>()), &[
993 dist::Rustc { compiler: Compiler { host: a, stage: 2 } },
995 assert_eq!(first(builder.cache.all::<dist::Std>()), &[
997 compiler: Compiler { host: a, stage: 2 },
1001 compiler: Compiler { host: a, stage: 2 },
1005 assert_eq!(first(builder.cache.all::<dist::Src>()), &[dist::Src]);
1009 fn dist_with_hosts() {
1010 let build = Build::new(configure(&["B"], &[]));
1011 let mut builder = Builder::new(&build);
1012 builder.run_step_descriptions(&Builder::get_step_descriptions(Kind::Dist), &[]);
1014 let a = INTERNER.intern_str("A");
1015 let b = INTERNER.intern_str("B");
1017 assert_eq!(first(builder.cache.all::<dist::Docs>()), &[
1018 dist::Docs { stage: 2, host: a },
1019 dist::Docs { stage: 2, host: b },
1021 assert_eq!(first(builder.cache.all::<dist::Mingw>()), &[
1022 dist::Mingw { host: a },
1023 dist::Mingw { host: b },
1025 assert_eq!(first(builder.cache.all::<dist::Rustc>()), &[
1026 dist::Rustc { compiler: Compiler { host: a, stage: 2 } },
1027 dist::Rustc { compiler: Compiler { host: b, stage: 2 } },
1029 assert_eq!(first(builder.cache.all::<dist::Std>()), &[
1031 compiler: Compiler { host: a, stage: 2 },
1035 compiler: Compiler { host: a, stage: 2 },
1039 assert_eq!(first(builder.cache.all::<dist::Src>()), &[dist::Src]);
1043 fn dist_with_targets_and_hosts() {
1044 let build = Build::new(configure(&["B"], &["C"]));
1045 let mut builder = Builder::new(&build);
1046 builder.run_step_descriptions(&Builder::get_step_descriptions(Kind::Dist), &[]);
1048 let a = INTERNER.intern_str("A");
1049 let b = INTERNER.intern_str("B");
1050 let c = INTERNER.intern_str("C");
1052 assert_eq!(first(builder.cache.all::<dist::Docs>()), &[
1053 dist::Docs { stage: 2, host: a },
1054 dist::Docs { stage: 2, host: b },
1055 dist::Docs { stage: 2, host: c },
1057 assert_eq!(first(builder.cache.all::<dist::Mingw>()), &[
1058 dist::Mingw { host: a },
1059 dist::Mingw { host: b },
1060 dist::Mingw { host: c },
1062 assert_eq!(first(builder.cache.all::<dist::Rustc>()), &[
1063 dist::Rustc { compiler: Compiler { host: a, stage: 2 } },
1064 dist::Rustc { compiler: Compiler { host: b, stage: 2 } },
1066 assert_eq!(first(builder.cache.all::<dist::Std>()), &[
1068 compiler: Compiler { host: a, stage: 2 },
1072 compiler: Compiler { host: a, stage: 2 },
1076 compiler: Compiler { host: a, stage: 2 },
1080 assert_eq!(first(builder.cache.all::<dist::Src>()), &[dist::Src]);
1084 fn dist_with_target_flag() {
1085 let mut config = configure(&["B"], &["C"]);
1086 config.run_host_only = false; // as-if --target=C was passed
1087 let build = Build::new(config);
1088 let mut builder = Builder::new(&build);
1089 builder.run_step_descriptions(&Builder::get_step_descriptions(Kind::Dist), &[]);
1091 let a = INTERNER.intern_str("A");
1092 let b = INTERNER.intern_str("B");
1093 let c = INTERNER.intern_str("C");
1095 assert_eq!(first(builder.cache.all::<dist::Docs>()), &[
1096 dist::Docs { stage: 2, host: a },
1097 dist::Docs { stage: 2, host: b },
1098 dist::Docs { stage: 2, host: c },
1100 assert_eq!(first(builder.cache.all::<dist::Mingw>()), &[
1101 dist::Mingw { host: a },
1102 dist::Mingw { host: b },
1103 dist::Mingw { host: c },
1105 assert_eq!(first(builder.cache.all::<dist::Rustc>()), &[]);
1106 assert_eq!(first(builder.cache.all::<dist::Std>()), &[
1108 compiler: Compiler { host: a, stage: 2 },
1112 compiler: Compiler { host: a, stage: 2 },
1116 compiler: Compiler { host: a, stage: 2 },
1120 assert_eq!(first(builder.cache.all::<dist::Src>()), &[]);
1124 fn dist_with_same_targets_and_hosts() {
1125 let build = Build::new(configure(&["B"], &["B"]));
1126 let mut builder = Builder::new(&build);
1127 builder.run_step_descriptions(&Builder::get_step_descriptions(Kind::Dist), &[]);
1129 let a = INTERNER.intern_str("A");
1130 let b = INTERNER.intern_str("B");
1132 assert_eq!(first(builder.cache.all::<dist::Docs>()), &[
1133 dist::Docs { stage: 2, host: a },
1134 dist::Docs { stage: 2, host: b },
1136 assert_eq!(first(builder.cache.all::<dist::Mingw>()), &[
1137 dist::Mingw { host: a },
1138 dist::Mingw { host: b },
1140 assert_eq!(first(builder.cache.all::<dist::Rustc>()), &[
1141 dist::Rustc { compiler: Compiler { host: a, stage: 2 } },
1142 dist::Rustc { compiler: Compiler { host: b, stage: 2 } },
1144 assert_eq!(first(builder.cache.all::<dist::Std>()), &[
1146 compiler: Compiler { host: a, stage: 2 },
1150 compiler: Compiler { host: a, stage: 2 },
1154 assert_eq!(first(builder.cache.all::<dist::Src>()), &[dist::Src]);
1155 assert_eq!(first(builder.cache.all::<compile::Std>()), &[
1157 compiler: Compiler { host: a, stage: 0 },
1161 compiler: Compiler { host: a, stage: 1 },
1165 compiler: Compiler { host: a, stage: 2 },
1169 compiler: Compiler { host: a, stage: 1 },
1173 compiler: Compiler { host: a, stage: 2 },
1177 assert_eq!(first(builder.cache.all::<compile::Test>()), &[
1179 compiler: Compiler { host: a, stage: 0 },
1183 compiler: Compiler { host: a, stage: 1 },
1187 compiler: Compiler { host: a, stage: 2 },
1191 compiler: Compiler { host: a, stage: 1 },
1195 compiler: Compiler { host: a, stage: 2 },
1199 assert_eq!(first(builder.cache.all::<compile::Assemble>()), &[
1201 target_compiler: Compiler { host: a, stage: 0 },
1204 target_compiler: Compiler { host: a, stage: 1 },
1207 target_compiler: Compiler { host: a, stage: 2 },
1210 target_compiler: Compiler { host: b, stage: 2 },
1216 fn build_default() {
1217 let build = Build::new(configure(&["B"], &["C"]));
1218 let mut builder = Builder::new(&build);
1219 builder.run_step_descriptions(&Builder::get_step_descriptions(Kind::Build), &[]);
1221 let a = INTERNER.intern_str("A");
1222 let b = INTERNER.intern_str("B");
1223 let c = INTERNER.intern_str("C");
1225 assert!(!builder.cache.all::<compile::Std>().is_empty());
1226 assert!(!builder.cache.all::<compile::Assemble>().is_empty());
1227 assert_eq!(first(builder.cache.all::<compile::Rustc>()), &[
1229 compiler: Compiler { host: a, stage: 0 },
1233 compiler: Compiler { host: a, stage: 1 },
1237 compiler: Compiler { host: a, stage: 2 },
1241 compiler: Compiler { host: b, stage: 2 },
1245 compiler: Compiler { host: a, stage: 0 },
1249 compiler: Compiler { host: a, stage: 1 },
1253 compiler: Compiler { host: a, stage: 2 },
1257 compiler: Compiler { host: b, stage: 2 },
1262 assert_eq!(first(builder.cache.all::<compile::Test>()), &[
1264 compiler: Compiler { host: a, stage: 0 },
1268 compiler: Compiler { host: a, stage: 1 },
1272 compiler: Compiler { host: a, stage: 2 },
1276 compiler: Compiler { host: b, stage: 2 },
1280 compiler: Compiler { host: a, stage: 0 },
1284 compiler: Compiler { host: a, stage: 1 },
1288 compiler: Compiler { host: a, stage: 2 },
1292 compiler: Compiler { host: b, stage: 2 },
1296 compiler: Compiler { host: a, stage: 2 },
1300 compiler: Compiler { host: b, stage: 2 },
1307 fn build_with_target_flag() {
1308 let mut config = configure(&["B"], &["C"]);
1309 config.run_host_only = false;
1310 let build = Build::new(config);
1311 let mut builder = Builder::new(&build);
1312 builder.run_step_descriptions(&Builder::get_step_descriptions(Kind::Build), &[]);
1314 let a = INTERNER.intern_str("A");
1315 let b = INTERNER.intern_str("B");
1316 let c = INTERNER.intern_str("C");
1318 assert!(!builder.cache.all::<compile::Std>().is_empty());
1319 assert_eq!(first(builder.cache.all::<compile::Assemble>()), &[
1321 target_compiler: Compiler { host: a, stage: 0 },
1324 target_compiler: Compiler { host: a, stage: 1 },
1327 target_compiler: Compiler { host: b, stage: 1 },
1330 target_compiler: Compiler { host: a, stage: 2 },
1333 target_compiler: Compiler { host: b, stage: 2 },
1336 assert_eq!(first(builder.cache.all::<compile::Rustc>()), &[
1338 compiler: Compiler { host: a, stage: 0 },
1342 compiler: Compiler { host: a, stage: 1 },
1346 compiler: Compiler { host: a, stage: 0 },
1350 compiler: Compiler { host: a, stage: 1 },
1355 assert_eq!(first(builder.cache.all::<compile::Test>()), &[
1357 compiler: Compiler { host: a, stage: 0 },
1361 compiler: Compiler { host: a, stage: 1 },
1365 compiler: Compiler { host: a, stage: 2 },
1369 compiler: Compiler { host: b, stage: 2 },
1373 compiler: Compiler { host: a, stage: 0 },
1377 compiler: Compiler { host: a, stage: 1 },
1381 compiler: Compiler { host: a, stage: 2 },
1385 compiler: Compiler { host: b, stage: 2 },
1389 compiler: Compiler { host: a, stage: 2 },
1393 compiler: Compiler { host: b, stage: 2 },